почему мое приложение падает, когда я использую метод setText?

ВОПРОС:
Почему мое приложение аварийно завершает работу всякий раз, когда я пытаюсь использовать метод setText() для назначения случайных чисел в качестве текста кнопок?

Моя цель - установить случайные числа для кнопок, и если пользователь нажимает кнопку с большим числом, ему присуждается балл.

Я отладил программу и обнаружил, что логика работает правильно. Однако приложение продолжает падать при запуске, и я не знаю, в чем именно заключается проблема.

ЭТО ОБРАЗ МНЕ НУЖЕН

ОСНОВНАЯ ДЕЯТЕЛЬНОСТЬ:

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-ФАЙЛ:

<?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>

ЖУРНАЛ ОШИБОК:

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) 

person Vignesh Gunasekaran    schedule 10.09.2017    source источник
comment
в чем ошибка? покажи нам ошибку logcat   -  person Mahdi Nouri    schedule 10.09.2017
comment
@MahdiNouri добавил журнал ошибок!   -  person Vignesh Gunasekaran    schedule 10.09.2017


Ответы (5)


Чтобы добавить к ответу Амирхоссейна Нагшзана, здесь происходит то, что метод setText TextView может использовать resourceId в качестве параметра. Когда вы передаете целое число этому методу, он пытается найти строковый ресурс с этим идентификатором. Если он не может найти его, возникает исключение, поэтому необходимо обернуть одно числовое значение с помощью String.valueOf()

person Ivan Wooll    schedule 10.09.2017
comment
Спасибо! Это прояснило это! - person Vignesh Gunasekaran; 10.09.2017
comment
Благодарю. ты спас мой день. отличная работа. - person Reflection; 10.08.2020

Используйте String.valueof() для преобразования int в строку:

leftButton.setText(String.valueof(rand1));
rightButton.setText(String.valueof(rand2));
person Amirhossein Naghshzan    schedule 10.09.2017

Используйте String.valueof() в скобках .settext()

Образец:

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

Если вы взглянете на этот документацию по Java, то вы могли видеть, что String.valueOf() возвращает:

если аргумент null, то строка равна "null"; в противном случае возвращается значение obj.toString().

Так что на самом деле не должно быть разницы, кроме вызова дополнительного метода.

Кроме того, в случае Object#toString,, если экземпляр null, будет выброшен NullPointerException, поэтому, возможно, это менее безопасно.

person Zafar Kurbonov    schedule 10.09.2017
comment
Почему в этом случае метод toString() не работает? - person Vignesh Gunasekaran; 10.09.2017
comment
Я отредактировал свой ответ с дальнейшим объяснением разницы между toString и String.ValueOf - person Zafar Kurbonov; 10.09.2017

я очистил вашу активность, используйте вместо этого:

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;

     }

 }

}

person Mahdi Nouri    schedule 10.09.2017

Ваша ошибка:

Resources$NotFoundException: Идентификатор строкового ресурса

вы должны установить идентификатор в элементе просмотра:

<TextView
android:id="@+id/pointText"
person deadpoint    schedule 10.09.2017
comment
Он уже установлен. Оказывается, мне нужно использовать метод String.tovalues(). В любом случае спасибо! - person Vignesh Gunasekaran; 10.09.2017