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

Coding the Fun Facts

I am currently going through the android videos and I have created the if statements but the statements aren’t coming up on my emulator, can't get my head around this can anybody help and explain where i am going wrong ?

This is my code

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fun_facts);

        //declare are View variables and assign the views from the layout file
        final TextView factLabel = (TextView) findViewById(R.id.factTextView);

        Button showFactButton = (Button) findViewById(R.id.showFactButton);
        View.OnClickListener Listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            //the button was clicked, so update the fact label with a new fact
                String fact = "";
                // randomly select a fact
                Random randomGenerator = new Random();//construct a new random generator
                int randomNumber = randomGenerator.nextInt(3);

                /*Convert the randomNumber to a text fact
                    * 0 = Have a bath everyday
                    * 1 = Read a book once a month
                    * 2 = Always strive to be the best
                 */

                     // if randomNumber equals 0 then set fact equal to Have fact
                     if (randomNumber == 0){
                        fact = "Have a bath everyday";
                     }
                    // if  randomNumber equals 1 then set fact equal to Read fact
                   else if (randomNumber == 1){
                    fact = "Read a book once a month";
                     }

                     // if  randomNumber equals 2 then set fact equal to Always fact
                    else if (randomNumber == 2){
                    fact = "Always strive to be the best";
                    }

                    else{

                         fact = "sorry there was an error";
                     }

                //update the label with our dynamic fact
                         factLabel.setText(fact);
            }
        };
        showFactButton.setOnClickListener(Listener);
    }

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

1 Answer

You are implementing your button's onClickListener wrong. This is one of many ways an onClickListener is setup:

public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.mylayout);
        findViewById(R.id.button1).setOnClickListener(mButton1_OnClickListener);
    }   

    // OnClickListener for button1
    final OnClickListener mButton1_OnClickListener = new OnClickListener() {
        public void onClick(final View v) {
            //Inform the user the button has been clicked
            Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show();                
        }
    };
}

Another way (my personal favorite):

findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //Inform the user the button has been clicked
        Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show();  
    }
});

Or by using an onClick reference for the button in XML:

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button1"
            android:onClick="button1OnClick"/>

and then simply doing this:

//On click event for button1
public void button1OnClick(View v) {
    //Inform the user the button has been clicked
    Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show();                
}

Read this tutorial for more information on how to correctly implement an onClickListener. Hope that helps! Let me know if you have any other questions. :)

Thanks for the information i have decided to add the following to the xml document android:onClick="buttonClick"/>

This is the code i now have in my xml document :

<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Show Another Fun Fact " android:id="@+id/showFactButton" android:layout_gravity="center_horizontal|bottom" android:background="#ffffffff" android:onClick="buttonClick"/>

Numbers are still not coming up where am i going wrong , i know that i am close but can someone explain please ?

this is my code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fun_facts);
    Button button = (Button) findViewById(R.id.showFactButton);

    button.setOnClickListener(
       new Button.OnClickListener() {
           public void onClick(View v) {
             TextView factTextView =
                     (TextView)findViewById(R.id.factTextView);
             factTextView.setText("button clicked ");



           }
       }
    );

    //declare are View variables and assign the views from the layout file
    final TextView factLabel = (TextView) findViewById(R.id.factTextView);



    View.OnClickListener Listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        //the button was clicked, so update the fact label with a new fact
            String fact = "";
            // randomly select a fact
            Random randomGenerator = new Random();//construct a new random generator
            int randomNumber = randomGenerator.nextInt(3);

            /*Convert the randomNumber to a text fact
                * 0 = Have a bath everyday
                * 1 = Read a book once a month
                * 2 = Always strive to be the best
             */
                 // if randomNumber equals 0 then set fact equal to Have fact
                 if (randomNumber == 0){
                    fact = "Have a bath everyday";


                 }
                // if  randomNumber equals 1 then set fact equal to Read fact
               else if (randomNumber == 1){
                fact = "Read a book once a month";


                 }

                 // if  randomNumber equals 2 then set fact equal to Always fact
                else if (randomNumber == 2){
                fact = "Always strive to be the best";


                }

                else{

                     fact = "sorry there was an error";
                 }

            //update the label with our dynamic fact
                     factLabel.setText(fact);
        }
    };

}


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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}