Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
    
plz also share doInBackground method code –  ρяσѕρєя K May 12 '13 at 18:18
    
I added it to the original post. –  user1890328 May 12 '13 at 18:25
    
I recommend you to use Spring for Android –  Misagh Aghakhani May 12 '13 at 19:17
add comment

3 Answers 3

up vote 1 down vote accepted

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;
    }
share|improve this answer
    
I used your advice and the advice below this comment and the app still force closes because json is returning null. –  user1890328 May 12 '13 at 20:31
    
You were not intialiasing dialog properly, I have edited my answer –  Vishal Pawale May 12 '13 at 20:51
    
Is it solving the problem? –  Vishal Pawale May 12 '13 at 20:57
    
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 –  user1890328 May 12 '13 at 21:00
1  
Remove this line from JsonParser class -> //initialize static JSONObject object =null; And change method as I have posted in my answer –  Vishal Pawale May 12 '13 at 21:02
show 5 more comments

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();
        }
share|improve this answer
add comment

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();
    }
share|improve this answer
    
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 May 12 '13 at 20:26
    
@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 –  ρяσѕρєя K May 12 '13 at 20:34
    
I updated the original post (code and logcat), same issue now s is null and the rest fails because of that. –  user1890328 May 12 '13 at 20:51
    
@user1890328: make an log also for json = jParser.getJSONfromURL(url); and let me known what u are getting in result –  ρяσѕρєя K May 12 '13 at 20:54
    
i added the log and it returns null. I'm updating the code above with this. –  user1890328 May 12 '13 at 20:58
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.