Jas*_*son 4 sqlite android arraylist
我是Android开发的新手,无法弄清楚如何从我database/table的数据库读取.现在我有:
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();
}
Run Code Online (Sandbox Code Playgroud)
我怎么把它读成一个arraylist?
这是一个代码,向您展示如何从数据库查询中获取ArrayList.
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;
}
Run Code Online (Sandbox Code Playgroud)
如果在"aColumn"中提供null,它将为您提供所有列.我希望它会有所帮助.
//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();
Run Code Online (Sandbox Code Playgroud)
这是如何从Cursor创建arrayList的示例.
这里有一个类名称Calllog,它包含fileds和setter以及getter方法的列表.在这里,我使用Cursor制作了一个Calllog对象的ArrayList
| 归档时间: |
|
| 查看次数: |
8041 次 |
| 最近记录: |