Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Any ideas why my Crystal Ball app won't start?

So, I am on the Android track and I have just begun. I followed it correctly, and now am at the stage where I have a button, which pressed displays the text 'Yes'.... Or at least I'm supposed to. When I run it, I click Crystal Ball and it goes black then comes up with "Crystal Ball has stopped running". Could somebody please tell me what is wrong with it? Here is all my source code:

package com.example.crystalball;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    @SuppressWarnings("null")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Declare our view variables and assign the the views from our layout file
        final TextView answerLabel = (TextView) findViewById(R.id.textView1);
        Button getAnswerButton = null;

        getAnswerButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //The button was clicked, so update the answer label for an answer
                String answer = "Yes";
                answerLabel.setText(answer);

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

1 Answer

Your program is crashing in the onCreate method, so it dies as soon as it starts up. The problem is in these lines:

Button getAnswerButton = null;
getAnswerButton.setOnClickListener(new View.OnClickListener() {
// And so on

getAnswerButton is null when you call its setOnClickListener method. When you call a method on a null object, the program crashes. You need to set getAnswerButton to the appropriate button before you call its setOnClickListener method. Assuming the ID of your button is button1, you'd do it like this:

getAnswerButton = (Button) findViewById(R.id.button1);

Thanks!