BallisticMonkey
BallisticMonkey

Reputation: 83

Android app crashes on onClickListener

I have this app which is a simple lottery system but whenever I try pressing one of the buttons the app freezes then crashes and I don't know why. The program doesn't give me errors so it's really confusing. I saw some things about it being a problem with the layout but I can't figure out what it is. I will answer the page Layout in a comment under the question. Thanks in advance.

Here's the page script:

package com.example.myapplication;

import android.graphics.Color;
import android.icu.text.NumberFormat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.*;
import java.math.*;

import org.w3c.dom.Text;

import javax.xml.transform.Result;

public class Lottery extends AppCompatActivity {
    Button Check, Random;
    EditText User1;
    TextView Balance2, ResultText;
    int  Balance1 = 500;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lottery);
        Check = (Button)findViewById(R.id.CheckNumbers);
        Random = (Button)findViewById(R.id.RandomNumber);
        User1 = findViewById(R.id.PickNumber);
        Balance2 = (TextView)findViewById(R.id.Balance);
        ResultText = (TextView)findViewById(R.id.Result);
        ResultText.setVisibility(View.GONE);

       Balance2.setText("Balance: $500");

        Check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int User=Integer.parseInt(String.valueOf(User1));
                if(User1.toString().trim().equals("")){
                    ResultText.setBackgroundColor(Color.RED);
                    ResultText.setText("Please Enter a Number");
                    ResultText.setVisibility(View.VISIBLE);

                }
                else if(User > 100 || User < 1){
                    ResultText.setBackgroundColor(Color.RED);
                    ResultText.setText("Please Enter a Number between 1 and 100");
                    ResultText.setVisibility(View.VISIBLE);
                }
                else {
                    int answer = (int)((Math.random()*100)+1);
                    int placeholder = answer % 10;
                    int AnswerTens = (answer - placeholder)/10;
                    int AnswerOnes = placeholder;
                    placeholder = User %10;
                    int UserTens = (User- placeholder)/10;
                    int UserOnes = placeholder;

                    if(User == answer){
                        ResultText.setBackgroundColor(Color.GREEN);
                        ResultText.setText("Correct!!! The Number was "+User+" $1000 has been added to your account");
                        ResultText.setVisibility(View.VISIBLE);
                        Balance1 += 1000;
                        Balance2.setText("Balance: $ "+  Balance1);
                    }
                    else if((UserTens == AnswerOnes)&&(UserOnes == AnswerTens)){
                        ResultText.setBackgroundColor(Color.GREEN);
                        ResultText.setText(" Somewhat Correct! The digit were correct but in the wrong order The answer was "+answer+" $500 has been added to your account");
                        ResultText.setVisibility(View.VISIBLE);
                        Balance1 += 500;
                        Balance2.setText("Balance: $ "+  Balance1);
                    }
                    else if((UserTens == AnswerTens)|| (UserTens == AnswerOnes)||(UserOnes == AnswerOnes)||(UserOnes==AnswerTens)){
                        ResultText.setBackgroundColor(Color.GREEN);
                        ResultText.setText("Kinda Correct! One digit was  correct The answer was "+answer+" $100 has been added to your account");
                        ResultText.setVisibility(View.VISIBLE);
                        Balance1 += 100;
                        Balance2.setText("Balance: $ "+  Balance1);
                    }
                    else{
                        ResultText.setBackgroundColor(Color.RED);
                        ResultText.setText("Incorrect the Number was "+answer);
                        ResultText.setVisibility(View.VISIBLE);
                    }


                }
            }
        });
        Random.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               int answer = (int)((Math.random()*100)+1);

                User1.setText(answer);
            }
        });
    }
}

Upvotes: 0

Views: 83

Answers (2)

Tyler V
Tyler V

Reputation: 10910

I see a couple possible causes for a crash. As @Siros mentioned, you need to use String.valueOf(answer) in your call to setText

In addition, to get the string from an EditText you have to call User1.getText().toString(). Calling User1.toString() will return something like android.support.v7.widget.AppCompatEditText{cab8e45 VFED..CL. ......I. 0,0-0,0 #7f08003e app:id/editText}, which can definitely not be parsed as an integer.

Calling Integer.parseInt(String.valueOf(User1)); will always crash with a NumberFormatException (since the string it's trying to parse is like the one above).

When you call Integer.parseInt(string); it will throw an exception if the string is not a valid integer (e.g. a blank string, or 0.1.2.3). You will see a stack trace that looks something like this:

Process: com.project.testproject, PID: 30357
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.testproject/com.project.testproject.MainActivity}: java.lang.NumberFormatException: Invalid int: "android.support.v7.widget.AppCompatEditText{8c2c99a VFED..CL. ......I. 0,0-0,0 #7f08003e app:id/editText}"
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.NumberFormatException: Invalid int: "android.support.v7.widget.AppCompatEditText{8c2c99a VFED..CL. ......I. 0,0-0,0 #7f08003e app:id/editText}"
    at java.lang.Integer.invalidInt(Integer.java:138)
    at java.lang.Integer.parse(Integer.java:410)
    at java.lang.Integer.parseInt(Integer.java:367)
    at java.lang.Integer.parseInt(Integer.java:334)
    at com.project.testproject.MainActivity.onCreate(MainActivity.java:37)
    at android.app.Activity.performCreate(Activity.java:6237)

You may want to use something like this:

String UserString = User1.getText().toString();

if( UserString.trim().isEmpty() ) {
    //handle empty string
}
else {
    try {
       int User = Integer.parseInt(UserString);

       // Handle valid number cases
    }
    catch(NumberFormatException ne) {
      // handle invalid entry
    }
}

Upvotes: 0

Siros Baghban
Siros Baghban

Reputation: 406

Change this :

User1.setText(answer);

To this :

User1.setText(String.valueOf(answer));

Upvotes: 1

Related Questions