Null PointerExeption一直都是吗?

时间:2011-12-28 14:53:19

标签: java android nullpointerexception

为什么mainB_news总是null? (在onBackPressed()方法中) 在onCreate中我为按钮设置了一个值! :(

PS:findViewById()我得到同样的错误......

public class MainActivity extends Activity {
    private Button mainB_news;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mainB_news = (Button) findViewById(R.id.mainB_news);
        mainB_news.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setContentView(R.layout.news);
            }
        });
    }

    @Override
    public void onBackPressed() {
        // check if page 2 is open
        if (mainB_news != null && mainB_news.isShown()){
            setContentView(R.layout.main); // open main view again
            return;
        }else
            super.onBackPressed(); // allows standard use of backbutton for page 1


    }
}

非常感谢!

2 个答案:

答案 0 :(得分:1)

因为它没有在res / layout / main.xml中定义?

答案 1 :(得分:1)

因为您在按钮上单击更改contentView。在contentView更改后,mainB_news不存在。您不应该以这种方式使用setContentView()。考虑使用其他活动来展示新闻。