· 8 years ago · Jul 04, 2018, 02:28 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 myDB = openOrCreateDatabase("myTestDb", SQLiteDatabase.CREATE_IF_NECESSARY, null);
30 save.setOnClickListener(new OnClickListener() {
31
32 public void onClick(View v) {
33 // TODO Auto-generated method stub
34 name = ed.getText().toString();
35
36 try {
37
38
39 /* Create a Table in the Database. */
40 myDB.execSQL("CREATE TABLE IF NOT EXISTS "
41 + TableName
42 + " (Field1 VARCHAR, Field2 INT(3));");
43
44 /* Insert data to a Table*/
45 myDB.execSQL("INSERT INTO "
46 + TableName
47 + " (Field1, Field2)"
48 + " VALUES ('" + name + "' , 20);");
49
50 /*retrieve data from database */
51 Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
52
53 int Column1 = c.getColumnIndex("Field1");
54 int Column2 = c.getColumnIndex("Field2");
55
56 // Check if our result was valid.
57 c.moveToFirst();
58 if (c != null) {
59 // Loop through all Results
60 do {
61 String Name = c.getString(Column1);
62 int Age = c.getInt(Column2);
63 Data =Data +Name+"/"+Age+"\n";
64 }while(c.moveToNext());
65 }
66
67 tv.setText(Data);
68
69 }
70 catch(Exception e) {
71 Log.e("Error", "Error", e);
72 } finally {
73 if (myDB != null)
74 myDB.close();
75 }
76 }
77
78
79
80
81
82
83});
84
85 }
86}