Skip to content Skip to sidebar Skip to footer

New App Crashing On Start-up, Debug Not Helping

Alright I tried debugging my code, using DDMS and I can't qutie get the hang of it just yet. I think it's because my program crashes on launch. Anyways, I showed this to a buddy an

Solution 1:

The problem you have is you are creating your UI elements in the global area. You can declare them there if you want it to be a global object, but you can not instantiate them until after you have set the content view. For example:

privateRadioButton rockRB;
    privateRadioButton paperRB;
    privateRadioButton scissorsRB;
    privateTextView result;



    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
        // Content View Must be set before making UI Elements
        rockRB = (RadioButton)findViewById(R.id.radioRock);
        paperRB = (RadioButton)findViewById(R.id.radioPaper);
        scissorsRB = (RadioButton)findViewById(R.id.radioScissors);
        result =  (TextView)findViewById(R.id.result);

Solution 2:

It is actually quite simple. You initialize the variables rockRB, paperRB, scissorRB and result while initializing the class. At the time you invoke findViewById(...) the layout has not been loaded yet, and therefore no view with the specified id is found. The function findViewById therefore returns null to indicate that. When you later try to use the stored id (which is null), you get a null-pointer exception and therefore the entire application crashes.

To solve your problem, move the initialization of the variables using findViewById(...) to the function onCreate below the setContentView statement, but before the setOnClickListener statements.

Like this:

public class RockPaperScissorsActivity extends Activity implements Button.OnClickListener { /** Called when the activity is first created. */

private RadioButton rockRB;
private RadioButton paperRB;
private RadioButton scissorsRB;
private TextView result;



@Overridepublic void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    rockRB = (RadioButton)findViewById(R.id.radioRock);
    paperRB = (RadioButton)findViewById(R.id.radioPaper);
    scissorsRB = (RadioButton)findViewById(R.id.radioScissors);
    result = (RadioButton)findViewById(R.id.result);

    rockRB.setOnClickListener(this);
    paperRB.setOnClickListener(this);
    scissorsRB.setOnClickListener(this);
}

and so on...

Post a Comment for "New App Crashing On Start-up, Debug Not Helping"