Brownman Revival Brownman Revival - 10 days ago 5x
JSON Question

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

I am getting element using

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

and error1.1 is:

Unhandled exception: org.json.JSONException

My Question is:

  1. How to use
    to get the id of textview radio button and checkbox? So I can get further information for the said element.

  2. Fix exception.


1) Instead of findViewById(touchable.getId())

Use this

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

2) handle exception by proper try catch method

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