lundi 31 août 2015

App crashes on if statement [duplicate]

This question already has an answer here:

I want to create a randomizer app but every time i click on the button the app crashes here is the code for the MainActivity.java

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;

    import java.util.Random;

    public class MainActivity extends AppCompatActivity {

        TextView random_number_text_view;

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

        random_number = (TextView) findViewById(R.id.random_number_text_view);

    }

    public void onButtonClick(View view) {

        Random random = new Random();

        int randomNumber = random.nextInt(5 - 1) +1;


        if (randomNumber == 1){

         random_number_text_view.setText(randomNumber);
     }

        else {

         random_number_text_view.setText(randomNumber);
        }

    }
}

And here for the activity_main.xml

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
        xmlns:tools="http://ift.tt/LrGmb4"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center|top"
        android:orientation="vertical"
        android:padding="20dp"
        tools:context=".MainActivity">

    <TextView
        android:id="@+id/random_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/random_number"
        android:textSize="30sp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onButtonClick"
        android:text="Click me" />

</LinearLayout>

Aucun commentaire:

Enregistrer un commentaire