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.

How to retrieve JSON web service data for android? I'm currently trying to retrieve event data in JSON format and display it but i'm not really sure how should i do it. But somehow i just can't run in my mobile application. Here is a sample of my code:

package com.androidhive.jsonparsing;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AndroidJSONParsingActivity extends ListActivity {

    // url to make request
    private static String url = "http://api.eventful.com/json/events/get?app_key=rDkKF6nSx6LjWTDR&id=E0-001-000324672-7";

    // JSON Node names
    private static final String TAG_ID = "id";
    private static final String TAG_REGION = "region";
    private static final String TAG_STARTTIME = "start_time";
    private static final String TAG_TITLE = "title";
    private static final String TAG_CITY = "city";
    private static final String TAG_VENUE_NAME = "venue_name";

    // contacts JSONArray
    JSONArray id;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

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

        try {
            // Getting Array of Contacts
            id = json.getJSONArray(TAG_ID);

            // looping through All Contacts
            for (int i = 0; i < id.length(); i++) {
                JSONObject c = id.getJSONObject(i);

                // Storing each json item in variable
                String mid = c.getString(TAG_ID);
                String region = c.getString(TAG_REGION);
                String starttime = c.getString(TAG_STARTTIME);
                String mtitle = c.getString(TAG_TITLE);
                String city = c.getString(TAG_CITY);
                String venuename = c.getString(TAG_VENUE_NAME);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, mid);
                map.put(TAG_REGION, region);
                map.put(TAG_STARTTIME, starttime);
                map.put(TAG_TITLE, mtitle);
                map.put(TAG_CITY, city);
                map.put(TAG_VENUE_NAME, venuename);

                // adding HashList to ArrayList
                contactList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, contactList,
                R.layout.list_item, new String[] { TAG_TITLE },
                new int[] { R.id.mtitle });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.mtitle))
                        .getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        SingleMenuItemActivity.class);
                in.putExtra(TAG_TITLE, name);


            }
        });

    }

}

As Requested, this is my sample code for JSONParser:

package com.androidhive.jsonparsing;

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;

    }
}
share|improve this question
2  
What happens when you run your code that is unexpected? Exceptions? Computer shuts down? A new pope is elected? :) –  Joachim Isaksson Jul 10 '13 at 6:57
    
Post you stack trace.. @JoachimIsaksson : lol –  Shanku Jul 10 '13 at 7:01
    
When i run the code, nothing came out. Just black screen! –  Leo Jul 10 '13 at 7:02
    
are you using emulator ?? is this the first time your running an android project??? –  Shanku Jul 10 '13 at 7:11
    
can you post JSONParser class code –  Shanku Jul 10 '13 at 7:13
show 9 more comments

4 Answers

So if String strJson is the resultant string received from the HTTP request that has to be populated in a ListView for instance then :-

JSONObject strJsonObj = new JSONObject(strJson);
Listview listContent = getListFromJson(strJsonObj);

and from strJsonObj create a JSON array like:

JSONArray resultantArray = strJsonObj.getJSONArray("resultantTag");

Making a loop to traverse the JsonArray Create Json Object for every traverse:

for(int i=0; i<searchResultArray.length(); i++){
      JSONObject objAtI = (JSONObject) resultantArray.get(i);
      objAtI.get("xyz").toString();
      objAtI.get("abc").toString();
}

Thats it.

share|improve this answer
    
If you feel this question is a duplicate and another question already has the answer, please mark it as such. Copy and Pasting your answers isn't that effective. –  Lukas Knuth Jul 10 '13 at 9:17
add comment

You can check this link. It gives example of JSONParser and parse the JSON from a string.

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
share|improve this answer
add comment

check you JSONParser class:

You might be making a POST request to this url but it is NOT ALLOWED.You should change the HTTP REQUEST to type GET

if you find in your code

HttpPost httpPost = new HttpPost(url); //then change it httpget

ForExample:

DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI("youurl"));
HttpResponse response = defaultHttpClient.execute(method);
InputStream data = response.getEntity().getContent();

i found where your making mistake. Probably you have just learnt to create web service form a blog and literally changed it according to your requirement.nothing wrong here bt what your missing is the input format of json. tutorial you referred had different format of input and your URL has different format. so u need to parse your jsonobject accordingly..

id = json.getJSONArray(TAG_ID); there is no array object with name id.. check your json input.. i hope you understood the problem.

UPDATE:

no dude ID is not an array of object in your link(tag is). so the way your retrieving it is wrong.I suggest you learn json format and parsing it, it is quite simple.

For Example

String data="{'foo':'bar','coolness':2.0, 'altitude':39000, 'pilot':{'firstName':'Buzz','lastName':'Aldrin'}, 'mission':'apollo 11'}";

I retrieved like this

JSONObject json = (JSONObject) JSONSerializer.toJSON(data);        
    double coolness = json.getDouble( "coolness" );
    int altitude = json.getInt( "altitude" );
    JSONObject pilot = json.getJSONObject("pilot");
    String firstName = pilot.getString("firstName");
    String lastName = pilot.getString("lastName");

    System.out.println( "Coolness: " + coolness );
    System.out.println( "Altitude: " + altitude );
    System.out.println( "Pilot: " + lastName );

So in code when your receiving JSONObject from method dont convert it to jsonarray. just use

String ID = json.getString("id");
share|improve this answer
    
Yeap, i use a web service code from a blog and change it to mine according to the api i have. Let me post up the original code! As for the id = json.getJSONArray(TAG_ID), i'm not sure which part went wrong still. From the link provided,"api.eventful.com/json/events/…;, there is a json input called "id":"E0-001-000324672-7". Isn't this the array object with name id? Sorry for the trouble and thanks for the help Shanku, appreciated it alot :) –  Leo Jul 11 '13 at 1:15
add comment

Replace

// Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

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

with

String response = getRequest(url);
JSONObject object = new JSONObject(response);

Add these two functions

public String getRequest(final String url) {
        String responseString=null;
        try {  

            Logger.show(Log.INFO, TAG,
                    "URL " +url);
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    15000);
            HttpConnectionParams.setSoTimeout(httpParameters,15000);
            HttpClient client = new DefaultHttpClient(httpParameters);
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            InputStream ips  = response.getEntity().getContent();
            responseString = response.toString();
            responseString = intputStreamToStringConvertor(ips);

        } catch (NullPointerException e) {
            Logger.show(e);
            responseString = null;
        } catch (UnsupportedEncodingException e) {
            Logger.show(e);
            responseString = null;
        } catch (ClientProtocolException e) {
            Logger.show(e);
        } catch (IOException e) {
            Logger.show(e);
            responseString = null;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return responseString;
    }

    /** Converting InputStream to string */
    private static String intputStreamToStringConvertor(InputStream inputStream) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream, "UTF-8"), 800);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            inputStream.close();
            return sb.toString();
        } catch (NullPointerException e) {
            Logger.show(e);
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
share|improve this answer
    
My widget is not displaying the data I received from the JSON parse :/ stackoverflow.com/questions/20082315/… –  SiKni8 Nov 19 '13 at 22:01
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.