0

I am trying to make a simple text game but I cant even get through the first step. There is a textview in the layout and 3 radio buttons. I want to change the text when you click at one of the radio buttons and to determine what text the app is going to use, I have a position int. example: I select button one: if position = 1, then set set text to text 2. If position = 9, then set text to 11 and so on. here is the code:

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;


public class Game extends Activity implements OnCheckedChangeListener{
    public int position;
    TextView text;
    RadioGroup rggr;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        position = 1;
        text = (TextView) findViewById(R.id.text);

        setContentView(R.layout.p1);

        rggr = (RadioGroup) findViewById(R.id.rgGr);
        rggr.setOnCheckedChangeListener(this);
    }

    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // TODO Auto-generated method stub
        switch (checkedId){
                case R.id.rb1:
                    if(position == 1){
                        text.setText("this is text 1");
                        position = 2;

                    }
                }
            }
        }

If I change the line "text.setText("this is text 1");" to something else. for example setcontentview then it all works. But when I want to change the text, it crashes the moment I select the radio button.

user1833270
  • 59
  • 1
  • 7

3 Answers3

2

Looks like you are trying to get a reference to a TextView before setting the UI for this activity. instead of

    text = (TextView) findViewById(R.id.text);
    setContentView(R.layout.p1);

try

    setContentView(R.layout.p1);
    text = (TextView) findViewById(R.id.text);
David M
  • 2,511
  • 1
  • 15
  • 18
0

If you try get a view before you set the content view, it will be null, so in this example text is null because you call it before setting the content view. You can verify that with the debugger.

Therefore, when you try to access it via text.setText(...) it will crash with NullPointerException

As David M also said, calling findViewById after setContentView will solve the problem

For future references, as David M has commented, the LogCat output will be helpful.

shalafi
  • 3,926
  • 2
  • 23
  • 27
0

thanks to all fo you. It was the wrong order of

 setContentView(R.layout.p1);
 text = (TextView) findViewById(R.id.text);

thank you.

user1833270
  • 59
  • 1
  • 7