SQLite Database in android
Hii everybody ,
I am noob at android and need some help...
I am developing an app which requires me to write to an SQLiteDatabase in one activity and access it from another activity . I a开发者_JAVA技巧m facing a problem implementing this. Any suggestions/ideas as to how we can share the database across multiple activities ...?
I'd recommend you to use the SQLiteOpenHelper class.
Simply use the same database name consistently across your activities, it should not cause any problem.
SQLiteOpenHelper helper = new SQLiteOpenHelper(
context, R.string.db_name, null, 1);
SQLiteDatabase db = helper.getWritableDatabase();
The issue of accessing the same database two different activities can be handled in a few different ways.
The simplest, which should work for your case, is to create a new class that extends SQLITEOpenHelper and instantiate that class from both activities.
Android has no problem with multiple Activities or processes accessing the SQlite database simultaneously.
Simply you can make a common Class for DataBase and use it by creating object.
public class DbOperation extends SQLiteOpenHelper{
public static final String name="mydb.db";
public static final String MainTab="MainTab";
public static final String ID="_ID";
public static final String LevelName="LevelName";
int version =2;
public DbOperation(Context context, String name, CursorFactory factory,
int version) {
super(context, name,null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String str="CREATE TABLE "+MainTab+"("+ID+" integer primary key autoincrement,"+LevelName+" text not null unique key)";
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Use this data base in any activity in below way
DbOperation ob=new DbOperation ();
SQLiteDatabase db=new SQLiteaDatabase();
db=ob.getWritableDataBase();
and now you can use operation like query,delete,update
Cursor cur=db.query(Table_name,null,null,null,null); etc
精彩评论