Rami Yahia
Rami Yahia

Reputation: 41

Displaying a string into a listview

I successfully parsed data from this website here. After writing a few codes, I get a string in which I would like to display into a ListView. Basically, I want to display the whole array from the website into a ListView.

DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://ec2-54-213-155-95.us-west-2.compute.amazonaws.com/notices.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");

    InputStream inputStream = null;
    String result = null;
    try {
        HttpResponse response = httpclient.execute(httppost);           
        HttpEntity entity = response.getEntity();

        inputStream = entity.getContent();
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        result = sb.toString();
    } catch (Exception e) { 
        // Oops
    }
    finally {
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
    }

    try {
        JSONObject jObject = new JSONObject(result);
        JSONArray jsonArray = jObject.getJSONArray("notices");        
        for(int i = 0; i < jsonArray.length(); i++) {
            String arrayString = jsonArray.getString(i);
            Log.d("notices", arrayString); 
            ListView listView1 = (ListView) findViewById(R.id.listView1);


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I am thinking of using arrayAdapter but I am not to sure of how to use it!

Upvotes: 0

Views: 2795

Answers (5)

Nu miyang
Nu miyang

Reputation: 13

You may have got the answer till now but still it may help others. I did it this way and it works great.

I made an xml recco_list file with 4 text views in.

Declare these.

ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
ListView list;

Getting into array

      for(int i = 0; i < RECCO_ARRAY.length(); i++) {
        try {

            JSONObject recco = RECCO_ARRAY.getJSONObject(i);
            JSONObject program = recco.getJSONObject("program");
            JSONObject outlet = recco.getJSONObject("outlet");
            String normalized_weight = recco.getString("normalized_weight");
            String distance = recco.getString("distance");
            HashMap<String, String> map = new HashMap<String, String>();
            String program_name = program.getString("name");
            String outlet_basics = outlet.getString("basics");
            String outlet_name = new JSONObject(outlet_basics).getString("name");
            map.put("program_name", program_name);
            map.put("outlet_name", outlet_name);
            map.put("normalized_weight", normalized_weight);
            map.put("distance", distance);

            oslist.add(map);
            list= (ListView) rootView.findViewById(R.id.recco_list);
            ListAdapter adapter = new SimpleAdapter(getActivity(), oslist, 
                    R.layout.recco_list_view, new String[] {"program_name","outlet_name", "normalized_weight", "distance"}, 
                    new int[]{R.id.program_name,R.id.outlet_name, R.id.normalized_weight, R.id.distance});
            list.setAdapter(adapter);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Upvotes: 0

GrIsHu
GrIsHu

Reputation: 23638

Try to add the data using ArrayList<String> and StableArrayAdapter as below:

    ListView listView1 = (ListView) findViewById(R.id.listView1); 
     JSONObject jObject = new JSONObject(result);
    JSONArray jsonArray = jObject.getJSONArray("notices");   
     final ArrayList<String> list = new ArrayList<String>();
     for (int i = 0; i < jsonArray.length; ++i) 
       {
           String arrayString = jsonArray.getString(i);
            Log.d("notices", arrayString); 
           list.add(arrayString);
     }
    final StableArrayAdapter adapter = new StableArrayAdapter(this,
    android.R.layout.simple_list_item_1, list);
    listview1.setAdapter(adapter);

StableArrayAdapter class

   private class StableArrayAdapter extends ArrayAdapter<String> {
         HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
   public StableArrayAdapter(Context context, int textViewResourceId,
           List<String> objects) {
         super(context, textViewResourceId, objects);
        for (int i = 0; i < objects.size(); ++i) {
          mIdMap.put(objects.get(i), i);
     }
  }
@Override
public long getItemId(int position) {
  String item = getItem(position);
  return mIdMap.get(item);
}
@Override
public boolean hasStableIds() {
  return true;
}

}

Upvotes: 0

Bhoomika Brahmbhatt
Bhoomika Brahmbhatt

Reputation: 7415

If you want to show your data in listview then u can use following code:

    private ArrayAdapter<String> mArrayAdapter;
     ListView listView1 ;

    // Initialize array adapter.

   mArrayAdapter = new ArrayAdapter<String>(this, R.layout.array_layout);
    listView1 = (ListView) findViewById(R.id.listView1);

    // Rest of your code...
    //
    //  

 try {
            JSONObject jObject = new JSONObject(result);
            JSONArray jsonArray = jObject.getJSONArray("notices");        
            for(int i = 0; i < jsonArray.length(); i++) {
                String arrayString = jsonArray.getString(i);
                   mArrayAdapter.add(arrayString) ;

                Log.d("notices", arrayString); 
                }
               listView1.setAdapter(mArrayAdapter);


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

array_layout.xml

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="18sp"
    android:padding="5dp"
/>

Upvotes: 0

Praveen Sharma
Praveen Sharma

Reputation: 4348

you can use SimpleArrayAdapter as follows :-

ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++) {
            String arrayString = jsonArray.getString(i);
            Log.d("notices", arrayString); 
          list .add(arrayString);


    }


// and after filling this array list you can set this adapter to you list as 
ListView listView1 = (ListView) findViewById(R.id.listView1);
 final StableArrayAdapter adapter = new StableArrayAdapter(this,
        android.R.layout.simple_list_item_1, list);
    listView1 .setAdapter(adapter)

Upvotes: 0

Rishabh Srivastava
Rishabh Srivastava

Reputation: 3745

First decide whether you want to store your data in ArrayList or the Database before showing it in ListView. For ArrayList to ListView you will need ArrayAdapter and from database to ListView you will need CursorAdapter. In ArrayList if you only have only TextView then you can use Simple ArrayAdapter else if there are multiple TextViews or more components then go for Custom ArrayAdapter.

Upvotes: 4

Related Questions