Friday, January 8, 2010

Lập trình database trên android

Để các bạn lập trình được với các ứng dụng cần dùng đến cơ sở dữ liệu trên android mình xin giới thiệu với các bạn sơ qua về lập trình database trên android:
Thật tuyệt vời khi mà trên android OS đã hỗ trợ chúng ta SQLite:
1, Việc đầu tiên bạn cần làm với database là tạo một cơ sở dữ liệu: Ở đây nó chỉ là một file cơ sở dữ liệu:
private final String MY_DATABASE_NAME = "myAndroidDB";
private final String MY_DATABASE_TABLE = "Member";
SQLiteDatabase myDB = null;
try {
/* Create the Database (no Errors if it already exists) */
this.createDatabase(MY_DATABASE_NAME, 1, MODE_PRIVATE, null);



2, Bạn đã tạo database roài giờ mở nó thế nào nhỉ:

/* Open the DB and remember it */
myDB = this.openDatabase(MY_DATABASE_NAME, null);



3, Tiếp đến bạn tạo một table đơn giản:

/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ MY_DATABASE_TABLE
+ " (LastName VARCHAR, FirstName VARCHAR,"
+ " Country VARCHAR, Age INT(3));");



4, Giờ ta insert thử vào database xem sao nhỉ

/* Add two DataSets to the Table. */
myDB.execSQL("INSERT INTO "
+ MY_DATABASE_TABLE
+ " (LastName, FirstName, Country, Age)"
+ " VALUES ('Nguyễn', 'Tân', 'VietNam', 24);");
myDB.execSQL("INSERT INTO "
+ MY_DATABASE_TABLE
+ " (LastName, FirstName, Country, Age)"
+ " VALUES ('Nguyễn', 'Dung', 'VietNam', 23);");



5, Có dữ liệu roài giờ truy vấn thử xem sao nhỉ:

/* Query for some results with Selection and Projection. */
Cursor c = myDB.query("SELECT FirstName,Age" +
" FROM " + MY_DATABASE_TABLE
+ " WHERE Age > 10 LIMIT 7;",
null);



6, Sử dụng hàm getColumnIndex(String) để lấy thông tin nhé:

/* Get the indices of the Columns we will need */
int firstNameColumn = c.getColumnIndex("FirstName");
int ageColumn = c.getColumnIndex("Age");

/* Check if our result was valid. */
if (c != null) {
/* Check if at least one Result was returned. */
if (c.first()) {
int i = 0;
/* Loop through all Results */
do {
i++;
/* Retrieve the values of the Entry
* the Cursor is pointing to. */
String firstName = c.getString(firstNameColumn);
int age = c.getInt(ageColumn);
/* We can also receive the Name
* of a Column by its Index.
* Makes no sense, as we already
* know the Name, but just to shwo we can Wink */
String ageColumName = c.getColumnName(ageColumn);

/* Add current Entry to results. */
results.add("" + i + ": " + firstName
+ " (" + ageColumName + ": " + age + ")");
} while (c.next());
}
}


7, Sau khi làm việc với database bạn hãy đóng nó lại nhé:

} catch (FileNotFoundException e) {
} finally {
if (myDB != null)
myDB.close();
}



8, Cuối cùng bạn lấy thông tin ra roài giờ hiển thị nó thui nhỉ:
this.setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1_small, results));
}
}

No comments:

Post a Comment