java - 使用id查找元素获取信息并添加到数组android java

标签 java android arrays json

我正在使用

获取元素
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

错误1.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();}

关于java - 使用id查找元素获取信息并添加到数组android java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40035010/

相关文章:

javascript - Bookshelf.js - 如何仅获取一个查询的 'hidden' 字段?

c++ - 反向数组 - 没有第一个数字

java - lambda 表达式和实例化方法引用之间的不同行为

java - 如何在运行时修改注释的属性

android - 如何创建多平台本地化解决方案?

android - sqlite3权限被拒绝android

android - 关闭我的案例中已启动的 Activity

c# - 查找数组中的最大值但是为字符分配了数字

java - 为什么 .equals 方法在两个相同的值对象上失败?

java - Spring Security 工作时 Spring LdapRepository 不返回结果