0

I am having problems parsing JSON data to my android application. I need to parse a JSON object as listed below. For my application i want to pull this json data store it in an array. then display each question along with possible answers using text view and buttons. I then want to display then next question in the array along with the possible answers.

JSON Object

 {
    "52f66c6eb82944cc1c00002a": {
        "_id": {
            "$id": "52f66c6eb82944cc1c00002a"
        },
        "Question": "Capital city of England",
        "Answer 1": "Paris",
        "Answer 2": "Liverpool",
        "Correct Answer": "London"
    },
    "52f66c8ab82944780d000029": {
        "_id": {
            "$id": "52f66c8ab82944780d000029"
        },
        "Question": "Capital city of Ireland",
        "Answer 1": "Cork",
        "Answer 2": "Liverpool",
        "Correct Answer": "Dublin"
    }
}

android code

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

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    protected TextView TitleTextView;
    protected Button PossibleAnswer1;
    protected Button PossibleAnswer2;
    protected Button CorrectAnswer;
    protected String URL ="http://127.0.0.1/mongo-form-create-quiz/processform.php";
    protected HttpClient HTTPClient;
    protected HttpPost HTTPPost;
    protected HttpResponse ResponseFromWeb;
    protected String JSONString;
    protected JSONObject JSONObject;
    protected String JSONQuestion;
    protected String JSONPossibleAnswer1;
    protected String JSONPossibleAnswer2;
    protected String JSONCorrectAnswer;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppostresponse = new HttpPost("http://127.0.0.1/mongo-form-create-quiz/recordinput.php");
    Intent openLastActivity = new Intent("com.example.quizqizzdemo.LASTACTIVITY");


    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        StrictMode.ThreadPolicy policy = new StrictMode.
        ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 

        setContentView(R.layout.activity_main);

        HTTPClient = new DefaultHttpClient();
        HTTPPost = new HttpPost(URL);

        TitleTextView = (TextView) findViewById(R.id.Question_Title);


        PossibleAnswer1 = (Button) findViewById(R.id.PossibleAnswer1);

        PossibleAnswer2 = (Button) findViewById(R.id.PossibleAnswer2);

        CorrectAnswer = (Button) findViewById(R.id.CorrectAnswer);

        try{
            ResponseFromWeb = HTTPClient.execute(HTTPPost);

            JSONString = FormatJSONInput(
                    ResponseFromWeb.getEntity().getContent()).toString();
            JSONObject = new JSONObject(JSONString);

            JSONQuestion = JSONObject.getString("Question");
            JSONPossibleAnswer1 = JSONObject.getString("Answer 1");
            JSONPossibleAnswer2 = JSONObject.getString("Answer 2");
            JSONCorrectAnswer = JSONObject.getString("Correct Answer");

            TitleTextView.setText(JSONQuestion);
            PossibleAnswer1.setText(JSONPossibleAnswer1);
            PossibleAnswer2.setText(JSONPossibleAnswer2);
            CorrectAnswer.setText(JSONCorrectAnswer);

        }

    catch (JSONException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }



        PossibleAnswer1.setOnClickListener(new OnClickListener() {

              @Override
              public void onClick(View arg0) {

                  /*
                 Toast.makeText(getApplicationContext(), 
                               "Incorrect!!", Toast.LENGTH_LONG).show();
                 PossibleAnswer1.setBackgroundColor(Color.RED);
                 */

                    try {
                        // Add your data
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("UserAnswer", JSONPossibleAnswer1));
                        nameValuePairs.add(new BasicNameValuePair("CorrectAnswer", JSONCorrectAnswer));
                        httppostresponse.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                        // Execute HTTP Post Request
                        HttpResponse response = httpclient.execute(httppostresponse);


                        startActivity(openLastActivity);

                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }

              }
        });

        PossibleAnswer2.setOnClickListener(new OnClickListener() {

              @Override
              public void onClick(View arg0) {

                  /*
                 Toast.makeText(getApplicationContext(), 
                             "Incorrect!!", Toast.LENGTH_LONG).show();
                 PossibleAnswer1.setBackgroundColor(Color.RED);
                 */

                    try {
                        // Add your data
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("UserAnswer", JSONPossibleAnswer2));
                        nameValuePairs.add(new BasicNameValuePair("CorrectAnswer", JSONCorrectAnswer));
                        httppostresponse.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                        // Execute HTTP Post Request
                        HttpResponse response = httpclient.execute(httppostresponse);

                        startActivity(openLastActivity);

                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }

              }
        });

        CorrectAnswer.setOnClickListener(new OnClickListener() {

              @Override
              public void onClick(View arg0) {

                  /*
                 Toast.makeText(getApplicationContext(), 
                             "Correct!!", Toast.LENGTH_LONG).show();
                 CorrectAnswer.setBackgroundColor(Color.GREEN);
                 */

                try {
                    // Add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("UserAnswer", JSONCorrectAnswer));
                    nameValuePairs.add(new BasicNameValuePair("CorrectAnswer", JSONCorrectAnswer));
                    httppostresponse.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // Execute HTTP Post Request
                    HttpResponse response = httpclient.execute(httppostresponse);

                    startActivity(openLastActivity);

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                }
              }
        });
    }
    private StringBuilder FormatJSONInput(InputStream is) {
        String ReadLine = "";
        StringBuilder CorrectDBData = new StringBuilder();

        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
            while ((ReadLine = rd.readLine()) != null) {
                CorrectDBData.append(ReadLine);
            }
        }

        catch (IOException e) {
            e.printStackTrace();
        }
        return CorrectDBData;
    }

}

I can do this using an array of strings but for my application i need to display this data which is from a mongohq database.

I am a student and am new to Android, json and mongodb.

  • is this the complete json, what have you tried so far ? – amit singh Feb 08 '14 at 17:53
  • Yes the json is display on a php webpage which will increase as questions are added i can parse one question and display in on android application but i need display next question after a button is clicked – peterodoherty92 Feb 08 '14 at 17:57
  • if you are able to parse this json then what is the problem in displaying the data? – amit singh Feb 08 '14 at 18:00
  • I have added my java code that is working display one question and answers i now want to be able to display the next question when any button is pressed – peterodoherty92 Feb 08 '14 at 18:03
  • Part of my question is also how do i correctly parse the above json object and store its contents in an array – peterodoherty92 Feb 08 '14 at 18:12

1 Answers1

0

if you'll pull new question from server everytime you press on button. I suggest you to put those code into new method then just call method when you done work in onClick() method

but if you just get all questions at once i suggest you to convert it to JSONObject as you did then do like

ArrayList<JSONObject> list = new ArrayList<JSONObject>();
JSONArray names = json.names();
for(int i =0; i<json.length();i++){
   JSONObject innerJson = json.getJSONObject(names.optString(i));
   /* put stuffs in object*/
   /* add object to list */
   list.add("parse object");
}

after you got a list when you press next button you'll just get your object from the list instead

vfongmala
  • 185
  • 1
  • 2
  • 11
  • Ok but i am not sure that i will need to pull from the server each time a button is clicked? once the json object is created it once change using run time – peterodoherty92 Feb 08 '14 at 18:15
  • Thanks i am a little confused i am sorry. what is json.names() ? how do i get that ? is the inner the questions? and tehn i add them to an object for each loop and then it to the list? – peterodoherty92 Feb 08 '14 at 18:26
  • json.names() is to get all names from your JSONObject it'll return JSONArray which is `{["52f66c6eb82944cc1c00002a","52f66c8ab82944780d000029"]}` so you can use loop for get each JSONObject for your question to add to your list and use that list to work on your application later on – vfongmala Feb 09 '14 at 03:59