使用id查找元素获取信息添加到数组androidjava

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: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference

error1.1 是:

Unhandled exception: 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();}