问题
I'm relatively new to Android and I was making a To-Do List application. I have a database containing a column of tasks. How can I put these tasks into an ArrayList and display it ?
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.query(TaskContract.TABLE, new String[]{TaskContract.Columns._ID,TaskContract.Columns.TASK}, null, null, null, null, null);
arrayListToDo = new ArrayList<String>();
arrayAdapterToDo = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayListToDo);
ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
listViewToDo.setAdapter(arrayAdapterToDo);
回答1:
Try this code
while (cursor.moveToNext()) {
arrayListToDo.add(cursor.getString(cursor.getColumnIndex("Your column name")));
}
回答2:
You can get the data in Array list :-
ArrayList<String> arrayListToDo= new ArrayList<String>();
//your query will returns cursor
if (cursor.moveToFirst()) {
do {
arrayListToDo.add(get you string from cursor);
} while (cursor.moveToNext());
}
now add this aray list to your Adapter.
回答3:
get list data from database this is only overview
ArrayList<String> data = databaseObject.GetList();
ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
arrayAdapterToDo = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listViewToDo.setAdapter(arrayAdapterToDo);
ArrayList<String> GetList()
{
ArrayList<String> arrayListtemp= new ArrayList<String>();
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.query(TaskContract.TABLE, new String[]{TaskContract.Columns._ID,TaskContract.Columns.TASK}, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
arrayListtemp.add("");// added your table value from database
} while (cursor.moveToNext());
}
return arrayListtemp;
}
来源:https://stackoverflow.com/questions/27523669/how-to-add-data-from-an-sqlite-database-into-an-arraylist-android