Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create SQLite database in android

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 when app is first time installed it checks whether the database exist or not, if exists it updates it else if not then creates a new database.

further more I am making a DB class to facilitate my app,so I wont be creating an activity for my database creation.

if there are possible advices, please share with me

like image 439
Adil Bhatty Avatar asked Jun 14 '10 13:06

Adil Bhatty


People also ask

Can I use SQLite on Android?

Android SQLite is a very lightweight database which comes with Android OS. Android SQLite combines a clean SQL interface with a very small memory footprint and decent speed. For Android, SQLite is “baked into” the Android runtime, so every Android application can create its own SQLite databases.


2 Answers

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());    } 
like image 194
ArK Avatar answered Oct 04 '22 23:10

ArK


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.

like image 33
Janusz Avatar answered Oct 05 '22 01:10

Janusz