我正在使用AsyncTask从文件中读取数据。我在运行应用程序时遇到上述错误。
错误消息是:
03-29 20:06:08.445:E / AndroidRuntime(13191): java.lang.ExceptionInInitializerError 03-29 20:06:08.445: E / AndroidRuntime(13191): 在 com.google.app.BouncingBall.HighScore.loadFromFile(HighScore.java:81) 03-29 20:06:08.445:E / AndroidRuntime(13191): 在 com.google.app.BouncingBall.HighScore。(HighScore.java:24)03-29 20:06:08.445:E / AndroidRuntime(13191):at com.google.app.BouncingBall.BouncingBallActivity $ BouncingBallView.init(BouncingBallActivity.java:185) 03-29 20:06:08.445:E / AndroidRuntime(13191):at com.google.app.BouncingBall.BouncingBallActivity $ BouncingBallView.run(BouncingBallActivity.java:173) 03-29 20:06:08.445:E / AndroidRuntime(13191):at java.lang.Thread.run(Thread.java:1019)03-29 20:06:08.445: E / AndroidRuntime(13191):引起:java.lang.RuntimeException:不能 在没有调用Looper.prepare()的线程内创建处理程序 03-29 20:06:08.445:E / AndroidRuntime(13191):at android.os.Handler。(Handler.java:121)
守则
private void loadFromFile()
{
new AsyncDataStorage().execute(FILENAME);
}
class AsyncDataStorage extends AsyncTask<String, Integer, Boolean> {
protected Boolean doInBackground(String... args) {
try {
FileInputStream fis = context.openFileInput(FILENAME);
byte[] raw = new byte[fis.available()];
String rawData=null;
while(fis.read()!=-1)
{
rawData = new String(raw);
}
return (processRawData(rawData));
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
答案 0 :(得分:13)
03-29 20:06:08.445: E/AndroidRuntime(13191): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 03-29 20:06:08.445:
引用the documentation for AsyncTask
:
必须在UI线程上创建任务实例。
在你的cask中,没有在主应用程序(a.k.a.,UI)线程上创建任务实例,这是导致此异常的原因。
答案 1 :(得分:2)
只需在Runnable中将每个调用包装到com.google.app.BouncingBall.HighScore.loadFromFile
或创建AsyncTask
,然后将其发布到绑定到UI线程的Handler。