雖然這個問題在這裏已經問了很多次,但我找不到適合我的代碼的正確答案。我意識到它可能很小,但我似乎無法找到問題。從SQLite顯示記錄到ListView中
這是我的RunDatabase類。
// Getting All Contacts
public List<RecordLists> getAllContacts() {
List<RecordLists> contactList = new ArrayList<RecordLists>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
RecordLists contact = new RecordLists();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setUserName(cursor.getString(1));
contact.setFirstName(cursor.getString(2));
contact.setLastName(cursor.getString(3));
contact.setPassword(cursor.getString(4));
String name = cursor.getString(1) +"\n"+ cursor.getString(2) + "\n" + cursor.getString(3) + "\n" + cursor.getString(4);
AllRecords.ArrayofName.add(name);
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
現在我在另一個活動是AllRecords.java調用這個和代碼是:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
try {
RunDatabase db = new RunDatabase(this);
// Reading all contacts
Log.d("Reading: ", "Reading all Records..");
List<RecordLists> contacts = db.getAllContacts();
ArrayAdapter<RecordLists> adapter = new ArrayAdapter<RecordLists>(this, R.layout.records, contacts);
for (RecordLists cn : contacts)
{
final String log = "Id: "+cn.getId()+ " ,UserName " + cn.getUserName() + " ,FirstName: " + cn.getFirstName() + " ,LastName: " + cn.getLastName() + " ,Password " + cn.getPassword();
// Writing Contacts to log
Log.d("Name: ", log);
RecordList = (ListView) findViewById(R.id.list_View);
RecordList.setEmptyView(findViewById(android.R.id.empty));
RecordList.setAdapter(adapter);
如果tou使用遊標,則使用遊標適配器而不是陣列適配器來填充列表視圖 – Siva
你的問題和你卡在哪裏?你有嘗試過什麼嗎?你得到的輸出是什麼? – Sripathi
@Siva但它的投擲錯誤... – Umair