简体   繁体   中英

EditText crash when empty

so I have an EditText field,and when the user tap a number,its start counting down. The problem starts when the are not entering a number the app crash.

this is what I tried to do:

Thanks for the help.


public class MainActivity extends AppCompatActivity {

    EditText mEnterNumber;
    TextView mTest;
    int timerIsRunning = 0;

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

    public void StartRemainder(View view){
    
        mTest = findViewById(R.id.mTest);
        mEnterNumber = findViewById(R.id.mEnterNumber);
    
        int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
    
    
        if(userNumb < 0 || mEnterNumber.toString().isEmpty()){
            Toast.makeText(MainActivity.this, "Please enter correct number", Toast.LENGTH_SHORT).show();
        }
        else{
    
        CountDownTimer userTimer = new CountDownTimer(userNumb,1000) {
    
            @Override
            public void onTick(long millisUntilFinished) {
    
                long millis = millisUntilFinished;
    
                //Convert milliseconds into hour,minute and seconds
                String hms = String.format("%02d:%02d:%02d",
                        TimeUnit.MILLISECONDS.toHours(millis),
                        TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
                mTest.setVisibility(View.VISIBLE);
                mTest.setText(hms);
                timerIsRunning = 1;
    
            }
    
    
    
            @Override
            public void onFinish() {
    
    
            }
        }.start();
        }
    
    }

----------------------This is the error I get when the app crash:--------------------------------

2020-09-04 04:09:15.024 27096-27096/com.example.drinkme E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.drinkme, PID: 27096
java.lang.IllegalStateException: Could not execute method for android:onClick
    at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
    at android.view.View.performClick(View.java:6256)
    at android.view.View$PerformClick.run(View.java:24701)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
    at android.view.View.performClick(View.java:6256) 
    at android.view.View$PerformClick.run(View.java:24701) 
    at android.os.Handler.handleCallback(Handler.java:789) 
    at android.os.Handler.dispatchMessage(Handler.java:98) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6541) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
 Caused by: java.lang.NumberFormatException: For input string: ""
    at java.lang.Integer.parseInt(Integer.java:620)
    at java.lang.Integer.parseInt(Integer.java:643)
    at com.example.drinkme.MainActivity.StartRemainder(MainActivity.java:40)
    at java.lang.reflect.Method.invoke(Native Method) 
    at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
    at android.view.View.performClick(View.java:6256) 
    at android.view.View$PerformClick.run(View.java:24701) 
    at android.os.Handler.handleCallback(Handler.java:789) 
    at android.os.Handler.dispatchMessage(Handler.java:98) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6541) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

line of error:

int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;

I'm guessing the issue is with this line:

int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;

And it is because, an empty string( "" ) cannot be converted to a number unlike strings like "1" or "2"

To fix this: We Provide a try-catch block for the NumberFormatException

int userNumb = 0;
try {
    if (mEnterNumber != null && !TextUtils.isEmpty(mEnterNumber.getText().toString())) {
        userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000; 
    }
} 
catch (NumberFormatException ex) {}

You're not getting the text from the edittext before checking weather it's empty or not. Try this :

if(userNumb < 0 && mEnterNumber.`getText()`.toString().isEmpty()){
    Toast.makeText(MainActivity.this, "Please enter correct number", 
    Toast.LENGTH_SHORT).show();
    int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
}

As you can see I've put the integer conversion in the if block as it might also be the reason for it.

Like Felix Favour said it's because you're trying to parse a non-numeric item into a string. This line:

mEnterNumber = findViewById(R.id.mEnterNumber);

Will most likely resolve to Null if nothing is entered. You can try setting it to a numeric value:

    mEnterNumber = findViewById(R.id.mEnterNumber);
    if mEnterNumber.getText().toString().equals("")
    {
        int userNumb = 0;  // or whatever value you want to set as a starting default
    }
    else
    {
        int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
    }

This invariably could need more improvement for checking or preventing other non-numeric entries ofcourse.

Alternatively, you can also set it in the XML like this:

    <EditText
    android:id="@+id/mEnterNumber"
    ...
    android:text="0" />

I use something like this -

if (mEnterNumber.getText().toString().matches("")){
            Toast.makeText(this, "Please Enter any number", Toast.LENGTH_SHORT).show();
            return;
        }

I hope this will prevent the crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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