我有一个微调器,当你从微调器中选择一个项目时,一个字符串中的文本应该显示在textView中,(txtdescription1)但是当我开始活动时它会崩溃。
我已经测试了很多东西,但我没有在代码中发现错误。
Resources res = getResources();
int[] txt = res.getIntArray(R.array.description);
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
txtdescription1.setText(txt[position]);
}
这是LogCat
12-27 00:37:24.895: E/AndroidRuntime(1267): FATAL EXCEPTION: main
12-27 00:37:24.895: E/AndroidRuntime(1267): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.alpha.liveshit/com.alpha.liveshit.Sample}: java.lang.NullPointerException
12-27 00:37:24.895: E/AndroidRuntime(1267): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
12-27 00:37:24.895: E/AndroidRuntime(1267): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
12-27 00:37:24.895: E/AndroidRuntime(1267): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
12-27 00:37:24.895: E/AndroidRuntime(1267): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
12-27 00:37:24.895: E/AndroidRuntime(1267): at android.os.Handler.dispatchMessage(Handler.java:99)
12-27 00:37:24.895: E/AndroidRuntime(1267): at android.os.Looper.loop(Looper.java:123)
12-27 00:37:24.895: E/AndroidRuntime(1267): at android.app.ActivityThread.main(ActivityThread.java:4627)
12-27 00:37:24.895: E/AndroidRuntime(1267): at java.lang.reflect.Method.invokeNative(Native Method)
12-27 00:37:24.895: E/AndroidRuntime(1267): at java.lang.reflect.Method.invoke(Method.java:521)
12-27 00:37:24.895: E/AndroidRuntime(1267): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-27 00:37:24.895: E/AndroidRuntime(1267): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-27 00:37:24.895: E/AndroidRuntime(1267): at dalvik.system.NativeStart.main(Native Method)
12-27 00:37:24.895: E/AndroidRuntime(1267): Caused by: java.lang.NullPointerException
12-27 00:37:24.895: E/AndroidRuntime(1267): at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
12-27 00:37:24.895: E/AndroidRuntime(1267): at com.alpha.liveshit.Sample.<init>(Sample.java:42)
12-27 00:37:24.895: E/AndroidRuntime(1267): at java.lang.Class.newInstanceImpl(Native Method)
12-27 00:37:24.895: E/AndroidRuntime(1267): at java.lang.Class.newInstance(Class.java:1429)
12-27 00:37:24.895: E/AndroidRuntime(1267): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-27 00:37:24.895: E/AndroidRuntime(1267): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
12-27 00:37:24.895: E/AndroidRuntime(1267): ... 11 more
答案 0 :(得分:2)
您似乎是从您的活动的构造函数中调用getResources()
。您的活动不应该有构造函数(或者至少不是以任何方式与框架交互的构造函数)。它在那时尚未正确初始化(这就是调用getResources()
抛出NPE的原因)。将所有初始化代码放在onCreate(Bundle)
。