在查找EditText.isEmpty()后应用程序崩溃

时间:2018-02-21 17:24:44

标签: java android if-statement android-edittext kotlin

我甚至不明白这是什么以及为什么它不能正常工作。我有按钮,它开始新的活动。但在此之前,我检查了一些值,点击按钮后 - 它崩溃了.-。我不知道该怎么做,但它无论如何都不能正常工作。我正在写作 代码:

lateinit var string: String
var day: Int = 0
var month: Int = 0
var yearProp: Int = 0
var dayEnd: Int = 0
var monthEnd: Int = 0
var yearEndProp: Int = 0
var priceFrom: Int = 0
var priceTo: Int = 0
companion object {
    lateinit var props: Properties
}

override fun onDateSet(view: DatePickerDialog?, year: Int, monthOfYear: Int, dayOfMonth: Int, yearEnd: Int, monthOfYearEnd: Int, dayOfMonthEnd: Int) {
    day = dayOfMonth
    month = monthOfYear
    yearProp = year
    dayEnd = dayOfMonthEnd
    monthEnd = monthOfYearEnd
    yearEndProp = yearEnd
    button_whats_date.text = getString(R.string.title_from) + ": " + day + "/" + month + "/" + yearProp + " | " + getString(R.string.title_to) + ": " + dayEnd + "/" + monthEnd + "/" + yearEndProp
}    

param_done.setOnClickListener {
        if (input_price_from.getText().toString().matches("".toRegex()) || input_price_to.getText().toString().matches("".toRegex())) {
            priceFrom = 0; priceTo = 999999999
            Log.i("VALUES", "" + priceTo)
            if (Integer.parseInt(input_price_from.text.toString()) > Integer.parseInt(input_price_to.text.toString())) {
                Toast.makeText(this@MainActivity, getString(R.string.error_change_price), LENGTH_SHORT).show()
            } else {
                try {
                    props = Properties(string, int, int, int, int, int, int, priceFrom, priceTo)
                    val intent = Intent(this@MainActivity, SearchActivity::class.java)
                    startActivity(intent)
                } catch (e: Throwable) {
                    Toast.makeText(this@MainActivity, getString(R.string.props_error), LENGTH_SHORT).show()
                    Log.i("Hereissometex", "User cannot follow to next activity")
                }
            }
        }
    }


<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="12dp"
            android:layout_marginHorizontal="8dp"
            android:orientation="horizontal">
            <EditText
                android:id="@+id/input_price_from"
                android:inputType="number"
                android:layout_width="0dp"
                android:layout_height="60dp"
                android:layout_weight="2"
                android:textColor="#FFF"
                android:hint="@string/title_from"/>
            <EditText
                android:id="@+id/input_price_to"
                android:inputType="number"
                android:layout_width="0dp"
                android:layout_height="60dp"
                android:layout_weight="2"
                android:textColor="#FFF"
                android:hint="@string/title_to"/>
        </LinearLayout>
    </LinearLayout>
    <Button
        android:id="@+id/param_done"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|bottom"
        android:layout_marginBottom="10dp"
        android:background="@android:color/transparent"
        android:text="@string/done"
        android:textColor="@color/colorPrimary"/>
</FrameLayout>

它只是崩溃了。如果你需要别的东西 - 请给我一个标志。我如何检查输入值:

input_price_from.addTextChangedListener(object : TextWatcher {
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun afterTextChanged(s: Editable) {
            priceFrom = Integer.parseInt(input_price_from.text.toString())
        }
    })
    input_price_to.addTextChangedListener(object : TextWatcher {
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun afterTextChanged(s: Editable) {
            priceTo = Integer.parseInt(input_price_to.text.toString())
            Log.i("[TravelMet::INFO]", "InputPrice value changed and parced")
        }
    })   

**EDIT**: Added log.


    E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: s.com.s, PID: 1979
                  java.lang.NumberFormatException: For input string: ""
                      at java.lang.Integer.parseInt(Integer.java:533)
                      at java.lang.Integer.parseInt(Integer.java:556)
                      at arsensaruhanyan.com.travelmet.MainActivity$onCreate$5.onClick(MainActivity.kt:110)
                      at android.view.View.performClick(View.java:6261)
                      at android.widget.TextView.performClick(TextView.java:11185)
                      at android.view.View$PerformClick.run(View.java:23752)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6776)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

101:
                    Toast.makeText(this@MainActivity, getString(R.string.error_change_price), LENGTH_SHORT).show()

4 个答案:

答案 0 :(得分:0)

我想异常非常清楚

java.lang.NumberFormatException: For input string: ""

在这里更改并检查文本是否为空并且长度更长

检查文字是否为空

try{
    if(input_price_from.text.toString().length()>0){
       //code goes here
     }
   }catch(e:NumberFormatException){
     e.printStackTrace()
   }

答案 1 :(得分:0)

问题是您将空字符串传递给Integer.parseInt(input_price_from.text.toString())

在调用Integer.parseInt(input_price_from.text.toString())之前,您应首先检查字符串是否为空并且是整数。

您可以通过在这些行中编写一些代码来执行空白检查和数字是整数:

String n = input_price_from.text.toString();
if(n != null) {
    String trimmed = n.trim();
    if(!trimmed.isEmpty() && trimmed.matches("\\d+")) {
        int num = Integer.parseInt(n.trim());
        System.out.println(num);
        // ... whatever code
    }
}

答案 2 :(得分:0)

我找到了它!

同样适用于priceFrom以及priceTo

priceFrom = Integer.parseInt(input_price_from.text.toString())

如果没有文本,那么parseInt将尝试解析抛出Runtime Exception的空字符串。

你可以做这样的事情

val text = input_price_from.text.toString.trim()
if (text.isNotEmpty() && text.matches("\\d+")) {
        try {
            priceFrom = text.toInt()
        } catch (e: Exception) {
            priceFrom = 0 //default value if the text includes anything 
            //except for the number.
        }
    }

另外,您可以将EditTextinputType = number强制用于仅输入数字

答案 3 :(得分:0)

天哪,这很难理解,但我只是通过使用这个条件来解决它:

if (priceFrom > priceTo)

并且,我认为不是:price_from不是太重要,因为price_to以相同的方式检出。

无论如何,感谢所有人的帮助