Monday, February 27, 2012

How to use ContentValue in Android Sqlite?



Create the table with Helper Class first.........

public class DbHelper extends SQLiteOpenHelper {
    public DbHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
         String sql = "create table Games " +"(PlayerId integer primary key, " +
                 "Result integer, " +"PlayTime integer, " +"Difficulty integer); ";
     db.execSQL(sql);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      if (oldVersion == 1 && newVersion == 2) {
        String sql = "drop table Games;";
        db.execSQL(sql);
        sql = "create table Games " + "(Id integer primary key, "
                + "PlayerId integer, " + "Result integer, "
                + "PlayTime integer, " + "Difficulty integer); ";
        db.execSQL(sql); //OR // onCreate(db);
        }
    }
}


Now for adding data into the table with the help of ContentValue create another class as below....

public class DataLayer {

    private DbHelper _dbHelper;

    public DataLayer(Context c) {
        _dbHelper = new DbHelper(c);
    }
    public void AddGame(int playerId, int result, int playTime, int difficulty) {
        SQLiteDatabase db = _dbHelper.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put("PlayerId", playerId);
            values.put("Result", result);
            values.put("PlayTime", playTime);
            values.put("Difficulty", difficulty);
            db.insert("Games", "", values);
        } finally {
            if (db != null)
                db.close();
        }
    }



     public ArrayList<GameResult> SelectGames() {

    SQLiteDatabase db = _dbHelper.getReadableDatabase();
    try {
        ArrayList<GameResult> results = new ArrayList<GameResult>();
        Cursor c = db.rawQuery("select * from Games", null);
        if (c.getCount() > 0) {
            c.moveToFirst();
            do {
                results.add(new GameResult(
                        c.getInt(c.getColumnIndex("PlayerId")),
                        c.getInt(c.getColumnIndex("Result")),
                        c.getInt(c.getColumnIndex("PlayTime")),
                        c.getInt(c.getColumnIndex("Difficulty"))));
            } while (c.moveToNext());
        }
        return results;
    } finally {
        if (db != null)
            db.close();
    }
    }

    public int UpdateGames() {
    SQLiteDatabase db = _dbHelper.getWritableDatabase();
    try {
        Random r = new Random();
        ContentValues values = new ContentValues();
        values.put("PlayTime", r.nextInt());

        int affected = db.update("Games", values, null, null);
               //OR
       //mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + r.nextInt(), null) > 0;

        return affected;
    } finally {
        if (db != null)
            db.close();
    }
    }

     public int DeleteGames() {
    SQLiteDatabase db = _dbHelper.getWritableDatabase();
    try {
        int recordsDeleted = db.delete("Games", "1", null);
        return recordsDeleted;
    } finally {
        if (db != null)
            db.close();
    }
    }
}


Also create a class for storing the class type arrayList having all the records in it ..........



public class GameResult {

    public GameResult(int playerId, int result, int playTime, int difficulty) {
        PlayerId = playerId;
        Result = result;
        PlayTime = playTime;
        Difficulty = difficulty;
    }

    public int PlayerId;
    public int Result;
    public int PlayTime;
    public int Difficulty;
}



Now for adding the data just write down the following code from any class in application......

DataLayer d = new DataLayer(getBaseContext());


For inserting value we can use below line...
d.AddGame(1, 2, 3, 4);


For selecting all resords we can use following line....

ArrayList<GameResult> results = d.SelectGames();

For updating use below line....
d.UpdateGames();

For deleting game record...
d.DeleteGames();



No comments:

Post a Comment