簡體   English   中英

使用id查找元素以獲取信息並添加到數組android java

[英]Use id to find the element to get information and add to array android java

我正在使用元素

JSONArray myArray = new JSONArray();
for (View touchable : allTouchables) {
JSONObject j = new JSONObject();
// To check if touchable view is button or not
//if( touchable instanceof LinearLayout) {
//System.out.println("LinearLayout "+touchable.toString());
//}
if( touchable instanceof Button) { 
     System.out.println("Button "+touchable.getId());
}
if( touchable instanceof TextView) { 
     TextView question = (TextView) findViewById(touchable.getId());
     System.out.println("TextView "+ question.getText().toString());
     //j.put("key",value);
}
if( touchable instanceof RadioButton) {
     RadioButton value = (RadioButton)findViewById(touchable.getId());
     System.out.println("RadioButton "+value.getText().toString());
}
if( touchable instanceof CheckBox) {
     CheckBox value = (CheckBox)findViewById(touchable.getId());
     System.out.println("CheckBox "+value.getText().toString());
}
j.put("array",myArray);// error1.1
}

java.lang.NullPointerException:嘗試在空對象引用上調用虛擬方法'java.lang.CharSequence android.widget.TextView.getText()'

和error1.1是:

未處理的異常:org.json.JSONException

我的問題是:

  1. 如何使用touchable.getId()獲取textview單選按鈕和復選框的ID? 因此,我可以獲得有關所述元素的更多信息。
  2. 修復異常。

1)代替findViewById(touchable.getId())

用這個

if( touchable instanceof TextView) { 
 TextView question = (TextView)touchable;
 System.out.println("TextView "+ question.getText().toString());}

2)通過適當的try catch方法處理異常

try {
j.put("array",myArray);} catch (JSONException e) {e.printStackTrace();}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM