【问题标题】:Use id to find the element to get information and add to array android java使用id查找元素获取信息并添加到数组android java
【发布时间】:2016-10-14 04:37:44
【问题描述】:

我正在使用

获取元素
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. 修复异常。

【问题讨论】:

  • 可以直接将touchable投给view,不需要findViewById,TextView question = (TextView)touchable;
  • @darwin 您可以在回答问题时添加答案,以便我们关闭 OP

标签: java android arrays json


【解决方案1】:

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

【讨论】:

  • 第二个问题怎么样?顺便说一句,我需要 2 分钟来接受答案
  • 您是否遇到 json 异常的编译时错误?
  • 我有一个问题,队友 textview 不是获取 textvuew 的文本,而是获取单选按钮的文本。这是获取文本ivew文本的正确方法吗?
  • 代码看起来不错,您可以尝试调试并确保获得正确的视图是 if 语句。
  • 我的意思是也许没有办法获得 textview?因为单选按钮和复选框以及编辑文本工作正常,所以我正在输入文本。但对于 textview 没有任何回报。让我再检查一遍
猜你喜欢
  • 2011-07-17
  • 2014-04-05
  • 1970-01-01
  • 2020-11-25
  • 2012-10-27
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
相关资源
最近更新 更多