0

From my last post, got t know that, i need to use async task for json parsing from url, have done the same and attached below,

public class ReadJson extends ListActivity {
private static String url = "http://docs.blackberry.com/sampledata.json";

private static final String TAG_VTYPE = "vehicleType";
private static final String TAG_VCOLOR = "vehicleColor";
private static final String TAG_FUEL = "fuel";
private static final String TAG_TREAD = "treadType";

ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

ListView lv ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read_json);
    new ProgressTask(ReadJson.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog dialog;
    // private List<Message> messages;
    public ProgressTask(ListActivity activity) {
        context = activity;
        dialog = new ProgressDialog(context);
    }
    /** progress dialog to show user that the backup is processing. */
    /** application context. */
    private Context context;
    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }
    @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        ListAdapter adapter = new SimpleAdapter(context, jsonlist,
                R.layout.list_item, new String[] { TAG_VTYPE, TAG_VCOLOR,
                TAG_FUEL, TAG_TREAD }, new int[] {
                R.id.vehicleType, R.id.vehicleColor, R.id.fuel,
                R.id.treadType });
        setListAdapter(adapter);
        // selecting single ListView item
        lv = getListView();
    }
    protected Boolean doInBackground(final String... args) {
        JSONParser jParser = new JSONParser();
        JSONArray json = jParser.getJSONFromUrl(url);
        for (int i = 0; i < json.length(); i++) {
            try {
                JSONObject c = json.getJSONObject(i);
                String vtype = c.getString(TAG_VTYPE);
                String vcolor = c.getString(TAG_VCOLOR);
                String vfuel = c.getString(TAG_FUEL);
                String vtread = c.getString(TAG_TREAD);
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(TAG_VTYPE, vtype);
                map.put(TAG_VCOLOR, vcolor);
                map.put(TAG_FUEL, vfuel);
                map.put(TAG_TREAD, vtread);
                jsonlist.add(map);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

}

When i execute this, i get null pointer exception for error executing in asyc background in the line, for (int i = 0; i < json.length(); i++), tried several things but not working, any help will be gr8ly appreciated!!

Edit 1: added parser code

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.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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 {

    static InputStream is = null;
    static JSONArray jarray = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url) {

        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e("==>", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

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

        // return JSON String
        return jarray;

    }
}
bharath
  • 953
  • 4
  • 17
  • 30
  • have you tried debugging and checked if data is parsed properly? – Sanober Malik Mar 29 '13 at 03:54
  • Do a debug and check that the `JSONArray json` has values in it. Or do a `Log.e("JSON DATA", json.toString);` and see that it has a data. It will show up in your DDMS perspective. – Siddharth Lele Mar 29 '13 at 03:56
  • How can i do that?? i cant add log.e or toast in background r8?? please suggest how to check if json object is not null – bharath Mar 29 '13 at 04:13
  • @bharath: Read my earlier comment. And you can add a `Toast` in the `doInBackground()` in a Runnable block. Just add the `Log.e....` (as shown in my earlier comment) right below the `JSONArray json = jParser.getJSONFromUrl(url);` – Siddharth Lele Mar 29 '13 at 04:24
  • The problem is in the server side code which is returning the JSON. check for any syntax or logic error. try to print the json result to a file before returning for confirmation. or check the errorlog file at the server side. – SKK Mar 29 '13 at 04:33

3 Answers3

0

It looks like you're using this JSONParser I think. What appears to be happening is that you have a URL that is not producing valid JSON, which is resulting in an Exception being thrown and caught in the class somewhere along the way -- most likely in the jObj = new JSONObject(json); line. The end result is that the returned variable is still null. So when you call json.length() in your loop, you're trying to call length() on a null object. You should do a check on it prior to going into the loop to make sure that it isn't null.

jprofitt
  • 10,874
  • 4
  • 36
  • 46
  • Ok, i commented the for loop and checked if its parsing at all in the first place, then got this error, 03-29 09:45:32.019: E/JSON Parser(942): Error parsing data org.json.JSONException: End of input at character 0, checked with other sample json scripts as well, scripts are fine, is there an issue with the parser?? – bharath Mar 29 '13 at 04:18
  • It's more likely that it's a problem with the data that is being returned. You should debug and find what the actual response data is from the URL. – jprofitt Mar 29 '13 at 04:20
  • have been tryin from yesterday without any result, is there any samples i can reuse for parsing just an element from the url using async to work for android 3.0 and above?? if so, please suggest, want to wrap this off!! – bharath Mar 29 '13 at 04:41
  • @bharath : plz show your getJSONFromUrl method code to get more help – ρяσѕρєя K Mar 29 '13 at 04:42
  • Take a look at [this answer](http://stackoverflow.com/questions/2075836/read-contents-of-a-url-in-android) for how to get the contents of the URL, then you can log that. After that, you should be able to see if you have a valid JSON response – jprofitt Mar 29 '13 at 04:43
  • You aren't using a standard parser, which is why I linked to what I thought might be the best candidate for what you were using. If you can, it would be best to verify that you are using the code that I linked to. – jprofitt Mar 29 '13 at 04:50
0

I think that, you are not getting valid JSON format from server. before parsing check the response getting from your server, Here is snippet of code, here pass url and get yourReponseInJSONStr check response string in logcat is it in proper JSON format or not and then do the operation of parsing.

 try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        url);

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String yourReponseInJSONStr = httpclient.execute(httppost,
                    responseHandler);

            Log.d("yourReponseInJSONStr ", yourReponseInJSONStr );

                    JSONObject yourJsonObj = new JSONObject(yourReponseInJSONStr);


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

you can also continue parsing in this code as well,Hope this helps you,

Amol Sawant
  • 13,842
  • 2
  • 20
  • 27
0

Try this for getting json

public static String getJSONString(String url) {
    String jsonString = null;
    HttpURLConnection linkConnection = null;
    try {
        URL linkurl = new URL(url);
        linkConnection = (HttpURLConnection) linkurl.openConnection();
        int responseCode = linkConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream linkinStream = linkConnection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int j = 0;
            while ((j = linkinStream.read()) != -1) {
                baos.write(j);
            }
            byte[] data = baos.toByteArray();
            jsonString = new String(data);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (linkConnection != null) {
            linkConnection.disconnect();
        }
    }
    return jsonString;
}

public static boolean isNetworkAvailable(Activity activity) {
    ConnectivityManager connectivity = (ConnectivityManager) activity
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

use isNetworkAvailable for checking connection

and i parsed this way

try {

                JSONObject jObjectm = new JSONObject(result);
                JSONObject jObject=jObjectm.getJSONObject("items");
                  if(jObject!=null)
                  {
                    Iterator<?> iterator1=jObject.keys();
                         LinkedHashMap<String,LinkedHashMap<String, Object> > inneritem = new LinkedHashMap<String, LinkedHashMap<String, Object> >();
                        while (iterator1.hasNext() ){
                            Item hashitem=new Item();
                               String key1 = (String)iterator1.next();
                               JSONObject jObject1=jObject.getJSONObject(key1);
                               Iterator<?> iterator=jObject1.keys();
                                 LinkedHashMap<String, Object> inneritem1 = new LinkedHashMap<String, Object>();
                                while (iterator.hasNext() ){


                                    String key =(String) iterator.next();

                                  inneritem1.put(key, jObject1.get(key));


                                }
                                 hashitem.setItem(key1,inneritem1);
                                inneritem.put(key1,inneritem1);
                                arrayOfList.add(hashitem); 
                        }




                  }
                } catch (JSONException e) {

                    System.out.println("NO Json data found");
                }
Akilan
  • 924
  • 1
  • 7
  • 19