我正在使用ListFragment来显示数据库中的数据。但数据显示不正确。
在我的片段中,在用户点击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
我想看看联系人的姓名。有人有想法吗?
答案 0 :(得分:3)
但是引用了TextView,它将填充数组中每个对象的toString()。您可以添加自定义对象的列表或数组。覆盖对象的toString()方法,以确定将为列表中的项显示哪些文本。
因此,要将自定义文字添加到列表中,请在toString()
课程中添加Contact
方法:
public String toString()
{
return name;
}