移动应用开发实践-Task9-关于安卓的异步查询操作
目的
将之前的查询所有省份、按照parentId查询城市、模糊查询城市的三个方法都通过异步方法封装,放到线程中执行。
1.升级CityDataBase
1)暴露一个接口,来实现将一个List对象传导到外部调用。
public interface OnQueryFinished {
public void onFinished(List<City> list);
}
2)声明一个内部类接口,来确定执行的哪个具体方法(即查询所有省份、按照parentId查询城市、模糊查询城市这个三个)。
interface LoaderWork {
List<City> qureyWork();
}
3)这里就是创建线程,将上面两步的两个接口传参进去,一个确定具体要执行的查询操作(work),一个将得到的结果传参到外部activity(listener),由外部来决定将得到的list对象做什么处理。
private void asyncLoader(final OnQueryFinished listener, final LoaderWork work) {
new Thread(new Runnable() {
@Override
public void run() {
final List<City> list = work.qureyWork();//执行方法
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onFinished(list);
}
});
}
}).start();
}
4)然后就是调用这个方法,将三个具体的查询搞定。
public void queryAllProvincesAsync(final OnQueryFinished listener) {
asyncLoader(listener, new LoaderWork() {
@Override
public List<City> qureyWork() {
return queryAllProvinces();
}
});
}
public void queryCityListByParentIdAsync(final int parentId, final int level, final OnQueryFinished listener) {
asyncLoader(listener, new LoaderWork() {
@Override
public List<City> qureyWork() {
return queryCityListByParentId(parentId, level);
}
});
}
public void fuzzyQueryCityListAsync(final String match, final OnQueryFinished listener) {
asyncLoader(listener, new LoaderWork() {
@Override
public List<City> qureyWork() {
return fuzzyQueryCityList(match);
}
});
}
2.MainActivity调用异步查询方法
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
//这里调用了异步模糊查询
cityDatabase.fuzzyQueryCityListAsync(newText, new CityDatabase.OnQueryFinished() {
@Override
public void onFinished(List<City> list) {
updateListView(list);
}
});
return false;
}
});
private void getAndUpdateCityList(final String url, final int parent_id, final int level) {
//这里调用了而异步查询城市ByParentId
cityDatabase.queryCityListByParentIdAsync(parent_id, level, new CityDatabase.OnQueryFinished() {
@Override
public void onFinished(List<City> list) {
if (list == null || list.size() == 0) {
HttpUtil.getOkHttpAsync(MainActivity.this, url, new HttpUtil.SimpleAsyncCall() {
@Override
public void onFailure(String e) {
showToast(e);
}
@Override
public void onResponse(String s) {
textView.setText(url);
List<City> list = JsonUtil.getCityListFromJson(s, parent_id, level);
cityDatabase.insertList(list);
showDbList(parent_id, level);
//updateListView(list);
}
});
} else {
textView.setText(url);
updateListView(list);
}
}
});
}
private void showDbList(int parent_id, int level) {
//这里调用了而异步查询城市ByParentId
cityDatabase.queryCityListByParentIdAsync(parent_id, level, new CityDatabase.OnQueryFinished() {
@Override
public void onFinished(List<City> list) {
updateListView(list);
}
});
}