【发布时间】:2019-08-16 10:34:12
【问题描述】:
我正在使用一个函数从 android 电话簿中选择电话名称,并使用光标来获取联系人的姓名和号码。我能够成功地做到这一点,并将值插入到我在此处另一个问题的帮助下编写的 sqllite 数据库中,但是当向数据库中插入新值时,listview 不会自动更新。
我已经使用了所有需要的行,包括
((BaseAdapter)display_contacts1.getAdapter()).notifyDataSetChanged();display_contacts1.invalidateViews();arrayAdapter.notifyDataSetChanged();manageListView(getContext());
但我仍然无法找到解决方案。列表视图更新的唯一方法是进入不同的片段或重新启动应用程序。
原始 SQL 数据库代码 Android OnItemClick not working with loaded SQL Database into listview
SelectModemFragment.java
//--------------------------------------------------------------------
// Select Phone number from Contacts list
//--------------------------------------------------------------------
@Override
public void onActivityResult(int reqCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
// Check for the request code
switch (reqCode)
{
case CONTACT_PICKER:
contactPicked(data);
break;
}
}
else
{
Log.e("MainActiivity", "Failed to pick contact");
}
}
private void contactPicked(Intent data)
{
//Cursor cursor = null;
try
{
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getActivity().getApplicationContext().getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the contact name
int nameIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
// column index of the phone number
int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
name = cursor.getString(nameIndex);
phoneNo = cursor.getString(phoneIndex);
// Show message displaying the contact selected from the phonebook
Toast.makeText(getContext(),name, Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(), phoneNo, Toast.LENGTH_SHORT).show();
// Insert values to sqlite database
dbHelper.insert(name, phoneNo);
// Need to immediately update the listview one the values have been inserted into the database
((BaseAdapter)display_contacts1.getAdapter()).notifyDataSetChanged();
//display_contacts1.invalidateViews(); // This isn't working
//arrayAdapter.notifyDataSetChanged(); // This isn't working
//manageListView(getContext());, this didn't work
}
catch (Exception e)
{
e.printStackTrace();
}
}
【问题讨论】:
-
我把行 thelist = dbHelper.getAllRowsAsList();和 ((BaseAdapter)display_contacts1.getAdapter()).notifyDataSetChanged();将值插入数据库后但仍未自动更新列表视图
标签: android sqlite listview android-cursor