· 8 years ago · Jul 04, 2018, 02:34 AM
1package com.db;
2
3import android.app.Activity;
4import android.database.Cursor;
5import android.database.sqlite.SQLiteDatabase;
6import android.os.Bundle;
7import android.util.Log;
8import android.view.View;
9import android.view.View.OnClickListener;
10import android.widget.Button;
11import android.widget.EditText;
12import android.widget.TextView;
13
14public class DBTest extends Activity {
15 /** Called when the activity is first created. */
16 SQLiteDatabase myDB= null; String Data="";String name ;
17 @Override
18 public void onCreate(Bundle savedInstanceState) {
19 super.onCreate(savedInstanceState);
20 setContentView(R.layout.main);
21 ;
22 final String TableName = "myTable";
23 Button save;
24 final EditText ed;
25
26 ed = (EditText)findViewById(R.id.editText1);
27 save = (Button)findViewById(R.id.button1);
28 final TextView tv = (TextView)findViewById(R.id.textView1);
29
30
31 save.setOnClickListener(new Button.OnClickListener() {
32
33 public void onClick(View v) {
34 // TODO Auto-generated method stub
35
36
37 try {
38 myDB = openOrCreateDatabase("myTestDb", SQLiteDatabase.CREATE_IF_NECESSARY, null);
39 name = ed.getText().toString();
40 /* Create a Table in the Database. */
41 myDB.execSQL("CREATE TABLE IF NOT EXISTS "
42 + TableName
43 + " (Field1 VARCHAR, Field2 INT(3));");
44
45 /* Insert data to a Table*/
46 myDB.execSQL("INSERT INTO "
47 + TableName
48 + " (Field1, Field2)"
49 + " VALUES ('" + name + "' , 20);");
50
51 /*retrieve data from database */
52 Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
53
54 int Column1 = c.getColumnIndex("Field1");
55 int Column2 = c.getColumnIndex("Field2");
56
57 // Check if our result was valid.
58 c.moveToFirst();
59 if (c != null) {
60 // Loop through all Results
61 do {
62 String Name = c.getString(Column1);
63 int Age = c.getInt(Column2);
64 Data =Data +Name+"/"+Age+"\n";
65 }while(c.moveToNext());
66 }
67
68 tv.setText(Data);
69
70 }
71 catch(Exception e) {
72 Log.e("Error", "Error", e);
73 } finally {
74 if (myDB != null)
75 myDB.close();
76 }
77 }
78
79
80
81
82
83
84});
85
86 }
87}