0

I have used httpclient to call a restapi written in django. It returned the json output. My httpresponse variable stored it and later convert the reponse to string and then to json object, i think its lengthy though it is working . I am really new to java , can anybody advise me , what is the best alternative logic to the code below

public void onClick(View v) {
    // TODO Auto-generated method stub

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httppost = new HttpGet("http://10.0.2.2:8000/api/ca/entry/?
            format=json&username=pragya");
    try {
        // Add your data
        //List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        //nameValuePairs.add(new BasicNameValuePair("username", un.getText().toString()));
        //nameValuePairs.add(new BasicNameValuePair("username", pw.getText().toString()));
        //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            JSONObject jsonObject = new JSONObject(sb.toString());
            JSONObject meta = jsonObject.getJSONObject("meta");  
            String limit = meta.getString("limit");  
            Toast.makeText(HelloWorldActivity.this, limit, Toast.LENGTH_SHORT).show();
            JSONArray array = jsonObject.getJSONArray("objects");

            String key = array.getJSONObject(0).getString("api_key");
            String uname = array.getJSONObject(0).getString("username");
            Toast.makeText(HelloWorldActivity.this, uname + " " + key,
            Toast.LENGTH_SHORT).show();

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        //Toast.makeText(HelloWorldActivity.this, sb.toString(), Toast.LENGTH_SHORT).show();
    } catch (ClientProtocolException e) {
        Toast.makeText(HelloWorldActivity.this, e.toString(), Toast.LENGTH_SHORT).show();

        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Toast.makeText(HelloWorldActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
    }   
}
});

the json is as follows

{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"api_key": "c87391754b522d0c83b2c8b5e4c8cfd614559632deee70fdf1b48d470307e40e", "homeAddress": "kathmandu", "resource_uri": "/api/ca/entry/1/", "username": "sumit"}]}
hangman
  • 865
  • 5
  • 20
  • 31

2 Answers2

5

Use Gson library from google, it is perfect for these kind of tasks.

All you need to do is define a new class that contains fields with the names of the keys in the json object and then use Gson to parse the Json string directly into the object or vice versa.

So for example:

Json looks like this: "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1.

Java Class will be:

public class MyClass {
    private int limit;
    private int next;
    private int offset;
    private int previous;
    private int total_count;

public int getLimit() {
    return limit;
}
public void setLimit(int limit) {
    this.limit = limit;
}
public int getNext() {
    return next;
}
public void setNext(int next) {
    this.next = next;
}
public int getOffset() {
    return offset;
}
public void setOffset(int offset) {
    this.offset = offset;
}
public int getPrevious() {
    return previous;
}
public void setPrevious(int previous) {
    this.previous = previous;
}
public int getTotal_count() {
    return total_count;
}
public void setTotal_count(int total_count) {
    this.total_count = total_count;
}
}

And use Gson code like that:

 Gson gson = new Gson(); // Or use new GsonBuilder().create();
 MyClass myClass = gson.fromJson(json, MyClass.class); // deserializes json into MyClass 

Please note that the name of the class fields have to match exactly the name of the keys in the json string.

Tomer
  • 17,787
  • 15
  • 78
  • 137
1

Always perform lengthy non-UI task using AsyncTask. All the operations you described, fetching of json and parsing them, can be performed in AsyncTask. Write the entire code which you have currently written in onClick event and write it doInBackground() of an AsyncTask.

Check the following for more details: http://developer.android.com/reference/android/os/AsyncTask.html

Arun George
  • 18,352
  • 4
  • 28
  • 28