Reading from a database in android for archaist

I am very new to Android development and cannot figure out how to read from my database/table in arrayList. Right now I have:

  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(); } 

How did I read this in an arraylist?

+4
source share
2 answers

Here is the code that shows you how to get an ArrayList request from a database.

 public ArrayList<String> GetAllValues(String aTable,String[] aColumn) { ArrayList<String> list = new ArrayList<String>(); Cursor cursor = sqlDB.query(aTable, aColumn, null, null, null, null, null); if (cursor.moveToFirst()) { do { list.add(cursor.getString(0)); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } return list; } 

If you specify null in "aColumn", it will provide you with all the columns. Hope this helps.

+7
source
 //ArrayList of Calllog class objects ArrayList<CallLog> arrCallLogs = null; Cursor curCalllog = myDB.rawQuery("SELECT * FROM " + TableName , null); if(curCalllog != null && curCalllog.moveToFirst()) { arrCallLogs = new ArrayList<CallLog>(); while (curCalllog.isAfterLast() == false) { //Calllog is a class with list of fileds CallLog callLog = new CallLog(); callLog.setId(curCalllog.getLong(curCalllog.getColumnIndex(KEY_ROWID))); callLog.setName(curCalllog.getString(curCalllog.getColumnIndex(KEY_NAME))); callLog.setNumber(curCalllog.getString(curCalllog.getColumnIndex(KEY_NUMBER))); callLog.setNumberType(curCalllog.getInt(curCalllog.getColumnIndex(KEY_NUMBERTYPE))); callLog.setCallType(curCalllog.getInt(curCalllog.getColumnIndex(KEY_CALLTYPE))); callLog.setDatetime(curCalllog.getLong(curCalllog.getColumnIndex(KEY_DATETIME))); callLog.setDuration(curCalllog.getLong(curCalllog.getColumnIndex(KEY_DURATION))); callLog.set_new(curCalllog.getInt(curCalllog.getColumnIndex(KEY_NEW))); arrCallLogs.add(callLog); curCalllog.moveToNext(); } } curCalllog.close(); myDB.close(); 

This is an example of how you can make an arrayList from Cursor.

Here is the name of the Calllog class, which has a list of filed and setter and getter labels. Here I made an ArrayList of Calllog objects using Cursor

+5
source

All Articles