我正在读取电话联系人并将其存储到SQLite表中,但它的工作正常,但是当我试图显示来自SQLite表的同一活动中的联系人进入列表视图时,我需要关闭并重新打开活动以查看来自SQLite的联系人列表表格。我该怎么做,请提供解决方案。谢谢。
public class ContactsActivity extends AppCompatActivity {
private DataBaseHelper db;
private ListView listView;
private ProgressBar progressBar;
private List<String> namelist=null;
private Button btnLoad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
listView = findViewById(R.id.listView);
progressBar = findViewById(R.id.progressBar);
btnLoad = findViewById(R.id.btnLoad);
db=new DataBaseHelper(ContactsActivity.this);
namelist = db.getData();
if(namelist.size()>0)
{
ArrayAdapter listadapter = new ArrayAdapter<>(getApplication(),android.R.layout.simple_list_item_1,namelist);
listView.setAdapter(listadapter);
}
else{
AsyncTask.execute(() -> getcontacts());
}
}
public void getcontacts()
{
progressBar.setVisibility(View.VISIBLE);
db=new DataBaseHelper(ContactsActivity.this);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
assert cur != null;
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
assert pCur != null;
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String Name = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
db.insert(Name,phoneNo);
}
pCur.close();
}
}
progressBar.setVisibility(View.GONE);
namelist = db.getData();
ArrayAdapter listadapter = new ArrayAdapter<>(getApplication(),android.R.layout.simple_list_item_1,namelist);
listadapter.notifyDataSetChanged();
listView.setAdapter(listadapter);
cur.close();
}
}
}
数据已成功插入到SQLite表中,但是关闭并重新打开活动后,列表视图中正在填充结果。如何在不关闭并重新打开活动的情况下填充结果?
答案 0 :(得分:0)
请更改,
ArrayAdapter listadapter = new ArrayAdapter<>(getApplication(),android.R.layout.simple_list_item_1,namelist);
listadapter.notifyDataSetChanged();
listView.setAdapter(listadapter);
带有以下代码,
ArrayAdapter listadapter = new ArrayAdapter<>(getApplication(),android.R.layout.simple_list_item_1,namelist);
listView.setAdapter(listadapter);
listadapter.notifyDataSetChanged();