kustomrtr
kustomrtr

Reputation: 1477

Populate a ListView from an ArrayList<HashMap<String, String>>

I have an ArrayList<HashMap<Contact, Name>> and I want to populate a ListView with it. Here's my attempt (which is not working)

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

    // Array of strings "titulos"
    String titulos[] = { "Dolar (Transferencia)", "Euro (Transferencia)",
        "Dolar (Efectivo)", "Euro (Efectivo)", "Dolar (cúcuta)",
        "Euro (cucuta)" };

    try {
        JSONObject json = result; // result is a JSONObject and the source is located here: https://dl.dropbox.com/u/8102604/dolar.json
        JSONObject root = json.getJSONObject("root"); 
        JSONArray items = root.getJSONArray("item");
        int j = 0; 

        for (int i = 0; i < items.length(); i++) {
            JSONObject item = items.getJSONObject(i);
            String key = item.getString("key");
            String mount = item.getString("mount");
            if (key.equals("TS") || key.equals("TE") || key.equals("EE")
                    || key.equals("CE") || key.equals("ES")
                    || key.equals("CS")) { // i did this since i only need the items where the key is equal to TS, TE, EE, CE, ES or CS.
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("id", String.valueOf(i));
                map.put(key, mount);
                lista.add(map);
                System.out.println(titulos[j] + "(" + key + "). BsF = " + mount); // just for debugging purposes
                j++; // add 1 to j if key is equal to TS, TE, EE, CE, ES or CS. In this way i can associate the two arrays (item and titulos)
            }
        }

        ListView lv = (ListView) myMainActivity.findViewById(R.id.listView1); // create a list view 
        lv.setAdapter(new ArrayAdapter<String>(contexto, android.R.layout.simple_list_item_1, lista)); // set adapter to the listview (not working)

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

That last line is throwing an error in eclipse:

The constructor ArrayAdapter<String>(Context, int, ArrayList<HashMap<String,String>>) is undefined

I've tried everything but I still couldn't make it work, could you help me please?

Thanks in advance.

PS: Full source: https://gist.github.com/4451519

Upvotes: 3

Views: 9905

Answers (4)

Lalith B
Lalith B

Reputation: 12239

You need to use your own CustomArrayAdapter like below and consume this class in your code.

public class CustomArrayAdapter extends BaseAdapter {
    private JSONArray jsonArray = null;
    public ImageAdapter(Context c, JSONArray jsonArray) {
        context = c;
        this.jsonArray = jsonArray;
    }
    public int getCount() {
        return jsonArray.length();
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        //DO YOUR CODE HERE
        LayoutInflater inflater = (LayoutInflater)       context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

       if (convertView == null) {
          convertView = inflater.inflate(R.layout.list_item_view, null);
       }else{
          //Set values for your listview on the list item.
          convertView.findViewById(R.id.someID).setText("GetJSONTEXT");
       }
    }
}

MY SUGGESTION FOR YOUR MAINACTIVITY

package com.kustomrtr.dolarparalelovenezuela;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import com.loopj.android.http.*;
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AsyncHttpClient client = new AsyncHttpClient();
        client.get("http://192.168.1.5/dolar.json", new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                System.out.println(response);
                try {
                    JSONObject json = new JSONObject(response); // result is a JSONObject and the source is located here: https://dl.dropbox.com/u/8102604/dolar.json
                    JSONObject root = json.getJSONObject("root"); 
                    JSONArray items = root.getJSONArray("item");

                    ListView lv = (ListView) myMainActivity.findViewById(R.id.listView1); // create a list view 
                    lv.setAdapter(new CustomArrayAdapter<String>(contexto, android.R.layout.simple_list_item_1, items));

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

            }
        });
    } 

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

Upvotes: 2

njzk2
njzk2

Reputation: 39386

Just use a SimpleAdapter.

String[] from = new String[] { /* all your keys */};
int[] to = new int[] { /* an equal number of android.R.id.text1 */};
ListAdapter adapter = new SimpleAdapter(contexto, lista, android.R.layout.simple_list_item_1, from, to);

It would be simple (and more logical) if each item of your list contained a similarly formed object, not a different key every time.

I would replace

map.put(key, mount);

by

map.put("key", key);
map.put("value", mount);

and then the from and to are simply:

String[] from = new String[] { "value" };
int[] to = new int[] { android.R.id.text1 };

Upvotes: 3

Scorpion
Scorpion

Reputation: 6891

You have to create you own Custom Adapter by Extending BaseAdapter in Android. Then you can set your custom adapter to the ListView by using the setAdapter method of the list view.

For your reference of please see the below small example of BaseAdapter. You need to pass your ArrayList< HashMaP > to the Adapter.

http://jimmanz.blogspot.in/2012/06/example-for-listview-using-baseadapter.html

Hope this helps.

Upvotes: 0

karllindmark
karllindmark

Reputation: 6071

You'll have to create your own adapter if you really want to pass the whole list of HashMaps, as the ArrayAdapter<String> expects the third parameter in your case to be of the type List<String>.

You should follow @Tomislav Novoselec's suggestion in the comments, and create a List<String> from the HashMap values.

Upvotes: 2

Related Questions