why does my app crash when I use the setText Mehod

2019-09-20 09:15发布

This question already has an answer here:

QUESTION:
Why is my app crashing whenever I try to use the setText() method to assign random Numbers as my Buttons' text?

My Goal is to set random numbers to the buttons and if the user clicks the button with the larger number, he/she is awarded a point.

I debugged the program and found the logic to be working correctly. However the app keeps crashing at startup and I don't know what exactly is the underlying problem.

THIS IS THE LOOK I AM GOING FOR

MAIN ACTIVITY:

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

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private static int points, rand1, rand2;


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

        points =0;
        randomize();
    }


    public void onLeftClick(View view) {

        if(rand1 > rand2)
            points++;
        else
            points--;

        TextView text = (TextView) findViewById(R.id.pointText);
        text.setText("Points : "+points);

        randomize();
    }

    public void onRightClick(View view) {

        if(rand2 > rand1)
            points++;
        else
            points--;

        TextView text = (TextView) findViewById(R.id.pointText);
        text.setText("Points : "+points);

        randomize();
    }

    private void randomize() {

        Random random = new Random();
        rand1= random.nextInt(10);
        rand2 = 0;

        while (true) {
            rand2 = random.nextInt(10);
            if (rand1 != rand2)
                break;
        }


        Button leftButton = (Button)findViewById(R.id.leftButton);
        leftButton.setText((char)rand1);   **ERROR HERE**
        Button rightButton = (Button)findViewById(R.id.rightButton);
        rightButton.setText((char)rand2);
    }

}

XML FILE:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.example.clickgame.MainActivity">

    <TextView
        android:layout_width="119dp"
        android:layout_height="24dp"
        android:text="CLICK GAME"
        android:textAlignment="center"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.032"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintLeft_creator="1" />

    <Button
        android:id="@+id/leftButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="215dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="216dp"
        android:onClick="onLeftClick"
        android:text="0"
        app:layout_constraintBottom_toTopOf="@+id/pointText"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintBottom_creator="1"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintTop_creator="1" />

    <Button
        android:id="@+id/rightButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="215dp"
        android:layout_marginEnd="18dp"
        android:layout_marginRight="18dp"
        android:layout_marginTop="216dp"
        android:onClick="onRightClick"
        android:text="0"
        app:layout_constraintBottom_toTopOf="@+id/pointText"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintBottom_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <TextView
        android:id="@+id/pointText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="POINTS : 0"
        android:textStyle="bold"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintBottom_creator="1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_constraintLeft_creator="1"
        android:layout_marginBottom="16dp"
        app:layout_constraintLeft_toLeftOf="parent" />

</android.support.constraint.ConstraintLayout>

ERROR LOG:

09-10 14:51:53.742 478-478/? E/AndroidRuntime: FATAL EXCEPTION: main
                                               Process: com.example.clickgame, PID: 478
                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.clickgame/com.example.clickgame.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x6
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                   at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                   at android.os.Looper.loop(Looper.java:154)
                                                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x6
                                                   at android.content.res.Resources.getText(Resources.java:335)
                                                   at android.widget.TextView.setText(TextView.java:4555)
                                                   at com.example.clickgame.MainActivity.randomize(MainActivity.java:66) //THIS LINE
                                                   at com.example.clickgame.MainActivity.onCreate(MainActivity.java:22) //THIS LINE
                                                   at android.app.Activity.performCreate(Activity.java:6679)
                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                                                   at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                   at android.os.Looper.loop(Looper.java:154) 
                                                   at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

5条回答
戒情不戒烟
2楼-- · 2019-09-20 09:49

Use String.valueof(), in the brackets of .settext()

Sample:

 TextView text = (TextView) findViewById(R.id.pointText);
    text.setText("Points : "+ String.valueof(points));

If you glance on this java documentation, then you could see that String.valueOf() returns:

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

So there shouldn't really be a difference except for an additional method invocation.

Also, in case of Object#toString, if the instance is null, a NullPointerException will be thrown, so, arguably, it's less safe.

查看更多
Ridiculous、
3楼-- · 2019-09-20 10:00

To add to the answer of Amirhossein Naghshzan what is happening here is that the setText method of TextView is capable of using a resourceId as a parameter. When you pass in and integer to this method it tries to find a string resource with that id. If it can't find one an exception is thrown hence the need to wrap a single number value with String.valueOf()

查看更多
家丑人穷心不美
4楼-- · 2019-09-20 10:02

Your Error is:

Resources$NotFoundException: String resource ID

you have to set the ID on your View item:

<TextView
android:id="@+id/pointText"
查看更多
We Are One
5楼-- · 2019-09-20 10:06

Use String.valueof() to cast int to string:

leftButton.setText(String.valueof(rand1));
rightButton.setText(String.valueof(rand2));
查看更多
闹够了就滚
6楼-- · 2019-09-20 10:08

i have cleaned your activity, use this one instead :

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private int 
             points = 0, 
             rand1, 
             rand2;

    private TextView text;

    private Button leftButton, rightButton;

    private Random random = new Random();

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

        text = (TextView) findViewById(R.id.pointText);

        leftButton = (Button)findViewById(R.id.leftButton);
        leftButton.setOnClickListener(this);

        rightButton = (Button)findViewById(R.id.rightButton);
        rightButton.setOnClickListener(this);

        randomize();
    }

    private void randomize() {

        rand1 = random.nextInt(10);
        rand2 = 0;

        while (true) {
            rand2 = random.nextInt(10);
            if (rand1 != rand2)
                break;
        }
        leftButton.setText(String.valueOf(rand1));
        rightButton.setText(String.valueOf(rand2));
    }

    @Override
    public void onClick(View v){

        switch(v.getId()){

            case R.id.leftButton{

                if(rand1 > rand2)
                    points++;
                else
                    points--;


                text.setText("Points : " + String.valueOf(points));

                randomize();

            }break;

            case R.id.rightButton:{

                if(rand2 > rand1)
                    points++;
                else
                    points--;


                text.setText("Points : " + String.valueOf(points));

                randomize();

            }break;

     }

 }

}

查看更多
登录 后发表回答