所以经过一些研究,我有一个可行的解决方案,但如果有人有任何其他建议,他们将不胜感激。
由于我们使用 contentProvider 来获取游标,然后通过 IntentService 更新后端数据。当我们的用户在他们的搜索中输入第一个字符时,我们会抓住光标,如果光标计数 = 0,那么我们会显示一个空列表消息,否则我们会显示该光标中的项目列表..
** 注意:一些游标处理可能需要稍微调整一下,我没有看到任何崩溃,因为我们的适配器有一个游标被撕掉并变为空,但你的里程可能会有所不同..(这是更多关于使用 contentProviderClient())
** 注意:根据文档,您必须在不再使用时释放 contentProviderClient()。
由于内容提供者应该返回一个类型,我们可以执行以下操作..
所以我们定义一个成员变量
private ContentProviderClient contentProviderClient = null;
然后当我们的用户更改我们最终调用的搜索字符串时
public void setFilter( String searchFilter ) {
searchedString = !TextUtils.isEmpty(filter) ? filter : "";
boolean reload = false; // Reloads content provider
// contentProvider is null on first connection, assumed to be up on
// subsequent connections as we only close the cursor and
// contentProviderClient when we exit
if (contentProviderClient != null) {
try {
// getType will throw an exception if the instance of the
// contentProvider went away (killed by user/memory collection etc)
contentProviderClient.getType(searchFactoryUri);
} catch (RemoteException e) {
if( searchAdapter != null ) {
Cursor cursor = searchAdapter.getCursor();
cursor = null;
reload = true;
contentProviderClient.release();
}
}
}
// This is for first search initialization or reloading cursor
// if the content provider went away for some unknown reason.
if( this.searchAdapter == null || reload ){
Cursor cursor = getActivity().getContentResolver().query(
MY_URI,
null,
null,
null,
null);
contentProviderClient = getActivity()
.getContentResolver()
.acquireContentProviderClient(MY_URI);
cursor.setNotificationUri(getActivity.getContentResolver(), MY_URI);
// DO what ever you need to after getting cursor, a cursor loader
// would be a better implementation here, but simplifying it as
// I don't want to over-complicate the example.
myList.setAdapter(searchAdapter);
}
getActivity().startService(MyUtil.getSearchIntent( MY_URI, searchedString );
}
@Override
public void onDestroy() {
super.onDestroy();
// Cleanup adapter, cursor, provider client
if (searchAdapter != null) {
searchAdapter.changeCursor(null); // Closes existing cursor
}
if (contentProviderClient != null) {
contentProviderClient.release(); // Release client
}
}