我知道这个异常意味着什么(在后台方法中调用UI方法),我已经在几个地方修复了它。但我有一个我不明白的事件。该代码在Android 5及更高版本上运行良好,但在Android 4.2上失败。有人可以告诉我原因吗?
我需要在启动时运行初始化Preferences的代码:
public class LeliMathApp extends Application
public void onCreate() {
super.onCreate();
new FeedPreferencesTask().doInBackground(null);
}
private class FeedPreferencesTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void[] params) {
log.debug("Loading default values from XML");
PreferenceManager.setDefaultValues(LeliMathApp.this, R.xml.game_prefs, false);
log.debug("Defaults are loaded");
return null;
}
}
例外:
Caused by: android.view.InflateException: Binary XML file line #34: Error inflating class java.lang.reflect.Constructor
at android.preference.GenericInflater.createItem(GenericInflater.java:397) ~[na:0.0]
at android.preference.GenericInflater.onCreateItem(GenericInflater.java:417) ~[na:0.0]
at android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428) ~[na:0.0]
at android.preference.GenericInflater.inflate(GenericInflater.java:263) ~[na:0.0]
at android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:269) ~[na:0.0]
at android.preference.PreferenceManager.setDefaultValues(PreferenceManager.java:482) ~[na:0.0]
at android.preference.PreferenceManager.setDefaultValues(PreferenceManager.java:441) ~[na:0.0]
at lelisoft.com.lelimath.helpers.LeliMathApp$FeedPreferencesTask.doInBackground(LeliMathApp.java:156) ~[na:0.0]
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:197) ~[na:0.0]
at android.os.Handler.<init>(Handler.java:111) ~[na:0.0]
at android.widget.Editor$UserDictionaryListener.<init>(Editor.java:3836) ~[na:0.0]
at android.widget.Editor.<init>(Editor.java:192) ~[na:0.0]
at android.widget.TextView.createEditorIfNeeded(TextView.java:8489) ~[na:0.0]
at android.widget.TextView.<init>(TextView.java:1055) ~[na:0.0]
at android.widget.EditText.<init>(EditText.java:60) ~[na:0.0]
at android.widget.EditText.<init>(EditText.java:56) ~[na:0.0]
at android.preference.EditTextPreference.<init>(EditTextPreference.java:56) ~[na:0.0]
当我在Android 4.2上的主线程中运行此代码时,它运行良好。为什么它在较旧的Android上失败并且适用于新的Android?