I want to create a SQLite database in my app, which contains three tables, I will add data into tables and will use them later on.
but I like to keep database ,as if
A simple database example to insert Todo List of day today life in DB and get list of all todo list.
public class MyDatabaseHelper extends SQLiteOpenHelper {
// Logcat tag
private static final String LOG = "DatabaseHelper";
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "SQLiteDemoDB";
// Table Names
private static final String TABLE_TODO = "todos";
// column names
private static final String KEY_ID = "id";
private static final String KEY_CREATED_AT = "created_at";
private static final String KEY_TODO = "todoDescr";
// *********************************************************************************************
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TODO);
}
// Upgrading database **************************************************************************
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);
// Create tables again
onCreate(db);
}
// Creating Table TABLE_TEAM
String CREATE_TABLE_TODO = "CREATE TABLE " + TABLE_TODO + "("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_TODO + " text, "
+ KEY_CREATED_AT + " text" + ")";
// insert values of todo
public boolean InsertTodoDetails(String todo, String createdAt) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_TODO, todo);
contentValues.put(KEY_CREATED_AT, createdAt);
long rowInserted = db.insert(TABLE_TODO, null, contentValues);
db.close();
return true;
}
// Select values of todo
public Cursor GetAllTodoDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_TODO;
Cursor mcursor = db.rawQuery(query, null);
if (mcursor != null) {
mcursor.moveToFirst();
}
return mcursor;
}
}
My activity To save and get the record.
public class MyDbActivity extends AppCompatActivity {
@Bind(R.id.edt_todo)
EditText edtTodo;
@Bind(R.id.btn_save)
Button btnSave;
MyDatabaseHelper db;
@Bind(R.id.btn_getTodo)
Button btnGetTodo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_db);
ButterKnife.bind(this);
// creating database object
db = new MyDatabaseHelper(this);
}
@OnClick(R.id.btn_save)
public void onViewClicked() {
String datetime = "";
try {
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
datetime = dateformat.format(new Date());
} catch (Exception e) {
e.printStackTrace();
}
db.InsertTodoDetails(edtTodo.getText().toString().trim(), datetime);
}
@OnClick(R.id.btn_getTodo)
public void onGetTodoClicked() {
String todos = "";
Cursor TodoList = db.GetAllTodoDetails();
if (TodoList.moveToFirst()) {
do {
if (todos.equals("")) {
todos = TodoList.getString(TodoList.getColumnIndex("todoDescr"));
} else {
todos = todos + ", " + TodoList.getString(TodoList.getColumnIndex("todoDescr"));
}
// do what ever you want here
} while (TodoList.moveToNext());
}
TodoList.close();
Toast.makeText(this, "" + todos, Toast.LENGTH_SHORT).show();
}
}
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MyDb.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE_FRIDGE_ITEM = "create table FridgeItem(id integer primary key autoincrement,f_id text not null,food_item text not null,quantity text not null,measurement text not null,expiration_date text not null,current_date text not null,flag text not null,location text not null);";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_FRIDGE_ITEM);
}
// Method is called during an upgrade of the database,
@Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
Log.w(MyDatabaseHelper.class.getName(),"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS FridgeItem");
onCreate(database);
}
}
public class CommentsDataSource {
private MyDatabaseHelper dbHelper;
private SQLiteDatabase database;
public String stringArray[];
public final static String FOOD_TABLE = "FridgeItem"; // name of table
public final static String FOOD_ITEMS_DETAILS = "FoodDetails"; // name of table
public final static String P_ID = "id"; // pid
public final static String FOOD_ID = "f_id"; // id value for food item
public final static String FOOD_NAME = "food_item"; // name of food
public final static String FOOD_QUANTITY = "quantity"; // quantity of food item
public final static String FOOD_MEASUREMENT = "measurement"; // measurement of food item
public final static String FOOD_EXPIRATION = "expiration_date"; // expiration date of food item
public final static String FOOD_CURRENTDATE = "current_date"; // date of food item added
public final static String FLAG = "flag";
public final static String LOCATION = "location";
/**
*
* @param context
*/
public CommentsDataSource(Context context) {
dbHelper = new MyDatabaseHelper(context);
database = dbHelper.getWritableDatabase();
}
public long insertFoodItem(String id, String name,String quantity, String measurement, String currrentDate,String expiration,String flag,String location) {
ContentValues values = new ContentValues();
values.put(FOOD_ID, id);
values.put(FOOD_NAME, name);
values.put(FOOD_QUANTITY, quantity);
values.put(FOOD_MEASUREMENT, measurement);
values.put(FOOD_CURRENTDATE, currrentDate);
values.put(FOOD_EXPIRATION, expiration);
values.put(FLAG, flag);
values.put(LOCATION, location);
return database.insert(FOOD_TABLE, null, values);
}
public long insertFoodItemsDetails(String id, String name,String quantity, String measurement, String currrentDate,String expiration) {
ContentValues values = new ContentValues();
values.put(FOOD_ID, id);
values.put(FOOD_NAME, name);
values.put(FOOD_QUANTITY, quantity);
values.put(FOOD_MEASUREMENT, measurement);
values.put(FOOD_CURRENTDATE, currrentDate);
values.put(FOOD_EXPIRATION, expiration);
return database.insert(FOOD_ITEMS_DETAILS, null, values);
}
public Cursor selectRecords(String id) {
String[] cols = new String[] { FOOD_ID, FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION,FLAG,LOCATION,P_ID};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, P_ID+"=?", new String[]{id}, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor; // iterate to get each value.
}
public Cursor selectAllName() {
String[] cols = new String[] { FOOD_NAME};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, null, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor; // iterate to get each value.
}
public Cursor selectAllRecords(String loc) {
String[] cols = new String[] { FOOD_ID, FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION,FLAG,LOCATION,P_ID};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, LOCATION+"=?", new String[]{loc}, null, null, null, null);
int size=mCursor.getCount();
stringArray = new String[size];
int i=0;
if (mCursor != null) {
mCursor.moveToFirst();
FoodInfo.arrayList.clear();
while (!mCursor.isAfterLast()) {
String name=mCursor.getString(1);
stringArray[i]=name;
String quant=mCursor.getString(2);
String measure=mCursor.getString(3);
String expir=mCursor.getString(4);
String id=mCursor.getString(7);
FoodInfo fooditem=new FoodInfo();
fooditem.setName(name);
fooditem.setQuantity(quant);
fooditem.setMesure(measure);
fooditem.setExpirationDate(expir);
fooditem.setid(id);
FoodInfo.arrayList.add(fooditem);
mCursor.moveToNext();
i++;
}
}
return mCursor; // iterate to get each value.
}
public Cursor selectExpDate() {
String[] cols = new String[] {FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, null, null, null, null, FOOD_EXPIRATION, null);
int size=mCursor.getCount();
stringArray = new String[size];
if (mCursor != null) {
mCursor.moveToFirst();
FoodInfo.arrayList.clear();
while (!mCursor.isAfterLast()) {
String name=mCursor.getString(0);
String quant=mCursor.getString(1);
String measure=mCursor.getString(2);
String expir=mCursor.getString(3);
FoodInfo fooditem=new FoodInfo();
fooditem.setName(name);
fooditem.setQuantity(quant);
fooditem.setMesure(measure);
fooditem.setExpirationDate(expir);
FoodInfo.arrayList.add(fooditem);
mCursor.moveToNext();
}
}
return mCursor; // iterate to get each value.
}
public int UpdateFoodItem(String id, String quantity, String expiration){
ContentValues values=new ContentValues();
values.put(FOOD_QUANTITY, quantity);
values.put(FOOD_EXPIRATION, expiration);
return database.update(FOOD_TABLE, values, P_ID+"=?", new String[]{id});
}
public void deleteComment(String id) {
System.out.println("Comment deleted with id: " + id);
database.delete(FOOD_TABLE, P_ID+"=?", new String[]{id});
}
}