Pages

Thursday, 24 November 2011

Android Database

This sample code illustrates how we can use Android SQLite Database to store data in Android. Following example will give output as Saranga/22 since I have created a text view and set the out put to it. If you want to add your own fields, first drop the existing table using given source code.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class DBTest extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  SQLiteDatabase myDB= null;
  String TableName = "myTable";
  String Data="";
  /* Create a Database. */
  try {
   myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
   /* Create a Table in the Database. */
   myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");
   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Saranga', 22);");
   /*retrieve data from database */
   Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
   int Column1 = c.getColumnIndex("Field1");
   int Column2 = c.getColumnIndex("Field2");
   // Check if our result was valid.
   c.moveToFirst();
   if (c != null) {
    // Loop through all Results
    do {
     String Name = c.getString(Column1);
     int Age = c.getInt(Column2);
     Data =Data +Name+"/"+Age+"\n";
    }while(c.moveToNext());
   }
   TextView tv = new TextView(this);
   tv.setText(Data);
   setContentView(tv);
  }
  catch(Exception e) {
   Log.e("Error", "Error", e);
  } finally {
   if (myDB != null)
    myDB.close();
  }
 }
}




Tested with Android 2.3.3 Platform SDK.


If you are interested please refer Android User Interface Design to learn simple way to Designing interfaces.

No comments:

Post a Comment