Marcações

Android soup with SQLiteDatabase, ListActivity and Options Menu

Have some Android soup made with SQLiteDatabase, ListActivity and Options Menu as ingredients! In this latest encounter with Android I create a small database that holds a list of Train numbers and names. The contents of this list is displayed to the user. The user is also given a menu to “add”, “delete” and “deleteAll” the records.

To get started I create a SqlOpenHelper class which extends the SQLiteOpenHelper. This class has the methods to create the SQLiteDatabase.

publicvoid onCreate(SQLiteDatabase db) {

createDatabase(db);

}

publicvoid createDatabase(SQLiteDatabase db) {

//Create TRAIN_TABLE

String CREATE_TRAIN_TABLE = "CREATE TABLE IF NOT EXISTS " +

TRAINS_TABLE + "(" + TRAIN_ID + " INTEGER PRIMARY KEY," +

TRAIN_NO + " INTEGER , " + TRAIN_NAME + " TEXT" + ")";

Log.d("Creating: " , CREATE_TRAIN_TABLE);

db.execSQL(CREATE_TRAIN_TABLE);

}

Besides there are methods to

1) To add a train record

// Add a train method

publicvoid addTrain(int trainNo,String trainName) {

SQLiteDatabase db =this.getWritableDatabase();

ContentValues values =new ContentValues();

values.put(TRAIN_NO, trainNo);

values.put(TRAIN_NAME, trainName);

// Insert a new row

db.insert(TRAINS_TABLE,null, values);

db.close(); // Closing database connection

}

2) To delete a train record

// Delete a single train

publicvoid deleteTrain(Train train) {

SQLiteDatabase db =this.getWritableDatabase();

db.delete(TRAINS_TABLE,TRAIN_ID + " = ?",

new String[] { String.valueOf(train.getID()) });

db.close();

}

and to display all the trains in the database. The entire list is returned as a List.