New app crashing on start-up, debug not helping

2019-09-08 21:24发布

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 and he can't figure out what I'm doing wrong. Can someone please point out why my app is crashing on start up?

Thanks:

http://pastebin.com/ZXxHPzng

标签: android crash
2条回答
霸刀☆藐视天下
2楼-- · 2019-09-08 22:13

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:

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



    @Override
    public void onCreate(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);
查看更多
The star\"
3楼-- · 2019-09-08 22:22

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;



@Override
public 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...

查看更多
登录 后发表回答