Проблемы из редактируемого (EditText) в целые числа

#android #casting #android-widget #android-edittext #parseint

#Android #Кастинг #android-виджет #android-edittext #parseint

Вопрос:

У меня возникли проблемы с получением целочисленных значений для простой математической программы из полей edittext. Я могу получить из него строку, но когда я пытаюсь преобразовать ее в целое число, она выходит из строя. Я пробовал:

 int a = Intger.parseInt(X2.getText().toString());
  

и он все равно падает. Любая идея будет с благодарностью принята.
Вот исходный код.

 package siu.edu.cs215;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

public class Quadratic extends Activity {
private TextView answer;
private EditText X2, X, K; 
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.quad);
    Button1 = (Button)findViewById(R.id.quad);
    Button2 = (Button)findViewById(R.id.backwards);
    answer = (TextView)findViewById(R.id.B1);
    X2 = (EditText)findViewById(R.id.xsquared);
    X = (EditText)findViewById(R.id.xcoeff);
    K = (EditText)findViewById(R.id.kconst);

}
public Button Button1 = null;
public Button Button2 = null;
public void QA (View view){
//double sol1=0.0, sol2=0.0, disc=0.0;
int a = Integer.parseInt(X2.getText().toString());
//int b = Integer.getInteger(X.getText().toString());
//int c = Integer.getInteger(K.getText().toString());
//disc = Math.pow(b, 2) - 4.0*a*c;
//sol1 = (-b   Math.sqrt(disc)) / (2.0 * a);
//sol2 = (-b - Math.sqrt(disc)) / (2.0 * a);
answer.setText(a);
};
public void BACK (View view){
Intent i = new Intent(this, ExtraCreditActivity.class);
startActivity(i);
}
}
  

Вот файл xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >




<TableLayout
    android:id="@ id/tableLayout1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >


    <TableRow
        android:id="@ id/tableRow2"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight=".6" >

    </TableRow>


    <TableRow
        android:id="@ id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1" >

        <EditText
            android:id="@ id/xsquared"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:inputType="number" />


        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="X^2  "
            android:textSize="20dp" />

        <EditText
            android:id="@ id/xcoeff"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="number" />


        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="X   "
            android:textSize="20dp" />

        <EditText
            android:id="@ id/kconst"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:inputType="number" >

            <requestFocus />
        </EditText>
    </TableRow>

    <TableRow
        android:id="@ id/tableRow3"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1.2" >

        <Button
            android:id="@ id/quad"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="QA"
            android:text="Quadratic" />
    </TableRow>


    <TableRow
        android:id="@ id/tableRow4"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight=".8" >

            <TextView
        android:id="@ id/B1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="2pt"
        android:text="@string/app_name" />

    </TableRow>

    <TableRow
        android:id="@ id/tableRow5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <Button
            android:id="@ id/backwards"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Back"
            android:onClick="BACK" />

    </TableRow>

</TableLayout>

</LinearLayout>
  

Комментарии:

1. Вы убедились, что получили правильную строку?

Ответ №1:

Скорее всего, ваша проблема заключается в попытке проанализировать пустую строку. Возможно, вы можете просто избежать выполнения каких-либо вычислений, если все поля не могут быть правильно проанализированы. Поместите ваш синтаксический анализ в блок try / catch.

Комментарии:

1. «Он выходит из строя» — это не очень полезно. Пожалуйста, предоставьте фрагмент logcat аварии.