android中从EditTExt内获取数据并转换成int类型的问题
(2013-04-16 11:02:11)
word/media/image1.gif转载▼
前几天想写一个Activity之间相互通信的Demo,遇到了点问题,我从EditTExt内获取数据并想转换成int类型老是不能,报错:(317): java.lang.NumberFormatException: unable to parse '' as integer。 经过这几天不断的尝试,以及好心的道友的帮助,总算把这个问题解决了。虽然解决了问题,但是具体原因尚不清楚,待高手解答。解决方法: 把从EditTExt内获取的数据转成int类型只要,必须要进行一个异常处理,并且要把获取数据和转换类型的代码写在Button的监听器里面。像这样写就能正确的转换成int类型并传入数据: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myEditText=(EditText)findViewById(R.id.myEditText); myTextView=(TextView)findViewById(R.id.myTextView); myButton=(Button)findViewById(R.id.myButton); myButton.setOnClickListener(new View.OnClickListener() { /*@Override public void onClick(View v) { // TODO Auto-generated method stub //方法1 if (myEditText != null) { String str = myEditText.getText().toString(); if (str != null &&str.length() > 0) { data = Integer.parseInt(str); } } //方法2 try{ data=Integer.parseInt(myEditText.getText().toString()); }catch (Exception e){ e.printStackTrace(); } //方法3 String str_data = myEditText.getText().toString(); if(TextUtils.isEmpty(str_data) || (str_data.trim().length() == 0)){ str_data = "0"; } data=Integer.parseInt(str_data); System.out.println(data*3); Intent intent = new Intent(); intent.setClass(Activity_08.this, Activity02.class); intent.putExtra("msg2", "information2"); startActivityForResult(intent , 0); } }); }而这样就不能传入数据: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myEditText=(EditText)findViewById(R.id.myEditText); myTextView=(TextView)findViewById(R.id.myTextView); if (myEditText != null) { String str = myEditText.getText().toString(); if (str != null &&str.length() > 0) { data = Integer.parseInt(str); } System.out.println(data*3); } }
本文来源:https://www.2haoxitong.net/k/doc/a14e61b7aaea998fcd220e22.html
文档为doc格式