简体   繁体   English

单击按钮提交空输入时,Android应用程序崩溃

[英]Android app crashes when button is clicked to submit empty input

I am new to Android and I am currently creating a game in which the system generates a random number and the user has to guess it. 我是Android的新手,目前正在创建一个游戏,其中系统生成一个随机数,用户必须猜测它。 The code is given below: 代码如下:

package np.com.sagunrajlage.higherorlower;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;

import static np.com.sagunrajlage.higherorlower.R.layout.activity_main;

public class MainActivity extends AppCompatActivity {
    int randomnumber, count;
    TextView guessnumberTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(activity_main);
        guessnumberTextView = (TextView) findViewById(R.id.guessnumberTextView);
        Random rand = new Random();
        randomnumber = rand.nextInt(20) + 1;

    }

    public void makeToast(String string){
        Toast.makeText(this, string, Toast.LENGTH_LONG).show();
    }



    public void guess(View view){
        count++;
        EditText guesseditText = (EditText) findViewById(R.id.guesseditText);
        String guessedtext = guesseditText.getText().toString();
        int guessInt = Integer.parseInt(guessedtext);

        if(guessInt>randomnumber) {
            makeToast("Guess a lower number!");
        }
        else if(guessInt<randomnumber){
            makeToast("Guess a higher number!");
        }
        else{
            makeToast("You got it! "+ randomnumber +" was the number. Now guess the new number I chose.");
            Random rand = new Random();
            randomnumber = rand.nextInt(20) + 1;
        }
        guesseditText.setText("");
        guessnumberTextView.setText("Number of guesses: "+Integer.toString(count));
    }
}

Here, the onClick event hits guess() and when I click the button with an empty value at guesseditText , the application crashes with an error saying: java.lang.IllegalStateException: Could not execute method for android:onClick . 在这里, onClick事件会击中guess() ,当我click guesseditText处带有空值的按钮时,应用程序崩溃,并显示错误消息: java.lang.IllegalStateException: Could not execute method for android:onClick

The XML is: XML是:

<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="np.com.sagunrajlage.higherorlower.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="15dp"
            android:text="I'm thinking of a number between 1 and 20."
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            tools:layout_editor_absoluteY="45dp" />

        <android.support.constraint.Guideline
            android:id="@+id/guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_begin="20dp"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="20dp" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="9dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="20dp"
            android:text="Can you guess it?"
            android:textAppearance="@style/TextAppearance.AppCompat.Display1"
            app:layout_constraintBottom_toTopOf="@+id/guesseditText"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView2"
            app:layout_constraintVertical_bias="0.115" />

        <EditText
            android:id="@+id/guesseditText"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_marginBottom="31dp"
            android:layout_marginTop="45dp"
            android:ems="10"
            android:hint="Enter the number here"
            android:inputType="number"
            app:layout_constraintBottom_toTopOf="@+id/guessbutton"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent" />

        <TextView
            android:id="@+id/guessnumberTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Number of Guesses: 0"
            android:textAlignment="center"
            android:textAppearance="@style/TextAppearance.AppCompat.Display1" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <Button
                android:id="@+id/guessbutton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="50dp"
                android:layout_marginRight="50dp"
                android:layout_marginTop="30dp"
                android:onClick="guess"
                android:text="guess"
                android:textAlignment="center"
                app:layout_constraintHorizontal_bias="0.498"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                tools:layout_editor_absoluteY="303dp" />
        </RelativeLayout>

    </LinearLayout>

</android.widget.RelativeLayout>

You cannot convert blank string to integer. 您不能将空白字符串转换为整数。 you check blank string like: 您检查空白字符串,如:

if(guessedtext.equalsIgnoreCase(""){
 int guessInt = 0;
}else{
 int guessInt = Integer.parseInt(guessedtext);
}

Try android:onClick="guess" in Button's xml code and define EditText in onCreate method... 在Button的xml代码中尝试android:onClick="guess"并在onCreate方法中定义EditText ...

 EditText guesseditText;
 Button guessbutton;

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(activity_main);
    guessnumberTextView = (TextView) findViewById(R.id.guessnumberTextView);
    guesseditText = (EditText) findViewById(R.id.guesseditText);
    guessbutton=(Button)findViewById(R.id.guessbutton);
    Random rand = new Random();
    randomnumber = rand.nextInt(20) + 1;

}

Then you can get this edittext's value at anywhere.. 然后,您可以在任何地方获取此edittext的值。

I think you should be change this line: 我认为您应该更改此行:

 setContentView(activity_main);

To

setContentView(R.layout.activity_main);

Change your code as follow: 更改您的代码,如下所示:

Button btn = (Button) findViewById(R.id.yourButtonFromXml);

in onCreate() onCreate()

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        guess(v);
    }
});

- -

 public void guess(View view){
        count++;
        EditText guesseditText = (EditText) findViewById(R.id.guesseditText);
        String guessedtext = guesseditText.getText().toString();    
        int guessInt = Integer.parseInt(guessedtext.getZText().toString().trim());   //you missed guessedtext.getZText().toString()

        if(guessInt>randomnumber) {
            makeToast("Guess a lower number!");
        }
        else if(guessInt<randomnumber){
            makeToast("Guess a higher number!");
        }
        else{
            makeToast("You got it! "+ randomnumber +" was the number. Now guess the new number I chose.");
            Random rand = new Random();
            randomnumber = rand.nextInt(20) + 1;
        }
        guesseditText.setText("");
        guessnumberTextView.setText("Number of guesses: "+Integer.toString(count));
    }

Try this one :) this is running for me :) 试试这个:)这正在为我运行:)

import static teratomo.testapp.R.layout.activity_main;

public class MainActivity extends AppCompatActivity {

  int randomnumber, count;
  TextView guessnumberTextView;
  EditText guesseditText;
  String guessedtext;
  int guessInt = 0;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(activity_main);
    guessnumberTextView = (TextView) findViewById(R.id.guessnumberTextView);
    guesseditText = (EditText) findViewById(R.id.guesseditText);
    Random rand = new Random();
    randomnumber = rand.nextInt(20) + 1;
  }

  public void makeToast(String string){
    Toast.makeText(this, string, Toast.LENGTH_LONG).show();
  }



  public void guess(View view){
    count++;
    if (guesseditText.getText().length() > 0) {
      guessInt = Integer.parseInt(guesseditText.getText().toString());
      if(guessInt > randomnumber) {
        makeToast("Guess a lower number!");
      }
      else if(guessInt < randomnumber){
        makeToast("Guess a higher number!");
      }
      else{
        makeToast("You got it! "+ randomnumber +" was the number. Now guess the new number I chose.");
        Random rand = new Random();
        randomnumber = rand.nextInt(20) + 1;
      }
      guesseditText.setText("");
      guessnumberTextView.setText("Number of guesses: "+Integer.toString(count));
    } else {
      Toast.makeText(this, "Please fill field", Toast.LENGTH_SHORT).show();
    }
  }
}

尝试用您的活动public class MainActivity extends AppCompatActivity implement Onclicklistener {}

在oncreate中定义按钮在任何地方都没有定义

在此处输入图片说明

See the output a toast written inside the guess method is clearly visible here. 看到输出,在这里可以清楚地看到在guess方法中编写的祝酒词

Everything is fine in your code , just You should bind your activity in a rigth way like setContentView(R.layout.activity_main) instead of setContentView(activity_main); 一切在您的代码中都很好,只是您应该以setContentView(R.layout.activity_main)之类的严格方式绑定活动,而不是setContentView(activity_main);

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        guessnumberTextView = (TextView) findViewById(R.id.guessnumberTextView);
        Random rand = new Random();
        randomnumber = rand.nextInt(20) + 1;

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM