Cracker0dks
Cracker0dks

Reputation: 2490

Null PointerExeption ALL the time?

Why is mainB_news allways null? (in the method onBackPressed()) In onCreate I set a value to the button!!! :(

PS: with findViewById() I get the same error...

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


    }
}

THANKS a lot!

Upvotes: 1

Views: 152

Answers (2)

Sergey Glotov
Sergey Glotov

Reputation: 20356

Because you change contentView on button click. mainB_news doesn't exist after contentView changing. You shouldn't use setContentView() in this manner. Consider using another activity for showing news.

Upvotes: 1

Konstantin Pribluda
Konstantin Pribluda

Reputation: 12367

Because it is not defined in res/layout/main.xml ?

Upvotes: 1

Related Questions