Trabla: Android SQLite simple example
Solving:
1. Create default Android project with single activity
2. Create new Class in /src folder - DbHelper - copy code below
package com.samuraikit.test; // <- change to your package !!!!
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "mydb.db";
public static final int DB_VERSION = 4;
public static final String SQL_CREATE_TABLE = "CREATE TABLE mytable( id integer PRYMARY KEY AUTOINCEMENT, name TEXT )";
public static final String SQL_DROP_TABLE = "DROP TABLE IF EXISTS mytable";
public DbHelper(Context context) {
super(context, DbHelper.DB_NAME, null, DbHelper.DB_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DbHelper.SQL_CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL(DbHelper.SQL_DROP_TABLE);
this.onCreate(db);
}
}
3. Insert following code in Main Activity Class
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
long newRowId;
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues row = new ContentValues();
row.put("id", "1");
row.put("name", "Dart Weider");
newRowId = db.insert( "mytable", null,row);
row = new ContentValues();
row.put("id", "2");
row.put("name", "Master Yoda");
newRowId = db.insert( "mytable", null,row);
row = new ContentValues();
row.put("id", "3");
row.put("name", "Obi-Wan Kenobi");
newRowId = db.insert( "mytable", null,row);
Toast toast = Toast.makeText(this,
String.valueOf(newRowId), Toast.LENGTH_LONG);
toast.show();
db.close();
//Read from DB
db = dbHelper.getReadableDatabase();
String[] projection = {"id","name"};
Cursor c = db.query(
"mytable", // The table to query
projection, // The columns to return
"", // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
"" // The sort order
);
c.moveToFirst();
while(!c.isAfterLast()){
String name = c.getString(
c.getColumnIndexOrThrow("name")
);
long id = c.getLong(
c.getColumnIndexOrThrow("id")
);
toast = Toast.makeText(this, "ID:"+String.valueOf(id)+"|Name:"+
name, Toast.LENGTH_LONG);
toast.show();
c.moveToNext();
}
db.close();
}
No comments:
Post a Comment