0

I'm attempting to pull information from an API via JSON on Android. I've successfully downloaded the information, now I need to put it in the JSONArray given the tag "Categories". Ultimately this is going into a listview. Here is my code:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;


public class jsonParser {

    //initialize
    static JSONObject object =null;

    public jsonParser(){

    }

     public JSONObject getJSONfromURL (String url){
            //HTTP call
            try{
                URLConnection connection = new URL(url).openConnection();

                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 2048 * 16);
                StringBuffer builder = new StringBuffer();
                String line;

                while ((line = reader.readLine()) != null) {
                  builder.append(line).append("\n");
                }
                String blah = builder.toString();

                //Parsing string into JSONArray
                JSONObject object = new JSONObject ( new String(builder.toString()) );
                Log.e("success","created object: " + object);

                } catch(Exception e){
                    Log.e("Http Error","Error in http connection " + e.toString());

                }


            return object;
        }
}

Here is the Logcat:

05-12 16:57:54.040: E/success(9625): created object: {"Categories":[{"id":"2","name":"Glass Repair"},{"id":"3","name":"Appliance Repair"},{"id":"4","name":"Air Conditioning"},{"id":"5","name":"Community Involvement"},{"id":"6","name":"Electrical"},{"id":"7","name":"Flooring"},{"id":"8","name":"Heating Repair"},{"id":"9","name":"Landscaping"},{"id":"10","name":"Plumbing"},{"id":"11","name":"Remodeling\/Renovation"},{"id":"12","name":"Window Coverings"}]}
05-12 16:57:54.040: E/JSON Variable(9625): json returns this value: null
05-12 16:57:54.070: E/Test JSON(9625): JSON s returns: null
05-12 16:57:54.070: W/dalvikvm(9625): threadid=1: thread exiting with uncaught exception (group=0x416bf438)
05-12 16:57:54.070: E/AndroidRuntime(9625): FATAL EXCEPTION: main
05-12 16:57:54.070: E/AndroidRuntime(9625): java.lang.NullPointerException
05-12 16:57:54.070: E/AndroidRuntime(9625):     at com.example.hstnc_activity.DisplayServiceActivity$Request.onPostExecute(DisplayServiceActivity.java:104)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at com.example.hstnc_activity.DisplayServiceActivity$Request.onPostExecute(DisplayServiceActivity.java:1)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at android.os.AsyncTask.finish(AsyncTask.java:631)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at android.os.Looper.loop(Looper.java:137)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at android.app.ActivityThread.main(ActivityThread.java:4918)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at java.lang.reflect.Method.invokeNative(Native Method)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at java.lang.reflect.Method.invoke(Method.java:511)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
05-12 16:57:54.070: E/AndroidRuntime(9625):     at dalvik.system.NativeStart.main(Native Method)

Lastly here's the JSON information (used jsonlint.com to grab this):

{
    "Categories": [
        {
            "id": "2",
            "name": "Glass Repair"
        },
        {
            "id": "3",
            "name": "Appliance Repair"
        },
        {
            "id": "4",
            "name": "Air Conditioning"
        },
        {
            "id": "5",
            "name": "Community Involvement"
        },
        {
            "id": "6",
            "name": "Electrical"
        },
        {
            "id": "7",
            "name": "Flooring"
        },
        {
            "id": "8",
            "name": "Heating Repair"
        },
        {
            "id": "9",
            "name": "Landscaping"
        },
        {
            "id": "10",
            "name": "Plumbing"
        },
        {
            "id": "11",
            "name": "Remodeling/Renovation"
        },
        {
            "id": "12",
            "name": "Window Coverings"
        }
    ]
}

Here is the ASync method:

public class Request extends AsyncTask<String, Void, JSONObject> {

    private static final int REGISTRATION_TIMEOUT = 3 * 1000;
    private static final int WAIT_TIMEOUT = 30 * 1000;
    private ProgressDialog dialog = 
            new ProgressDialog(DisplayServiceActivity.this);


    protected void onPreExecute() {
        dialog = new ProgressDialog(DisplayServiceActivity.this);
        dialog.setMessage("Getting your info real quick... Please wait...");
        dialog.show();
    }

    protected JSONObject doInBackground(String... params) {

        json = jParser.getJSONfromURL(url);
        Log.e("JSON Variable", "json returns this value: " + json);

        return json;

    }

    protected void onPostExecute(JSONObject s) {          
        super.onPostExecute(s);

        dialog.dismiss();
        Log.e("Test JSON","JSON s returns: " + s);
        try {
            directory = s.getJSONArray("Categories");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for(int i = 0; i< directory.length(); i++){
            String str_id = directory.optString(i, "id");
            String str_name = directory.optString(i, "name");
            displayCatList(str_id, str_name);

            Log.e("Test directory","Directory returns: " + json);
        }

    }

}

I appreciate all the help!

3
  • plz also share doInBackground method code Commented May 12, 2013 at 18:18
  • I added it to the original post. Commented May 12, 2013 at 18:25
  • I recommend you to use Spring for Android Commented May 12, 2013 at 19:17

3 Answers 3

1

You need to return data object from getJSONFromURL() method.

Now in doInBackground() do this->

JSONArray categories = data.getJSONArray("Categories");

now here you will have categories array.

You need to initialize your dialog under onPreExecute like this ->

protected void onPreExecute() {
    dialog = new ProgressDialog(DisplayServiceActivity.this);
    dialog.setMessage("Getting your info real quick... Please wait...");
    dialog.show();
}

Do this - >

public JSONObject getJSONfromURL (String url){
        //HTTP call
        JSONObject object = new JSONObject();
        try{
            URLConnection connection = new URL(url).openConnection();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 2048 * 16);
            StringBuffer builder = new StringBuffer();
            String line;

            while ((line = reader.readLine()) != null) {
              builder.append(line).append("\n");
            }
            String blah = builder.toString();

            //Parsing string into JSONArray
            object = new JSONObject ( new String(builder.toString()) );
            Log.e("success","created object: " + object);

            } catch(Exception e){
                Log.e("Http Error","Error in http connection " + e.toString());

            }


        return object;
    }
Sign up to request clarification or add additional context in comments.

9 Comments

I used your advice and the advice below this comment and the app still force closes because json is returning null.
You were not intialiasing dialog properly, I have edited my answer
Is it solving the problem?
I updated my code and it's still closing. It has something to do with the json variable returning null I think. I've updated my original post with new code / logcat
Remove this line from JsonParser class -> //initialize static JSONObject object =null; And change method as I have posted in my answer
|
1

That is array not object. Please use below..

        json = jParser.getJSONfromURL(url);
        try {
            JSONArray array = json.getJSONArray("Categories");
            for(---){
              //do your stuff
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Comments

1

as in Log :

JSONException: No value for Categories

because you are returning object JSONObject from getJSONfromURL method which just contains id and name keys instead of Categories JSONArray.

you can get all values from object as :

try {
        String str_id = json.optString("id");
        String str_name = json.optString("name");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

5 Comments

Ok i redid the code and I still get a force close but the error originally is gone. I've updated my original code snippets and logcat.
@user1890328 : just move Log.e("Test JSON","JSON returns: " + json); try { directory = json.getJSONArray("Categories"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(int i = 0; i< directory.length(); i++){ String str_id = directory.optString(i, "id"); String str_name = directory.optString(i, "name"); displayCatList(str_id, str_name); } part in onPostExecute and use s JSONObject instead of json
I updated the original post (code and logcat), same issue now s is null and the rest fails because of that.
@user1890328: make an log also for json = jParser.getJSONfromURL(url); and let me known what u are getting in result
i added the log and it returns null. I'm updating the code above with this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.