在主Activity中,我定義了按鈕並將它們放在onclicklistener上。問題是在viewAll按鈕時,我想從數據庫填充列表視圖,以便我調用該方法db.getAllContacts(),但該代碼不起作用從數據庫中填充ListView
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.editText1);
phone = (EditText)findViewById(R.id.editText2);
btnViewAll=(Button)findViewById(R.id.button1);
btnAdd=(Button)findViewById(R.id.button2);
btnAdd.setOnClickListener(this);
btnViewAll.setOnClickListener(this);
}
@Override
public void onClick(View view) {
MySQLiteHelper db = new MySQLiteHelper(this);
if(view==btnViewAll) {
if(name.getText().toString().trim().length()==0 || phone.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values");
return;
}
else{
List<Contact> contact = new ArrayList<Contact>();
contact= db.getAllContacts();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, contact);
ListView listContent = (ListView)findViewById(R.id.List);
listContent.setAdapter(adapter);
}
}
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
name.setText("");
phone.setText("");
}
在SQLiteHelper文件:
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM contact";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhone(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}// return contact list
return contactList;}
請幫我
使用一個CursorAdapter來代替。 – Nazgul 2014-12-07 09:55:36
您應該爲您的聯繫人列表使用customAdapter – 2014-12-07 10:13:27
並檢查getAllContacts()方法的日誌,以便它從數據庫中返回聯繫人列表 – 2014-12-07 10:23:08