Create SQLite database in android Create SQLite database in android sqlite sqlite

Create SQLite database in android


Better example is here

 try {   myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);   /* Create a Table in the Database. */   myDB.execSQL("CREATE TABLE IF NOT EXISTS "     + TableName     + " (Field1 VARCHAR, Field2 INT(3));");   /* Insert data to a Table*/   myDB.execSQL("INSERT INTO "     + TableName     + " (Field1, Field2)"     + " VALUES ('Saranga', 22);");   /*retrieve data from database */   Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);   int Column1 = c.getColumnIndex("Field1");   int Column2 = c.getColumnIndex("Field2");   // Check if our result was valid.   c.moveToFirst();   if (c != null) {    // Loop through all Results    do {     String Name = c.getString(Column1);     int Age = c.getInt(Column2);     Data =Data +Name+"/"+Age+"\n";    }while(c.moveToNext());   }


If you want to keep the database between uninstalls you have to put it on the SD Card. This is the only place that won't be deleted at the moment your app is deleted. But in return it can be deleted by the user every time.

If you put your DB on the SD Card you can't use the SQLiteOpenHelper anymore, but you can use the source and the architecture of this class to get some ideas on how to implement the creation, updating and opening of a databse.


    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});        }}