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