我遇到了以下错误。
logUser("An error happend while creating graph:"+ getErrorMessage());
其中getErrorMessage()是无法在未调用Looper.prepare()的线程内创建处理程序,而logUser是一个只显示toast congaing消息的函数。
void prepareGraph() {
logUser("loading graph (" + Helper.VERSION + "|" + Helper.VERSION_FILE
+ ") ... ");
new MyAsyncTask<Void, Void, Path>() {
protected Path saveDoInBackground(Void... v) throws Exception {
GraphHopper tmpHopp = new GraphHopper().forAndroid();
tmpHopp.contractionHierarchies(true);
tmpHopp.load(mapsFolder + currentArea);
logUser("found graph with " + tmpHopp.getGraph().nodes() + " nodes");
hopper = tmpHopp;
return null;
}
protected void onPostExecute(Path o) {
if (hasError()) {
logUser("An error happend while creating graph:"
+ getErrorMessage());
} else {
logUser("Finished loading graph. Touch to route.");
calcPath(52.534185, 13.348732, 52.53857,
13.41259);
}
finishPrepare();
}
}.execute();
}
答案 0 :(得分:2)
您无法从后台线程执行UI操作。
试试这个:
GraphHopper tmpHopp = new GraphHopper().forAndroid();
tmpHopp.contractionHierarchies(true);
tmpHopp.load(mapsFolder + currentArea);
runOnUiThread(new Runnable() {
public void run() {
logUser("found graph with " + tmpHopp.getGraph().nodes() + " nodes");
}
});
hopper = tmpHopp;
return null;
答案 1 :(得分:2)
您需要在主线程上实例化AsyncTask
。 AsyncTask
源代码会创建Handler
来调用您的onPreExecute()
,onPostExecute()
等方法,如果Handler
未在主线程上实例化, Android将抛出异常,告诉您Handler
正在与之交互的线程没有调用它的Looper.prepare()
方法。