我正在使用 ListFragment 来显示数据库中的数据。但数据显示不正确。
在我的 Fragment 中,在用户单击 ActionBar 项目并插入名称后,我将联系人添加到 SQLite 数据库:
//Handle OnClick events on ActionBar items
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.menu_add:
Toast.makeText(getActivity(), "Click", Toast.LENGTH_SHORT).show();
LayoutInflater factory = LayoutInflater.from(getActivity());
//textEntryView is an Layout XML file containing text field to display in alert dialog
textEntryView = factory.inflate(R.layout.dialog_add_room, null);
//get the control from the layout
enter_room = (EditText) textEntryView.findViewById(R.id.enter_room);
//create Dialog
final AlertDialog.Builder alert1 = new AlertDialog.Builder(getActivity());
//configure dialog
alert1.setTitle("Raum hinzufügen:").setView(textEntryView)
.setPositiveButton("Hinzufügen",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String roomname = enter_room.getText().toString();
Log.d("Insert: ", "Inserting ..");
dbHandler.addContact(new Contact(roomname, "0"));
adapter.notifyDataSetChanged();
}
}).setNegativeButton("Abbrechen",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
//cancel dialog
}
});
alert1.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
然后我想获取所有联系人并使用以下代码在 ListFragment 中显示它们:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//display ActionBar items
setHasOptionsMenu(true);
//database
dbHandler = new DatabaseHandler(getActivity());
//get all contacts
contacts = dbHandler.getAllContacts();
adapter = new ArrayAdapter<Contact>(getActivity(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1, contacts);
adapter.setNotifyOnChange(true);
//show all contacts in the ListFragment
setListAdapter(adapter);
}
我的 DatabaseHandler 中的 getAllContacts():
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
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.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
但是在我的 ListFragment 中显示了以下内容:
com.example.fragmentmasterdetail.sqlite.Contact@21059ed8
我想查看联系人的姓名。任何人的想法?