1. Are you ready for the Galaxy S20? Here is everything we know so far!

Android Studio - App closes when you press the main button even thought the code is working fine !

Discussion in 'Android Development' started by Gleis, Aug 10, 2020.

  1. Gleis

    Gleis Lurker
    Thread Starter

    Tried many methods by changing the code, but it closes every time I press the "Try" button. You can find the Design, XML & Java code below. Also Android Studio is up to date.

    The "//" is the old code I tried.
    Code (Java):
    1. public class MainActivity extends AppCompatActivity {
    2.  
    3.     //int randomNumber;
    4.     public void higher_lower (View view){
    5.     EditText var1= (EditText) findViewById(R.id.TextField);
    6.     int  var = Integer.parseInt(var1.getText().toString());
    7.  
    8.     int randomNumber;
    9.     Random var2 = new Random();
    10.    randomNumber =var2.nextInt(0-20)+20;
    11.  
    12.    String message;
    13.  
    14.         if(var>randomNumber){
    15.             message ="The number is larger";
    16.             //Toast.makeText(this, "The hidden number is larger", Toast.LENGTH_SHORT).show();
    17.         }else if (var<randomNumber){
    18.             message="The number is smaller";
    19.             //Toast.makeText(this, "The hidden number is smaller", Toast.LENGTH_SHORT).show();
    20.         }else{
    21.  
    22.             message="BINGO!";
    23.         //Toast.makeText(this, "BINGO!", Toast.LENGTH_SHORT).show();
    24.         }
    25.     //Log.i("Info" , var3);
    26. Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    27.  
    28. }
    29. @Override
    30. protected void onCreate(Bundle savedInstanceState) {
    31.     super.onCreate(savedInstanceState);
    32.     setContentView(R.layout.activity_main);
    33.    // Random var2 = new Random();
    34.      //randomNumber = var2.nextInt(0-20)+20;
    35.  
    36. }
     

    Attached Files:



  2. mb4mobile

    mb4mobile Lurker

    Hi,
    A method that was executed when the button was clicked is missing in the code.

    Code (Java):
    1. public void higher_lower(View view)
    2. {
    3.  
    4.           //code executed on cliks
    5. }

    The name of metod you set in android : onClick in layout xml.
     
Loading...

Share This Page

Loading...