0

我遇到了以下错误。

logUser("An error happend while creating graph:"+ getErrorMessage());

其中 getErrorMessage() 是 Can't create handler inside 未调用 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();
}
4

2 回答 2

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;
于 2013-05-05T19:29:20.020 回答
2

您需要AsyncTask在主线程上实例化您的。AsyncTask源代码创建一个Handler来调用你的,onPreExecute()onPostExecute()方法,如果Handler没有在主线程上实例化,Android 会抛出一个异常,告诉你Handler正在与之交互的线程没有Looper.prepare()调用它的方法。

于 2013-05-05T19:32:55.480 回答