first to create a database
need to write a class as follow
public class SQLiteDB extends SQLiteOpenHelper {
public static final String CREATE_DB = "create table data ( "+
"id integer primary key autoincrement, "+
"name text)";
private Context mContext;
public SQLiteDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_DB);
Toast.makeText(mContext, "the table has been created", Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
then we can use it
private SQLiteDB sqLiteDB ;
sqLiteDB = new SQLiteDB(mContext, "sqldata.db", null, 1);
then this step would create a new database, just once. would not create later.
sqLiteDB.getWritableDatabase();
2/ write to database
SQLiteDatabase db = sqLiteDB.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "firstone");
db.insert("data" , null, values);
values.clear();
3/ read database
SQLiteDatabase db = sqLiteDB.getReadableDatabase();
// Cursor cursor = db.query("data",);
Cursor cursor1 = db.rawQuery("select * from data", new String[]{});
List<String> names = new ArrayList<String>();
while(cursor1.moveToNext())
{
names.add( cursor1.getString(1));
}
In summary:
database opereations–
1/ create,
db.execSQL(CREATE_DB); on class database override oncreate;
2/ write,
ContentValues values = new ContentValues();
values.put("key", "value");-->db.insert("table",null, values);
3/ query
Cursor cursor = db.rawQuery("SQL", new String[]{});
cursor.getString(columns);/getBoolean or sth.
4/ delete
db.delete("Book", "pages > ?", new String[] { "500" });
5/ update
values.put("price", 10.99);
db.update("Book", values, "name = ?", new String[] { "The Da
Vinci Code" });