1

I am pretty new to the world of Android and Java and I am wondering how I get data from the web api here http://www.imdbapi.com/ Into android. Should I use JSON or XML? What are the steps? Firstly I want to know how to download the data and then how to parse it to variables. Any sample code?

1 Answer 1

1
HttpClient httpclient = new DefaultHttpClient();
    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 
    // Execute the request
    HttpResponse response;

    JSONArray arr = new JSONArray();
    try {
       response = httpclient.execute(httpget);

       HttpEntity entity = response.getEntity();

       if (entity != null && response.getStatusLine().getStatusCode() == 200) {
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result = convertStreamToString(instream);
                arr=new JSONArray(result);
                instream.close();

            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            Log.e(TAG,e.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e(TAG,e.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            Log.e(TAG,e.toString());
        }

        return arr;


public static String convertStreamToString(InputStream is) {
    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) {
        Log.e(TAG + "ERROR",e.toString());

    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG + "ERRO",e.toString());
        }
    }
    return sb.toString();
}

As for parsing, here you go: http://developer.android.com/reference/org/json/package-summary.html

btw, this was all easily found on google : )

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

3 Comments

this run in 14 sdk version? what i do if want to run on 2.3.3? instead of json which alternative way to get those parameters?
This code throws error at TAG in android studio. 'TAG' has private access in 'android.support.v4.app.Fragment'
You can just remove TAG ... I throw it in the log so I know exactly where the exception is coming from.

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.