-2

Unfortunately, I cannot say much, just that it fails. I'm trying to understand how to parse a JSON array for Android. Below is what I have now. I'm sure it's no where close to working. I've tried breakpoints to see where exactly it bugs out, but it doesn't get that far.

My code:

package com.example.testers;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    private final String USER_AGENT = "Mozilla/5.0";

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

        JSONArray mJsonArray = null;
        try {
            mJsonArray = new JSONArray(sendGet());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject mJsonObject = new JSONObject();
        for (int i = 0; i < mJsonArray.length(); i++) {
            try {
                mJsonObject = mJsonArray.getJSONObject(i);
                mJsonObject.getString("id");
                mJsonObject.getString("title");
                mJsonObject.getString("post");
                mJsonObject.getString("author");
                mJsonObject.getString("tags");
                mJsonObject.getString("datePosted");

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

    @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;
    }

    private String sendGet() throws Exception {

        String url = "http://www.craftbrothers.net/news/app.php";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        return response.toString();

    }

    // HTTP POST request
    private void sendPost() throws Exception {

        String url = "https://selfsolve.apple.com/wcResults.do";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        // add request header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        System.out.println(response.toString());

    }


}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • 1
    This helped me a lot when I made something similar: http://jsonlint.com/. Put your JSON in there. Edit: Oh, it's valid JSON. – bbill Jun 25 '13 at 23:02
  • 1
    Try here - http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ – David Jashi Jun 25 '13 at 23:02
  • 1
    Fails can have 2 side effects, 1) a crash 2) null return values. When you say you cannot say much, you are not trying hard enough to post a complete and a good question. – Siddharth Jun 26 '13 at 04:08
  • no it's a legitament question. just that unfortunetly I'm unable to supply detail since it gets absolutly nowhere to begin with – BizBink Jun 26 '13 at 20:16

1 Answers1

0

First of all, you're not doing anything with the values you try to parse from the JSON response. When you call

mJsonObject.getString(String)

you're not assigning the getString() result to anything, so you certainly won't see it on your UI, or in any logs.

Also, MainActivity#onCreate() is called on the UI thread (aka main thread). You shouldn't perform network operations on the main thread, as it blocks the UI for the user (freezes).

You should normally use something like AsyncTask to perform network requests in the background, and then display the results to the UI in the task's onPostExecute() method.

Depending on which Android version you're running on, the system may actually throw an exception if you make this request on the UI thread, as you are.

Community
  • 1
  • 1
Nate
  • 31,017
  • 13
  • 83
  • 207
  • but I am doing what you said. Im putting it into an array. And I know I shouldnt place it there since it will wait until it finishes the request but thanks for the tip – BizBink Jun 26 '13 at 01:54
  • @BizBink, the part about `AsyncTask` is not a **tip**. You need to take that work off the UI thread. In newer (3.0+ I think) versions of Android, it will actually fail if you try to make this request on the UI thread, which could be why you never even see the request get to your breakpoints. As far as the JSON parsing itself, your code looks fine, assuming you actually do something with the results. – Nate Jun 26 '13 at 03:56
  • Oh. I've done this before tho running it in a UI Thread but not the main one. Compiling was the same except device debugging on runs 4.1.2 now instead of 2.2. Ill try what you said. – BizBink Jun 26 '13 at 20:19
  • @BizBink, the UI thread **is the main one**. Those two terms are the same. Perhaps it would be good [to review this document on Android threading](http://android-developers.blogspot.com/2009/05/painless-threading.html). – Nate Jun 27 '13 at 01:20