0

我在试图确定将我的听众放在哪里时遇到了问题(我正在尝试设置两个听众,但在这里只会引用一个,希望能够为自己解决第二个!)。

我有一个微调器,想在微调器项目更改时更新一些 TextView,所以我想我想要一个onItemSelected侦听器。在阅读了其他人关于 SO 的问题后,我尝试将其放入onCreate方法和onStart方法中,但该应用程序在加载时将只是 FC。

该应用程序使用选项卡/片段进行导航,这是否与问题有关(尝试设置侦听器时片段未膨胀)?

@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
        }

    });


}

还有日志猫;

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
4

1 回答 1

1

当您获得 NullPointerException 时,spinner.setXXX()您的spinner变量包含 null。这意味着findViewById()在 pine before 中没有找到当前上下文中的 spinner。上下文是用你的 line 设置的setContentView()

底线:看起来您的R.layout.activity_main不包含R.id.spinner.

于 2013-08-24T17:26:52.073 回答