-6

Possible Duplicate:
JSON object to listView

i have a json data on server and want to retrive it and show it in my android listview..sorry if this is duplicate question please give me some suggestion to start from stratch

answer will be appreciated thanks

Community
  • 1
  • 1

2 Answers2

1

This may help you..

Your Actmain class

Actmain.java

public class Actmain extends Activity {

// url to make request
private static String url = "http://api.androidhive.info/contacts/";

// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
private ArrayList<HashMap<String, String>> _alistHashmap; 
private Clsgetjson getjson;

// contacts JSONArray
private JSONArray Jarray = null;
private JSONObject jobj;
private Listview lv;


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

// Creating JSON Parser instance
getjson = new Clsgetjson();

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

lv=(listview)findviewbyid(R.id.lv);


 jobj= getjson.getJSONFromUrl(url);



  try {
        // Getting Array of Contacts
        Jarray = json.getJSONArray(TAG_CONTACTS);

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

            // Storing each json item in variable
            String id = jobject.getString(TAG_ID);
            String name = jobject.getString(TAG_NAME);
            String email = jobject.getString(TAG_EMAIL);
            String address = jobject.getString(TAG_ADDRESS);
            String gender = jobject.getString(TAG_GENDER);

            // Phone number is agin JSON Object
            JSONObject phone = jobject.getJSONObject(TAG_PHONE);
            String mobile = phone.getString(TAG_PHONE_MOBILE);
            String home = phone.getString(TAG_PHONE_HOME);
            String office = phone.getString(TAG_PHONE_OFFICE);

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

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_NAME, name);
            map.put(TAG_EMAIL, email);
            map.put(TAG_PHONE_MOBILE, mobile);

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



    //now set your adapter to listview (you can do this under buttons onclick event)


String[] from=new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE };
int[] to= new int[] {R.id.name, R.id.email, R.id.mobile }

SimpleAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.raw_lv,from,to);

lv.setAdapter(adapter);

now Clsgetjson.java

public class Clsgetjson {


static JSONObject jObj = null;
static String strjson = "";


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();

strjson=EntityUtility.toString(httpEntity);

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



    // try parse the string to a JSON object
    try {


        jObj = new JSONObject(strjson);


    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

or with parameter

        List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
    nvp.add(new BasicNameValuePair("function", "login"));
    nvp.add(new BasicNameValuePair("uname", username));
    nvp.add(new BasicNameValuePair("pwd", pass)));

add this in request

        if(nvp!=null)

        hpost.setEntity(new UrlEncodedFormEntity(nvp));

everything else is same as above

Kalpesh Lakhani
  • 1,003
  • 14
  • 28
0

First you will want to fetch your JSON

import java.io.IOException; 
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class WebServiceConnector
{

/**
 * Makes the HTTP GET request to the provided REST url 
 * @param requestUrl the URL to request
 * @return The string of the response from the HTTP request
 */
public String callWebService(String requestUrl)
{
    String deviceId                    = "Android Device";

    HttpClient httpclient            = new DefaultHttpClient();  
    HttpGet request                    = new HttpGet(requestUrl);  
    request.addHeader("deviceId", deviceId);  

    ResponseHandler handler    = new BasicResponseHandler();  
    String result                    = "";  

    try
    {  
        result = httpclient.execute(request, handler);  
    }
    catch (ClientProtocolException e)
    {  
        e.printStackTrace();
        Log.e(TAG, "ClientProtocolException in callWebService(). " + e.getMessage());
    }
    catch (IOException e)
    {  
        e.printStackTrace();
        Log.e(TAG, "IOException in callWebService(). " + e.getMessage());
    }

    httpclient.getConnectionManager().shutdown(); 
    Log.i(TAG, "**callWebService() successful. Result: **");
    Log.i(TAG, result);
    Log.i(TAG, "*****************************************");

    return result;
}
}

Then you need to parse that json. There are several JSON parsers, JAXB, Jackson... If it's simple structure, the easiest is probably to just parse it on your own using org.json classes (included in Android already) like org.json.JSONArray, org.json.JSONObject and org.json.JSONException. Generate your array/list of items from the json and then connect it to a listview using an ArrayAdapter like you normally would. Happy coding!

speakingcode
  • 1,518
  • 13
  • 12