[英]Android application crashes at getContentResolver().query
[英]Android getContentResolver().query error
我對Java編程和Android開發都很陌生,所以我的學習曲線目前相當陡峭。 我似乎陷入了一些我無法找到合適的例子來解決它的問題。
我寫了一個函數,根據我在網上和那里找到的示例和文檔獲取我所有手機的聯系人。 我似乎無法解決的問題是這個。 以下代碼工作得很好;
private void fillData() {
// This goes and gets all the contacts
// TODO: Find a way to filter this only on contacts that have mobile numbers
cursor = getContentResolver().query(Contacts.CONTENT_URI, null, null, null, null);
final ArrayList<String> contacts = new ArrayList<String>();
// Let's set our local variable to a reference to our listview control
// in the view.
lvContacts = (ListView) findViewById(R.id.lvContacts);
while(cursor.moveToNext()) {
contacts.add(cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME)));
}
// Make the array adapter for the listview.
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
contacts);
// Let's sort our resulting data alphabetically.
aa.sort(new Comparator<String>() {
public int compare(String object1, String object2) {
return object1.compareTo(object2);
};
});
// Give the list of contacts over to the list view now.
lvContacts.setAdapter(aa);
}
我想通過過濾掉所有沒有手機號碼條目的聯系人來更改查詢語句。 我試過這樣的事情;
cursor = getContentResolver().query(Contacts.CONTENT_URI,
new String[] {Data._ID, Phone.TYPE, Phone.LABEL},
null, null, null);
但是,當我這樣做時,它會拋出NullPointer異常錯誤。 這有什么問題? 我從android的網站上的一個例子中得到了這個,但是他們有一個不適用於我的需求的where子句,所以我將where stuff更改為null。 這是在搞砸嗎?
謝謝。
好吧,看來我已經找到了我自己的問題的解決方案。 (把頭發拉出我的頭后變得時髦禿頭)
事實上,似乎使用Phone.TYPE絕對是問題所在。 Phone.TYPE是常量而不是數據列。
事實證明,完美運作的代碼是這樣的;
private void fillData() {
// This goes and gets all the contacts that have mobile numbers
final ArrayList<String> contacts = new ArrayList<String>();
// Let's set our local variable to a reference to our listview control
// in the view.
lvContacts = (ListView) findViewById(R.id.lvContacts);
String[] proj_2 = new String[] {Data._ID, Phone.DISPLAY_NAME, CommonDataKinds.Phone.TYPE};
phnCursor = managedQuery(Phone.CONTENT_URI, proj_2, null, null, null);
while(phnCursor.moveToNext()) {
if ( phnCursor.getInt(2) == Phone.TYPE_MOBILE ) {
String name = phnCursor.getString(1);
contacts.add(name);
}
}
// Make the array adapter for the listview.
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
contacts);
// Let's sort our resulting data alphabetically.
aa.sort(new Comparator<String>() {
public int compare(String object1, String object2) {
return object1.compareTo(object2);
};
});
// Give the list of contacts over to the list view now.
lvContacts.setAdapter(aa);
}
我很感激幫助,但不幸的是必須說徹底的瘋狂和研究最終得到了回報。 希望這有助於其他人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.