2016-06-17 3 views
-2

Я пробовал много вещей, найденных здесь, но он продолжает сбой. Я хочу знать, что мне нужно добавить, чтобы показать сообщение Toast, когда кнопка нажата, а EditText пуст.Мои приложения продолжают сбой при нажатии кнопки и EditText пуст

INFO: Предполагается, что приложение должно отправить два значения в EditText в другую активность, указав Toast's в следующих исключениях: первое значение выше 6; второе значение выше (первое значение * 14); и если поля пусты (это моя проблема)

Вот мой код:

public class MainActivity extends AppCompatActivity implements View.OnClickListener { 

    TextView saludo_bienvenida; 
    EditText et1_creditos; 
    EditText et2_faltas; 
    Button boton_ingresar; 
    Button boton_info; 
    String numero_creditos; 
    String numero_faltas_actuales; 




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

     saludo_bienvenida = (TextView) findViewById(R.id.saludo_bienvenida); 

     et1_creditos = (EditText) findViewById(R.id.edittext1_numero_creditos); 

     et2_faltas = (EditText) findViewById(R.id.edittext2_numero_faltas); 

     boton_ingresar = (Button) findViewById(R.id.boton_ingresar); 

     boton_info = (Button) findViewById(R.id.boton_info); 

     if (boton_ingresar != null) { 
      boton_ingresar.setOnClickListener(this); 
     } 

     if (boton_info != null) { 
      boton_info.setOnClickListener(this); 
     } 

     et1_creditos.setInputType(InputType.TYPE_CLASS_NUMBER); 
     et2_faltas.setInputType(InputType.TYPE_CLASS_NUMBER); 

    } 

    @Override 
    public void onClick(View v) { 
     switch (v.getId()) { 
      case R.id.boton_ingresar: 
       numero_creditos = et1_creditos.getText().toString(); 
       numero_faltas_actuales = et2_faltas.getText().toString(); 
       int numero_creditos1 = Integer.parseInt(numero_creditos); 
       int numero_faltas_actuales1 = Integer.parseInt(numero_faltas_actuales); 
       int o = numero_creditos1 * 14; 



       if (numero_creditos1>6) { 
        Toast.makeText(getApplicationContext(), "Ingrese un número válido de créditos", Toast.LENGTH_LONG).show(); 
       }else if (numero_faltas_actuales1 > o){ 
        Toast.makeText(getApplicationContext(), "El número de faltas ingresadas es mayor que el número de horas del curso", Toast.LENGTH_LONG).show(); 
       }else{ 
        Intent intent = new Intent(MainActivity.this,Resultados.class); 
        intent.putExtra("numero_creditos",numero_creditos); 
        intent.putExtra("numero_faltas_actuales",numero_faltas_actuales); 
        startActivity(intent); 
       } 
       break; 
      case R.id.boton_info: 
       Intent informacion = new Intent(MainActivity.this,Informacion.class); 
       startActivity(informacion); 
       break; 
     } 
    } 
} 

Это журнал:

06-17 01:36:17.419 2738-2738/absence_counter.app.jorgepasco.com.absencecounter E/AndroidRuntime: FATAL EXCEPTION: main 
                          Process: absence_counter.app.jorgepasco.com.absencecounter, PID: 2738 
                          java.lang.NumberFormatException: Invalid int: "" 
                           at java.lang.Integer.invalidInt(Integer.java:138) 
                           at java.lang.Integer.parseInt(Integer.java:358) 
                           at java.lang.Integer.parseInt(Integer.java:334) 
                           at absence_counter.app.jorgepasco.com.absencecounter.MainActivity.onClick(MainActivity.java:60) 
                           at android.view.View.performClick(View.java:4780) 
                           at android.view.View$PerformClick.run(View.java:19866) 
                           at android.os.Handler.handleCallback(Handler.java:739) 
                           at android.os.Handler.dispatchMessage(Handler.java:95) 
                           at android.os.Looper.loop(Looper.java:135) 
                           at android.app.ActivityThread.main(ActivityThread.java:5254) 
                           at java.lang.reflect.Method.invoke(Native Method) 
                           at java.lang.reflect.Method.invoke(Method.java:372) 
                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
+0

Прочтите логарифм? Найденное исключение? Может быть, nullPointerException – user3502626

+0

Получает ли строка из вашего EditText [содержащее целое число синтаксического анализа] (https://developer.android.com/reference/java/lang/Integer.html#parseInt (java.lang.String)) –

ответ

1

Так что спасибо вам за ваш журнал!

Вы можете видеть в своем журнале, что у вас есть проблема, когда вы parseInt. Вы пытаетесь parseInt пустую строку.

Поэтому, когда пользователь ничего не пишет, вы должны сами установить значение по умолчанию. Вы можете сделать что-то подобное, что перед вашим разбором:

if(numero_creditos.equals("")) 
    numero_creditos = "0"; 

Но если бы я тебя, я бы заставить пользователь право непосредственно целое

+0

И конечно, вы должны сделать то же самое с «numero_faltas_actuales» –

+0

Это сработало !!!! Большое спасибо, на самом деле. –

+0

Рад помочь вам! –

0

Пожалуйста, покажите нам свой ящик журнала.

Возможно, сбой приложения, потому что у вас нет чехла по умолчанию в вашем корпусе коммутатора. Поэтому, если v.getId() - это не то, что вы думаете, это сработает.

Просто добавить, что в конце Вашего выключателя корпуса:

switch(v.getId()){ 
    case: ... 
    case: ... 
    default: Toast.makeText(getApplicationContext(),"v.getId = " + v.getId()); 
} 

Но мне было бы легче для меня, чтобы решить вашу проблему с журналом коробкой!

0

et1_creditos.getText() может, возможно, отправить нулевое значение. Тогда null.toString() не имеет смысла, потому что null не имеет toString().

попробовать:

String creditos = et1_creditos.getText() 
if(creditos != null){ 
    //stuff here 
} 
0

Это происходит сбой на этой линии.

 int numero_creditos1 = Integer.parseInt(numero_creditos); 

Если ваш numeor_creditos пуст, он не будет целым. Пробег

int numero_creditos1; 
if(TextUtils.isEmpty(numero_creditos){ 
    numero_creditos1 = 0; 
} else { 
    numero_creditos1 = Integer.parseInt(numero_creditos); 
} 
Смежные вопросы