我正在尝试在AsyncTask中的联系人簿中按编号查找联系人姓名。有时我会收到以下错误,我认为这会导致应用程序崩溃。请帮忙。
logcat的
08-05 09:00:49.627 24988-27371/com.fake.fake E/CursorLeakDetecter: PossibleCursorLeak:content://com.android.contacts/phone_lookup/%2B923310433708,QueryCounter:5
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.content.ContentResolver.query(ContentResolver.java:323)
at com.fake.fake.GV.getContactName(GV.java:177)
at com.fake.fake.MySQLiteHelper.GetNumbers(MySQLiteHelper.java:361)
at com.fake.fake.MainActivity$taskLoadContacts.doInBackground(MainActivity.java:930)
at com.fake.fake.MainActivity$taskLoadContacts.doInBackground(MainActivity.java:921)
at android.os.AsyncTask$2.call(AsyncTask.java:264)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
从数据库中检索联系号码。
public ArrayList<MyMessageDetails> GetNumbers(String query) {
ArrayList<MyMessageDetails> numbers = new ArrayList<MyMessageDetails>();
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.moveToFirst()) {
do {
MyMessageDetails item = new MyMessageDetails();
item.setNumber(cursor.getString(0));
String name = GV.getContactName(item.getNumber());
if (name == null) {
name = item.getNumber();
}
item.setName(name);
item.setTime(cursor.getString(3));
numbers.add(item);
} while (cursor.moveToNext());
}
return numbers;
}
检索联系人姓名。
public static String getContactName(String phoneNumber) {
if (phoneNumber != null) {
ContentResolver cr = ApplicationContextProvider.getContext().getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return "";
}
String contactName = null;
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
return phoneNumber;
}
答案 0 :(得分:2)
从中读取数据后使用Cursor#close()
。例如:
Cursor cursor = ...
try {
// fetch whatever you need here
} finally {
cursor.close();
}
答案 1 :(得分:0)
我在这里看到的几个问题。
首先,始终在try catch finally
块中包围您的查询,并关闭finally
块中的所有游标和数据库操作。对于你的两种方法都是如此。
我认为你在做错的是先调用GetNumbers()
方法然后调用getContactName()
。现在你不要在代码中的GetNumbers()
中关闭db,因此在你尝试对db执行的任何操作都会出现此错误,因此错误会出现在getContactName()