· 8 years ago · Aug 04, 2018, 03:26 PM
1How to fetch the data from the database by using this demo?
2public ArrayList<User> getUsersList() {
3
4 ArrayList<User> userList = null;
5 Cursor cursor = null;
6
7 try {
8
9 String queryString = "SELECT _id , name, address, type FROM User";
10
11 cursor = myDataBase.rawQuery(queryString, null);
12
13 if (cursor != null && cursor.moveToFirst()) {
14 userList = new ArrayList<User>();
15 do {
16 User nextUser = new User(cursor.getInt(0),
17 cursor.getString(1), cursor.getString(2) , cursor.getString(3));
18 userList.add(nextUser);
19 } while (cursor.moveToNext());
20 }
21 } catch (Exception e) {
22 e.printStackTrace();
23 userList = null;
24 } finally {
25 if (cursor != null && !cursor.isClosed()) {
26 cursor.deactivate();
27 cursor.close();
28 cursor = null;
29 }
30 if(myDataBase != null){
31 myDataBase.close();
32 }
33 }
34 return userList;
35 }
36
37package com.collabera.labs.sai.db;
38
39import java.util.ArrayList;
40
41import android.app.ListActivity;
42import android.database.Cursor;
43import android.database.sqlite.SQLiteDatabase;
44import android.database.sqlite.SQLiteException;
45import android.os.Bundle;
46import android.util.Log;
47import android.widget.ArrayAdapter;
48
49public class CRUDonDB extends ListActivity {
50
51 private final String SAMPLE_DB_NAME = "myFriendsDb";
52 private final String SAMPLE_TABLE_NAME = "friends";
53
54 /** Called when the activity is first created. */
55 @Override
56 public void onCreate(Bundle savedInstanceState) {
57 super.onCreate(savedInstanceState);
58
59
60 ArrayList<String> results = new ArrayList<String>();
61 SQLiteDatabase sampleDB = null;
62
63 try {
64 sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
65
66 sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
67 SAMPLE_TABLE_NAME +
68 " (LastName VARCHAR, FirstName VARCHAR," +
69 " Country VARCHAR, Age INT(3));");
70
71 sampleDB.execSQL("INSERT INTO " +
72 SAMPLE_TABLE_NAME +
73 " Values ('Makam','Sai Geetha','India',25);");
74 sampleDB.execSQL("INSERT INTO " +
75 SAMPLE_TABLE_NAME +
76 " Values ('Chittur','Raman','India',25);");
77 sampleDB.execSQL("INSERT INTO " +
78 SAMPLE_TABLE_NAME +
79 " Values ('Solutions','Collabera','India',20);");
80
81 Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM " +
82 SAMPLE_TABLE_NAME +
83 " where Age > 10 LIMIT 5", null);
84
85 if (c != null ) {
86 if (c.moveToFirst()) {
87 do {
88 String firstName = c.getString(c.getColumnIndex("FirstName"));
89 int age = c.getInt(c.getColumnIndex("Age"));
90 results.add("" + firstName + ",Age: " + age);
91 }while (c.moveToNext());
92 }
93 }
94
95 this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
96
97 } catch (SQLiteException se ) {
98 Log.e(getClass().getSimpleName(), "Could not create or Open the database");
99 } finally {
100 if (sampleDB != null)
101 sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
102 sampleDB.close();
103 }
104 }
105}