2

I am using JSONObject to parse content downloaded. Although the parser works for most json, it is throwing an exception for the json in a particular file.

Any advice as to why an exception is being thrown and how it can be fixed would be greatly appreciated.

Code:

    @Override
        protected String doInBackground(String... urls) {

            // params comes from the execute() call: params[0] is the url.
            try {
                return downloadUrl(urls[0], parseJson);
            } catch (IOException e) {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {

            // The parsed result comes in here
           // textView.setText(result);


        }

        private String downloadUrl(String URLString, boolean parseJSON) throws IOException { // when parsejson is false, xml will be parsed
            InputStream is = null;
            // Only display the first 500 characters of the retrieved
            // web page content.
            int len = 50000;

            try {
                URL url = new URL(URLString);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                if (useUserAuthentication) connection.setRequestProperty ("Authorization", "Basic TjN3czRwcDI0OnJld2R1Y0NvYVF1ZWFyZzk=");
                else connection.setRequestProperty("Authorization", userToken);

                connection.setDoInput(true);
                connection.setRequestMethod(requestType);

                connection.setReadTimeout(10000 /* milliseconds */);
                connection.setConnectTimeout(15000 /* milliseconds */);

                if (postHashMap != null) {

                    connection.setDoOutput(true);
                    String query = getQuery(postHashMap);
                    int contentLength = query.getBytes("UTF-8").length;
                    connection.setFixedLengthStreamingMode(contentLength);

                    OutputStream os = connection.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                    writer.write(query);
                    writer.close();
                    os.close();
                }


                // Starts the query
                connection.connect();
                int response = connection.getResponseCode();

                Log.i(LOGTAG, "The response is: " + String.valueOf(response));
                is = connection.getInputStream();

                // Convert the InputStream into a string
                String contentAsString = readIt(is, len);

                // CREATE IMAGE FROM INPUT STREAM
                //Bitmap bitmap = BitmapFactory.decodeStream(is);
                //ImageView imageView = (ImageView) findViewById(R.id.image_view);
                //imageView.setImageBitmap(bitmap);

                if (parseJSON) {

                    try {
                        String length = String.valueOf(contentAsString.length());
                        Log.i(LOGTAG, "the length is " +length);
                        //contentAsString = "{\"string\":\"But during winter, it’s more important\"}";
                        //contentAsString.replace("’","'");
                        //contentAsString = "{\"user_id\":\"juan\"}";
                        JSONObject jsonObject = new JSONObject(contentAsString);

                        // New User
                        if (requestName.equals("NewUser")) {

                            String tempToken = jsonObject.getString("token");
                            String tempUserID = jsonObject.getString("user_id");

                            if (tempToken != null && tempToken.length() > 0) {

                                userToken = "Token " +tempToken;
                                Log.i(LOGTAG, "saving the token " +userToken);
                                SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.app_preferences), Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPref.edit();
                                editor.putString("UserToken", userToken);
                                editor.putString("UserID", tempUserID);
                                editor.commit();

                                // Request content
                                indexArticlesForCategories();
                            }
                        }
                        // Index articles
                        else if (requestName.equals("IndexArticlesForCategories")) {

                            Log.i(LOGTAG,"got here");
                        }
                        // User Profile
                        else if (requestName.equals("UserProfile")) {

                            Log.i(LOGTAG, "the user id is " +jsonObject.getString("user_id"));
                        }

                    }
                    catch (JSONException e) {
                        Log.i(LOGTAG, "json exception " +e.getMessage());
                        e.printStackTrace();
                        Log.getStackTraceString(e.getCause().getCause());
                    }

                    Log.i(LOGTAG, "the json data " + contentAsString);
                }



                return contentAsString;

                // Makes sure that the InputStream is closed after the app is finished using it.
            } finally {
                if (is != null) {

                    is.close();
                }
            }
        }

        // convert input stream to text
        public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
//            Reader reader = null;
//            reader = new InputStreamReader(stream, "UTF-8");
//            char[] buffer = new char[len];
//            reader.read(buffer);
//            return new String(buffer);

            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));

            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }



            return sb.toString();
        }

Stack Trace (updated):

java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
        at java.util.concurrent.FutureTask.run(FutureTask.java:239)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
        Caused by: java.lang.NullPointerException
        at com.media24.myedit.WebServicesManager$AsyncDownloadTask.downloadUrl(WebServicesManager.java:248)
        at com.media24.myedit.WebServicesManager$AsyncDownloadTask.doInBackground(WebServicesManager.java:140)
        at com.media24.myedit.WebServicesManager$AsyncDownloadTask.doInBackground(WebServicesManager.java:126)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)
        ... 4 more
16
  • post the exeption/stacktrace please Commented Jul 23, 2013 at 12:15
  • What is the content of the Exception? Commented Jul 23, 2013 at 12:15
  • BufferedReader streamReader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); Might work, hard to tell without the stracktrace. Commented Jul 23, 2013 at 12:16
  • @user634545 I have added in UTF 8 but I am still getting an exception Commented Jul 23, 2013 at 12:20
  • 1
    try to also print e.getMessage() might help - but even with printStackTrace() there should be more :/ Commented Jul 23, 2013 at 12:28

4 Answers 4

1

I didn't check your code but I always use the following snippet and it works till now.

JSONParser.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

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

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

And call it like:

JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);

Sometimes json starts with an array node instead of jSON Object node. In those case, you have to return an JSONArray instead of JSONObject

Sign up to request clarification or add additional context in comments.

1 Comment

It was your last comment about using JSONArray which put me on the right path. Thanks!
0

Try the following:-

static InputStream is = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}} catch (Exception e) {

    Log.e("Buffer Error", "Error Converting Result" + e.toString());
}

Comments

0

Found the problem!

I was getting back an array and had to use JSONArray rather than JSONObject

Comments

0

From my point of view, you must call close() to InputStream and reader before returning the response as:

stream.close(); 
reader.close();
return sb.toString();

It would be better if you specify what kind of error you are getting while running the above piece of code to analyse the issue.

Thanks!

Comments

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.