简体   繁体   English

空时 EditText 崩溃

[英]EditText crash when empty

so I have an EditText field,and when the user tap a number,its start counting down.所以我有一个 EditText 字段,当用户点击一个数字时,它开始倒计时。 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"这是因为,与"1""2"等字符串不同,空字符串( "" )无法转换为数字

To fix this: We Provide a try-catch block for the NumberFormatException为了解决这个问题:我们为NumberFormatException提供了一个try-catch

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.在检查天气是否为空之前,您没有从 edittext 中获取文本。 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.如您所见,我已将整数转换放在 if 块中,因为这也可能是其原因。

Like Felix Favour said it's because you're trying to parse a non-numeric item into a string.就像 Felix Favor 所说的那样,这是因为您试图将非数字项解析为字符串。 This line:这一行:

mEnterNumber = findViewById(R.id.mEnterNumber);

Will most likely resolve to Null if nothing is entered.如果不输入任何内容,很可能会解析为 Null。 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:或者,您也可以像这样在 XML 中设置它:

    <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.我希望这将防止崩溃。

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

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