user3585229
user3585229

Reputation: 11

Android Json parsing to Arraylist

Hi Guys im new in android development please help me to read all json data in to android and how to put in ArrayList ..here i have 4 set of questions (4 x 4) = 16 questions .. in one set i have 4 question i want to call 1 question randomly from set .. please help me .. Thanks in advance

    package com.example.truefalsegame;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xml.sax.SAXException;

//import com.example.jsonparser.R;



import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity 
{
    SAXParserFactory factory;
    SAXParser saxParser;
    String datas;
    String SrData = "";
    String queData = "";
    String ansData = "";
    String des;
    TextView srNo_txt, questions_txt, answer_txt;
    ImageView imageView;

    ArrayList<String> list = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        questions_txt = (TextView) findViewById(R.id.QuestionTxt);

        imageView = (ImageView)findViewById(R.id.imageView1);

        factory = SAXParserFactory.newInstance();



         try {
            saxParser = factory.newSAXParser();
            InputStream is = getAssets().open("concepts.json");

            InputStreamReader isr=new InputStreamReader(is);
            BufferedReader br=new BufferedReader(isr);
            String str;
            StringBuffer sb=new StringBuffer();


            while((str=br.readLine())!=null)
            {


            sb = sb.append(str);
            datas =(str);
            list.add(datas);


            }

            str = sb.toString();

              JSONArray jsonarray = new JSONArray(str);

              for(int i=0; i<jsonarray.length(); i++)
              {
                    JSONObject obj = jsonarray.getJSONObject(i);

                    String questions = obj.getString("Questions"); 
                    JSONArray question = obj.getJSONArray("Questions");
                    JSONObject ids = question.getJSONObject(0);
                    des = ids.getString("Question");

                    Log.d("hitesh", "des : "+ des );
                    //String answers = obj.getString("Answer");
                    int srno = i+1;

                    System.out.println(questions);
                    //System.out.println(answers);
                    queData += des+" \n ";


                }   

              questions_txt.setText(""+queData);





        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

    }

    private String append(String str) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Here is my Json file My jsonfile name is (concepts.json) and its in Assets folder

[
    {
        "Concept": "1",
        "Questions": [
            {
                "Question": "Carbon compounds are only straight chain compounds",
                "Answer": "F"
            },
            {
                "Question": "Carbon compounds are only cyclic compounds",
                "Answer": "F"
            },
            {
                "Question": "Carbon - Carbon linkage may form straight chain, branched chain and ring like or cyclic compounds",
                "Answer": "T"
            },
            {
                "Question": "Carbon compounds can't be cyclic compounds",
                "Answer": "F"
            }
        ]
    },
    {
        "Concept": "2",
        "Questions": [
            {
                "Question": "Saturated carbon compounds are highly reactive",
                "Answer": "F"
            },
            {
                "Question": "Unsaturated organic compounds are more reactive than saturated organic compounds",
                "Answer": "T"
            },
            {
                "Question": "Unsaturated organic compounds are less reactive than saturated organic compounds",
                "Answer": "F"
            },
            {
                "Question": "Alkanes are less reactive than alkynes",
                "Answer": "T"
            }
        ]
    },
    {
        "Concept": "3",
        "Questions": [
            {
                "Question": "Hydrocarbons contain only carbon and hydrogen",
                "Answer": "T"
            },
            {
                "Question": "Hydrocarbons contain only carbon",
                "Answer": "F"
            },
            {
                "Question": "A compound of carbon and oxygen can be hydrocarbon",
                "Answer": "F"
            },
            {
                "Question": "A compound of carbon and nitrogen can be hydrocarbon",
                "Answer": "F"
            }
        ]
    },
    {
        "Concept": "3",
        "Questions": [
            {
                "Question": "Diagram",
                "Answer": "T"
            },
            {
                "Question": "Diagram",
                "Answer": "T"
            },
            {
                "Question": "Diagram",
                "Answer": "F"
            },
            {
                "Question": "Diagram",
                "Answer": "F"
            }
        ]
    }
]

Upvotes: 1

Views: 696

Answers (2)

pawel-schmidt
pawel-schmidt

Reputation: 1165

I recommend to use Gson Library - it's probably most elegant way to deal with JSON data.

All you need to do is create your model objects to store your read data and add a couple of lines to MainActivity. Here are model classes:

Concept.java

import java.util.List;

public class Concept {

    private String concept;
    private List<Question> questions;

    // Remember to DO NOT add constructor with params when you don't have default 
    // constructor! Otherwise Gson will not be able to construct object with 
    // default constructor by using reflection mechanism.

    public String getConcept() {
        return concept;
    }

    public List<Question> getQuestions() {
        return questions;
    }
}

Question.java

public class Question {

    private String question;
    private String answer;

    // Remember to DO NOT add constructor...

    public boolean getAnswer() {
        return answer != null && answer.equals("T");
    }

    public String getQuestion() {
        return question;
    }
}

As you can see, there is String answer field converted to boolean in method getAnswer. Better solution might be to use boolean values in your JSON file (i. e. "Answer": true). Please notice that field names are the same as in JSON file.

When you have model, you need to add the following code to your MainActivity:

MainActivity.java

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;
// some other imports...

public class MainActivity extends Activity {

    // fields, methods, etc...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final String fileContent = readFile();

        final Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                .create();

        final Type collectionType = new TypeToken<List<Concept>>(){}.getType();

        final List<Concept> concepts = gson.fromJson(fileContent, collectionType);
        final Concept firstConcept = concepts.get(0);
        firstConcept.getConcept(); // "1"
        final Question question = firstConcept.getQuestions().get(0);
        question.getQuestion();    // "Carbon compounds are only straight chain compounds"
        question.getAnswer();      // false

    }
}

Explanation

        final Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                .create();

We initialise our Gson parser using builder, because we need to set non-default naming policy. UPPER_CAMEL_CASE is camel case starting with upper letter.

        final Type listType = new TypeToken<List<Concept>>(){}.getType();

        final List<Concept> concepts = gson.fromJson(fileContent, listType);

Here we build a type of returned data. Root element in your JSON is array that's why we use List type. We also could use array type, but lists are easier to manage. fileContent and listType are passed to method fromJson which parses data and returns result of type passed as second parameter.

Upvotes: 1

DDsix
DDsix

Reputation: 1984

I would recommend you to use the Gson library to transform the Json object to Java object. Then, you can choose a random object from the List<> and remove it from the list (so your random mode of choice wouldn't chose it again).

Upvotes: 1

Related Questions