1

I have a JSON array sent from my SQL server via PHP in the following format which I am finding difficult to parse without encountering errors.

[
{
    "placename": "place1",
    "latitude": "50",
    "longitude": "-0.5",
    "question": "place1 existed when?",
    "answer1": "1800",
    "answer2": "1900",
    "answer3": "1950",
    "answer4": "2000",
    "correctanswer": "1900"
},
{
    "placename": "place2",
    "latitude": "51",
    "longitude": "-0.5",
    "question": "place2 existed when?",
    "answer1": "800",
    "answer2": "1000",
    "answer3": "1200",
    "answer4": "1400",
    "correctanswer": "800"
},
{
    "placename": "place3",
    "latitude": "52",
    "longitude": "-1",
    "question": "place 3 was established when?",
    "answer1": "2001",
    "answer2": "2005",
    "answer3": "2007",
    "answer4": "2009",
    "correctanswer": "2009"
}
]

I have verified my JSON at JSONLint and it comes up as valid. I have also used log code to print out my JSON in the Eclipse app debugger after my HTTP client has processed it and that also works fine (it shows the JSON as above so I know it has downloaded correctly).

I'm trying to fit the JSON Parser into the following activity but all my attempts thus far have either contained too many errors to run or have simply returned no results because of JSON parsing errors.

Here is the code of the main activity. The code for this activity is adapted from NewThinkTank.com (Android Development 15) and I'm trying to tweak it for my needs but the structure of the JSON used in the example is very different to mine.

I was hoping someone could suggest some code, or give me some pointers, as to how I could go about parsing this JSON array properly. I am fairly new to Android programming so this is a fairly steep task to figure out on my own.

Thanks for your time.

public class MainActivity extends Activity {

// The JSON REST Service I will pull from
static String dlquiz = "http://exampleserver.php";


// Will hold the values I pull from the JSON 
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";

@Override
public void onCreate(Bundle savedInstanceState) {
    // Get any saved data
    super.onCreate(savedInstanceState);

    // Point to the name for the layout xml file used
    setContentView(R.layout.main);

    // Call for doInBackground() in MyAsyncTask to be executed
    new MyAsyncTask().execute();

}
// Use AsyncTask if you need to perform background tasks, but also need
// to change components on the GUI. Put the background operations in
// doInBackground. Put the GUI manipulation code in onPostExecute

private class MyAsyncTask extends AsyncTask<String, String, String> {

    protected String doInBackground(String... arg0) {

        // HTTP Client that supports streaming uploads and downloads
        DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());

        // Define that I want to use the POST method to grab data from
        // the provided URL
        HttpPost httppost = new HttpPost(dlquiz);

        // Web service used is defined
        httppost.setHeader("Content-type", "application/json");

        // Used to read data from the URL
        InputStream inputStream = null;

        // Will hold the whole all the data gathered from the URL
        String result = null;

        try {

            // Get a response if any from the web service
            HttpResponse response = httpclient.execute(httppost);        

            // The content from the requested URL along with headers, etc.
            HttpEntity entity = response.getEntity();

            // Get the main content from the URL
            inputStream = entity.getContent();

            // JSON is UTF-8 by default
            // BufferedReader reads data from the InputStream until the Buffer is full
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);

            // Will store the data
            StringBuilder theStringBuilder = new StringBuilder();

            String line = null;

            // Read in the data from the Buffer untilnothing is left
            while ((line = reader.readLine()) != null)
            {

                // Add data from the buffer to the StringBuilder
                theStringBuilder.append(line + "\n");
            }

            // Store the complete data in result
            result = theStringBuilder.toString();

        } catch (Exception e) { 
            e.printStackTrace();
        }
        finally {

            // Close the InputStream when you're done with it
            try{if(inputStream != null)inputStream.close();}
            catch(Exception e){}
        }

        //this allowed me to verify the JSON download in the debugger
        Log.v("JSONParser RESULT ", result);

        // JSON parsing needs to happen here...



        return result;

    }

    protected void onPostExecute(String result){

        // Gain access so I can change the TextViews
        TextView line1 = (TextView)findViewById(R.id.line1); 
        TextView line2 = (TextView)findViewById(R.id.line2); 
        TextView line3 = (TextView)findViewById(R.id.line3); 

        // Change the values for all the TextViews
        line1.setText("Place Name: " + placename); 

        line2.setText("Question: " + question); 

        line3.setText("Correct Answer: " + correctanswer);

    }

}

}

rtg93
  • 23
  • 2
  • 6

1 Answers1

1

Check this answer out: How to parse JSON in Android

You'll be using:

    JSONArray array = new JSONArray(result);

From there, you'll loop through and get each JSONObject:

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

    //now, get whatever value you need from the object:
    placename = obj.getString("placename");

    //or if on the MainUI thread you can set your TextView from here:
    yourTextView.setText(obj.getString("placename"));
}

Good luck!

Community
  • 1
  • 1
Ben Krig
  • 101
  • 1
  • 5
  • Thanks for your response. This is something I tried already and the problem I'm having here is "JSONArray array = new JSONArray(result);' throws up "unhandled exception type JSON exception" in Eclipse so I can't even run the app. This, to me, makes no sense because all I'm doing is saying that "array" is a new JSONArray using the compiled string "result". For reference, this is what I've put into my mainactivity, http://pastebin.com/s1TvkCC1 – rtg93 Apr 10 '15 at 08:32
  • I just needed to enclose in try and catch loop, and a bit of tweaking got it working in the end. The result isn't what I wanted (it's outputting strings and I need lists - derp), but the code you provided fixed my problem so thanks for your help! – rtg93 Apr 10 '15 at 10:33