2016-03-15 3 views
0

Я начинаю изучать андроид, одним из моих первых упражнений является калькулятор. Прежде чем делать правильный калькулятор, я планировал создать очень простое приложение, в котором пользователь просто вводит 2 номера через EditText, выбирает арифметическую операцию с кнопками и получает результат в TextView при нажатии кнопки «igual».Разбор входных строк целых чисел, похоже, разбивает мое приложение

Моя идея состояла в том, чтобы объявить 2 строк (sinput1 & sinput2), и они получают текст из каждого EditText (Num1 & num2), а затем разобрать Струны для целочисленных переменных (input1 & input2).

Все макеты выглядели и работали нормально, прежде чем я начал кодировать способ работы, но каждый раз, когда я запускаю приложение (с моим телефоном или с эмулятором), он вылетает, когда я нажимаю EditText, чтобы ввести числа. Я поставлю здесь свой код, может быть, моя ошибка в другом месте.

Я думал, что изменение способа работы переключателей на onClick void решит его, и частично это произошло, потому что до того, как я использовал серию if и приложения, разбился даже до загрузки макета. Но теперь я застрял в этом вопросе.

package com.example.caye.colores; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

public class MainActivity extends AppCompatActivity implements View.OnClickListener{ 

    Button mas; 
    Button menos; 
    Button por; 
    Button div; 
    Button igual; 

    EditText num1; 
    EditText num2; 

    TextView letrero1; 
    TextView letrero2; 
    TextView resultado; 

    int input1; 
    int input2; 
    String sinput1; 
    String sinput2; 
    int operacion; 

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

     mas = (Button)this.findViewById(R.id.mas); 
     mas.setOnClickListener(this); 
     mas.setText("+"); 
     menos = (Button)this.findViewById(R.id.menos); 
     menos.setOnClickListener(this); 
     menos.setText("-"); 
     por = (Button)this.findViewById(R.id.por); 
     por.setOnClickListener(this); 
     por.setText("*"); 
     div = (Button)this.findViewById(R.id.div); 
     div.setOnClickListener(this); 
     div.setText("/"); 
     igual = (Button)this.findViewById(R.id.igual); 
     igual.setOnClickListener(this); 
     igual.setText("="); 

     num1 = (EditText)this.findViewById(R.id.num1); 
     num1.setOnClickListener(this); 
     num2 = (EditText)this.findViewById(R.id.num2); 
     num2.setOnClickListener(this); 

     letrero1 = (TextView)this.findViewById(R.id.letrero1); 
     letrero1.setText("Número 1"); 
     letrero2 = (TextView)this.findViewById(R.id.letrero2); 
     letrero2.setText("Número 2"); 
     resultado = (TextView)this.findViewById(R.id.resultado); 
     resultado.setText(""); 
    } 

    public void onClick(View view){ 
     switch (view.getId()){ 
      case R.id.mas: 
       operacion = 1; 
       break; 
      case R.id.menos: 
       operacion = 2; 
       break; 
      case R.id.por: 
       operacion = 3; 
       break; 
      case R.id.div: 
       operacion = 4; 
       break; 
      case R.id.num1: 
       sinput1 = num1.getText().toString(); 
       input1 = Integer.parseInt(sinput1); 
       break; 
      case R.id.num2: 
       sinput2 = num2.getText().toString(); 
       input2 = Integer.parseInt(sinput2); 
       break; 
      case R.id.resultado: 
       switch (operacion){ 
        case 1: 
         resultado.setText(input1 + input2); 
         break; 
        case 2: 
         resultado.setText(input1 - input2); 
         break; 
        case 3: 
         resultado.setText(input1 * input2); 
         break; 
        case 4: 
         resultado.setText(input1/input2); 
         break; 
        default: 
         resultado.setText("Elige una operación"); 
         break; 
       } 
       break; 
     } 
    } 
} 

Здесь.

03-15 09:41:24.234 22041-22041/? D/dalvikvm: Late-enabling CheckJNI 
03-15 09:41:24.334 22041-22041/com.example.caye.colores D/HyLog: I : /data/font/config/dfactpre.dat, No such file or directory (2) 
03-15 09:41:24.338 22041-22041/com.example.caye.colores D/asset: AssetManager-->addDefaultAssets CIP path not exsit! 
03-15 09:41:24.502 22041-22041/com.example.caye.colores W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;) 
03-15 09:41:24.502 22041-22041/com.example.caye.colores I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested 
03-15 09:41:24.502 22041-22041/com.example.caye.colores W/dalvikvm: VFY: unable to resolve interface method 15038: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z 
03-15 09:41:24.502 22041-22041/com.example.caye.colores D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002 
03-15 09:41:24.503 22041-22041/com.example.caye.colores I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode 
03-15 09:41:24.503 22041-22041/com.example.caye.colores W/dalvikvm: VFY: unable to resolve interface method 15042: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode; 
03-15 09:41:24.503 22041-22041/com.example.caye.colores D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002 
03-15 09:41:24.580 22041-22041/com.example.caye.colores I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations 
03-15 09:41:24.580 22041-22041/com.example.caye.colores W/dalvikvm: VFY: unable to resolve virtual method 396: Landroid/content/res/TypedArray;.getChangingConfigurations()I 
03-15 09:41:24.580 22041-22041/com.example.caye.colores D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002 
03-15 09:41:24.581 22041-22041/com.example.caye.colores I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType 
03-15 09:41:24.581 22041-22041/com.example.caye.colores W/dalvikvm: VFY: unable to resolve virtual method 418: Landroid/content/res/TypedArray;.getType (I)I 
03-15 09:41:24.581 22041-22041/com.example.caye.colores D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002 
03-15 09:41:24.690 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false 
03-15 09:41:24.690 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false 
03-15 09:41:24.838 22041-22041/com.example.caye.colores D/GraphicBuffer: create handle(0x619ca788) (w:544, h:960, f:1) 
03-15 09:41:24.844 22041-22041/com.example.caye.colores D/OpenGLRenderer: Enabling debug mode 0 
03-15 09:41:24.846 22041-22041/com.example.caye.colores D/GraphicBuffer: create handle(0x61bf9318) (w:1216, h:832, f:1) 
03-15 09:41:24.857 22041-22041/com.example.caye.colores D/OpenGLRenderer: setViewport 540x960 <0x619ca8c0> 
03-15 09:41:24.888 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false 
03-15 09:41:24.888 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false 
03-15 09:41:24.890 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false 
03-15 09:41:24.890 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false 
03-15 09:41:24.946 22041-22041/com.example.caye.colores D/cliptray_Editor: setInputTypeforClipTray(): 0 
03-15 09:41:24.960 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false 
03-15 09:41:24.960 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false 
03-15 09:41:24.960 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false 
03-15 09:41:24.961 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false 
03-15 09:41:25.008 22041-22041/com.example.caye.colores D/cliptray_Editor: setInputTypeforClipTray(): 0 
03-15 09:41:25.446 22041-22041/com.example.caye.colores D/GraphicBuffer: create handle(0x62130980) (w:544, h:960, f:1) 
03-15 09:41:25.957 22041-22041/com.example.caye.colores D/GraphicBuffer: create handle(0x6201a318) (w:544, h:960, f:1) 
03-15 09:41:28.168 22041-22041/com.example.caye.colores I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN 
03-15 09:41:28.316 22041-22041/com.example.caye.colores I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP 
03-15 09:41:28.341 22041-22041/com.example.caye.colores V/Provider/Settings: get setting for user 0 by user 0 so skipping cache 
03-15 09:41:28.342 22041-22041/com.example.caye.colores V/Provider/Settings: invalidate [system]: current 32 != cached 0 
03-15 09:41:28.347 22041-22041/com.example.caye.colores D/AndroidRuntime: Shutting down VM 
03-15 09:41:28.347 22041-22041/com.example.caye.colores W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4249be48) 
03-15 09:41:28.355 22041-22041/com.example.caye.colores E/AndroidRuntime: FATAL EXCEPTION: main 
                      Process: com.example.caye.colores, PID: 22041 
                      java.lang.NumberFormatException: Invalid int: "" 
                       at java.lang.Integer.invalidInt(Integer.java:137) 
                       at java.lang.Integer.parseInt(Integer.java:358) 
                       at java.lang.Integer.parseInt(Integer.java:331) 
                       at com.example.caye.colores.MainActivity.onClick(MainActivity.java:81) 
                       at android.view.View.performClick(View.java:4461) 
                       at android.view.View$PerformClick.run(View.java:18523) 
                       at android.os.Handler.handleCallback(Handler.java:733) 
                       at android.os.Handler.dispatchMessage(Handler.java:95) 
                       at android.os.Looper.loop(Looper.java:136) 
                       at android.app.ActivityThread.main(ActivityThread.java:5118) 
                       at java.lang.reflect.Method.invokeNative(Native Method) 
                       at java.lang.reflect.Method.invoke(Method.java:515) 
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605) 
                       at dalvik.system.NativeStart.main(Native Method) 
03-15 09:41:30.416 22041-22041/com.example.caye.colores I/Process: Sending signal. PID: 22041 SIG: 9 
+1

это сбой правый !. поэтому разместите stacktrace. Вы также вызываете, проверяете, вводит ли пользователь что-либо в editText с 'if (! TextUtils.isEmpty (« ваша строка »)', чтобы быть безопасным. – Raghunandan

+0

во-вторых получить значение из editText при нажатии кнопки мыши, когда вы нажимаете на свой текст редактирования, он фокусируется, чтобы вы введите что-то – Raghunandan

+0

Используйте инструкцию try для предотвращения сбоя и возможности утечки точной проблемы для устранения неполадок. – codermjb

ответ

0

Во-первых, вам необходимо предоставить трассировку стека вашей аварии.

Во-вторых, очень вероятно, что ваша ошибка исходит из преобразования Integer.parseInt(sinput1); строки в Integer.

Вы уверены, что у вас есть целые числа? Вероятно, вы пытаетесь преобразовать значение «» в целое.

Проверьте, не является ли EditText пустым и содержит ли он цифры.

if(!TextUtils.isEmpty(sinput1) && TextUtils.isDigitsOnly(sinput1)) { 
    input1 = Integer.parseInt(sinput1); 
} 
0

Мы не нужно использовать setOnClickListener для EditTexts попробуйте этот код

package com.example.caye.colores; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

public class MainActivity extends AppCompatActivity implements View.OnClickListener{ 

Button mas; 
Button menos; 
Button por; 
Button div; 
Button igual; 

EditText num1; 
EditText num2; 

TextView letrero1; 
TextView letrero2; 
TextView resultado; 

int input1; 
int input2; 
String sinput1; 
String sinput2; 
int operacion; 

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

    mas = (Button)this.findViewById(R.id.mas); 
    mas.setOnClickListener(this); 
    mas.setText("+"); 
    menos = (Button)this.findViewById(R.id.menos); 
    menos.setOnClickListener(this); 
    menos.setText("-"); 
    por = (Button)this.findViewById(R.id.por); 
    por.setOnClickListener(this); 
    por.setText("*"); 
    div = (Button)this.findViewById(R.id.div); 
    div.setOnClickListener(this); 
    div.setText("/"); 
    igual = (Button)this.findViewById(R.id.igual); 
    igual.setOnClickListener(this); 
    igual.setText("="); 

    num1 = (EditText)this.findViewById(R.id.num1); 
    //num1.setOnClickListener(this); 
    num2 = (EditText)this.findViewById(R.id.num2); 
    //num2.setOnClickListener(this); 

    letrero1 = (TextView)this.findViewById(R.id.letrero1); 
    letrero1.setText("Número 1"); 
    letrero2 = (TextView)this.findViewById(R.id.letrero2); 
    letrero2.setText("Número 2"); 
    resultado = (TextView)this.findViewById(R.id.resultado); 
    resultado.setText(""); 
} 

public void onClick(View view){ 
    switch (view.getId()){ 
     case R.id.mas: 
      operacion = 1; 
      break; 
     case R.id.menos: 
      operacion = 2; 
      break; 
     case R.id.por: 
      operacion = 3; 
      break; 
     case R.id.div: 
      operacion = 4; 
      break; 

/* 
     case R.id.num1: 
      sinput1 = num1.getText().toString(); 
      input1 = Integer.parseInt(sinput1); 
      break; 
     case R.id.num2: 
      sinput2 = num2.getText().toString(); 
      input2 = Integer.parseInt(sinput2); 
      break; 
*/ 
     case R.id.resultado: 


      sinput1 = num1.getText().toString(); 
      sinput2 = num2.getText().toString(); 

      if(!TextUtils.isEmpty(sinput1) && TextUtils.isDigitsOnly(sinput1)         
      { 
      input1 = Integer.parseInt(sinput1); 

      } 



      if(!TextUtils.isEmpty(sinput2) && TextUtils.isDigitsOnly(sinput2)         
      { 
      input2 = Integer.parseInt(sinput2); 

      } 



      if(input1 != null && input2 != null) { 

      switch (operacion){ 
       case 1: 
        resultado.setText(input1 + input2); 
        break; 
       case 2: 
        resultado.setText(input1 - input2); 
        break; 
       case 3: 
        resultado.setText(input1 * input2); 
        break; 
       case 4: 
        resultado.setText(input1/input2); 
        break; 
       default: 
        resultado.setText("Elige una operación"); 
        break; 
       } else { 

        resultado.setText("Check the inputs"); 

       } 

      } 
      break; 
    } 
} 
} 
0

Я думаю, содержание редактирования текста является пустым в то время вы выбираете редактировать тексты num1/num2. Лучший способ - редактировать текст ввода текста при нажатии кнопки. Также проверьте, что введенный номер или нет, используя API isDigitsOnly().

Смежные вопросы