0

today I started a new project, created a few buttons and progressbars, wrote the code like usually. Yet it doesn't work, I get the following Error message:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 
'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' 
on a null object reference

in the following line:

gameModeEasy = (Button) findViewById(R.id.buttonEasy);
Log.d("gameModeEasyButtonId", "" + R.id.buttonEasy);
gameModeEasy.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // TODO perform action on click ...
        Log.d("gameModeEasyButton", "OnClickListener works");
    }
});

and yet I get the Id of the button:

gameModeEasyButtonId     2131034174

so my question now is why did it work in every other project I worked on so far and just doesn't work any more? I saw that in the Layout folder there is an fragment.xml in which i designed this one, does it have anything to do with it and if so, why? It's not like I'm not getting back the Id, but just that It performs as if the line with findViewById doesn't exist at all. And YES, I tried several different ways for the onClickListener and everyone returned the same error so It's not his fault ... thx in advance ...

fkarg
  • 198
  • 2
  • 17
  • 1
    So the view is in the fragment layout and you're trying to access it in `onCreate()` of the activity? Too early. http://stackoverflow.com/questions/23653778/nullpointerexception-accessing-views-in-oncreate – laalto Jun 22 '14 at 19:42
  • @laalto I tried it, but now the Buttons name is underlined Red: 'Cannot make a static reference to the non-static field gameModeEasy'. what to do? – fkarg Jun 22 '14 at 19:52
  • Move the member variables to the fragment class as well. – laalto Jun 22 '14 at 19:53
  • ok I declared Button gameModeEasy two lines above, It's underlined: 'Unreachable code'. – fkarg Jun 23 '14 at 10:46

0 Answers0