2012-10-01 6 views
0

입력을 받아들이고이를 int로 자동 변경하는 앱을 만들려고합니다. 그러나 int를 얻으려고하면 응용 프로그램이 자동으로 중지됩니다. 아래 코드는 전체입니다 ...Int를 얻으 려 할 때 내 앱이 멈 춥니 다.

public class MainActivity extends Activity implements OnClickListener{ 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 

      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
      Button calculate = (Button)findViewById(R.id.calculateTip); 
      calculate.setOnClickListener(this); 

     }//end onCreate 

    public void onClick(View v) { 

      EditText money = (EditText)findViewById(R.id.bill); 
      int bill = Integer.parseInt(money.getText().toString()); 
      money.setText("Event Processed"); 

    }//end onClick 

    }//end MainActivity 
+0

어떤 오류가 발생합니까? XML을 게시 할 수 있습니까? –

+0

두 배가 아닌 정수 및 정수를 전송 하시겠습니까? –

+0

텍스트 필드의 내용은 무엇입니까? 그리고 LogCat 출력은 무엇입니까? – Eric

답변

1

구문 분석하려는 값이 실제로 정수가 아니기 때문에 응용 프로그램이 중지 된 것으로 판단됩니다. 해당 코드를 try catch에 던져야합니다.

예 :

public void onClick(View v) { 

     EditText money; 
     try 
     { 
      money = (EditText)findViewById(R.id.bill); 

      // This check makes sure that the EditText is returning the correct object. 
      if(money != null) 
      { 
       int bill = Integer.parseInt(money.getText().toString()); 
       money.setText("Event Processed"); 
      } 
     } 
     catch(NumberFormatException e) 
     { 
     // If we get in here that means the inserted value was not an Integer. So do    something. 
     //ie: 
     money.setText("Please enter a value amount"); 
     } 
    }//end onClick 

에 관계없이, 당신은 데이터의 무결성을 유지하기 위해 시도 캐치이 코드가 있어야합니다.

희망적으로 도움이됩니다. 건배.

+0

'onClick' 메소드 내에'money'를 지정하면 차이가 있습니까? 난 보통 그냥 onCreate에서 xml 참조를 할당 오전 – mrres1

+0

나는 일반적으로 전역 변수로 돈을 가지고 다음뿐만 아니라 onCreate에 할당합니다. 전역 변수로 돈을 사용하면 onClick과 같은 클래스의 아무 곳에서나 설정할 수 있습니다. 이 코드 샘플은 제공 한 코드로 수행 할 수있는 작업을 보여줍니다. – Dave

0

Object가 EditText의 인스턴스이고 null이 아닌 것은 확실합니까?

+2

은 .toString()에 아무런 문제가 없어야합니다. –

관련 문제