当我调用mAdaper.notifyDataSetChanged()时,Android应用程序崩溃;
问题描述:
这是一个应用程序,它应该从手机获取联系人,并列出在列表视图中有电话号码的应用程序。 但是,应用程序崩溃时mAdaper.notifyDataSetChanged();叫:/ 请帮忙。当我调用mAdaper.notifyDataSetChanged()时,Android应用程序崩溃;
public class MainActivity extends Activity{
static int num = 0;
ListView lv;
ArrayAdapter<String> mAdaper;
ArrayList<String> contacts = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getContacts();
lv = (ListView)findViewById(R.id.listView1);
mAdaper = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contacts);
lv.setAdapter(mAdaper);
}
private void getContacts(){
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, // projection,
null, // selection,
null, // selectionArgs,
"_ID DESC" // sortOrder
);
if (cur.getCount() > 0) {
while (cur.moveToNext() && num < 10) {
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// TableRow row = new TableRow(this);
TextView tv = new TextView(this);
String row = id + " - " + name;
contacts.add(row);
//mAdaper.add(row);
num++;
}
}
}
mAdaper.notifyDataSetChanged();
}
答
您在初始化mAdapter之前调用getContacts()。在getContacts()中,您正在调用mAdapter.notifyDataSetChanged();.此时,mAdapter尚未初始化。
在初始化mAdapter之后调用getContacts()。
lv = (ListView)findViewById(R.id.listView1);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contacts);
lv.setAdapter(mAdapter);
getContacts();