Android bundle sqlite database on application. Create sqlite database on first application invoke.
How to setup a default sqlite database structure with data in an android application. Add this class and initialize it in your main class th...
https://www.czetsuyatech.com/2010/06/android-bundle-sqlite-database-on.html
How to setup a default sqlite database structure with data in an android application.
Add this class and initialize it in your main class that extends Activity.
How to call in your main class
Add this class and initialize it in your main class that extends Activity.
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataHelper {
private static final String DATABASE_NAME = "kurenai.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_KURENAI = "kurenai";
private Context context;
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
openHelper.getWritableDatabase();
}
private class OpenHelper extends SQLiteOpenHelper {
public OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = String.format("SELECT name FROM sqlite_master WHERE type='table' AND name='%s'", TABLE_KURENAI);
Cursor c = db.rawQuery(sql, null);
try {
if(c.getCount() == 0) {
sql = "CREATE TABLE " + TABLE_KURENAI + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)";
db.execSQL(sql);
}
} finally {
c.close();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Sqlite", "Upgrading database, this process will destroy all data.");
onCreate(db);
}
}
}
How to call in your main class
public class SqliteDemo extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataHelper dh = new DataHelper(this);
}
}
Post a Comment