我在尝试找出放置听众的位置时遇到了问题(我有两个听众,我正在尝试设置,但只会在这里引用一个,希望能为自己工作第二个!)。
我有一个微调器,想要在微调器项改变时更新一些TextView,所以我想要一个onItemSelected
监听器。我在SO上阅读别人的问题之后尝试将其放在onCreate
方法和onStart
方法中,但加载时应用只会出现FC。
该应用程序使用Tabs / Fragments进行导航,这是否与问题有关(在尝试设置监听器时片段没有膨胀)?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
spinner = (Spinner)findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
和logcat;
08-24 17:19:16.256 13803-13803/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
... 11 more
答案 0 :(得分:1)
当您在spinner.setXXX()
获得NullPointerException时,您的spinner
变量包含null。这意味着之前松树中的findViewById()
在当前上下文中找不到微调器。使用您的行setContentView()
设置上下文。
结论:您的R.layout.activity_main
似乎不包含R.id.spinner
。