简体   繁体   中英

Dynamically use HashMap to populate columns in listView

I am using HashMap to put the data in TextView inside a ListView but I am unable to dynamically populate the list I am able to get only the first row as output. or How to do each for the hash string.

code -

for (int i=0; i<result.length(); i++) {
    JSONObject notice = result.getJSONObject(0);
    id[i] = notice.getString(KEY_ID);
    name[i] = notice.getString(KEY_NAME);
    date_from[i] = notice.getString(KEY_DATE_FROM);
    date_to[i] = notice.getString(KEY_DATE_TO);

    ListView listView = (ListView) findViewById(R.id.listView1);

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

    HashMap<String, String> temp= new HashMap<String, String>();
    temp.put(FIRST_COLUMN, id[i]);
    temp.put(SECOND_COLUMN, name[i]);
    temp.put(THIRD_COLUMN, date_from[i]);
    temp.put(FOURTH_COLUMN, date_to[i]);
    list.add(temp);
    ListViewAdapters adapter = new ListViewAdapters(this, list);
    listView.setAdapter(adapter);
}

Custom ListViewAdapter -

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater=activity.getLayoutInflater();

    if(convertView == null){
        convertView=inflater.inflate(R.layout.colmn_row, null);

        txtFirst=(TextView) convertView.findViewById(R.id.name);
        txtSecond=(TextView) convertView.findViewById(R.id.gender);
        txtThird=(TextView) convertView.findViewById(R.id.age);
        txtFourth=(TextView) convertView.findViewById(R.id.status);

    }


    HashMap<String, String> map=list.get(position);
    txtFirst.setText(map.get(FIRST_COLUMN));
    txtSecond.setText(map.get(SECOND_COLUMN));
    txtThird.setText(map.get(THIRD_COLUMN));
    txtFourth.setText(map.get(FOURTH_COLUMN));

    return convertView;
}

From the code you have shared, you are putting everything inside loop which is recreating ArrayList and ListView again and again. As a result, your list and listview contain only last item (one row). Do this -

ListView listView = (ListView) findViewById(R.id.listView1);
list = new ArrayList<HashMap<String, String>>();
for (int i=0; i<result.length(); i++) {
    JSONObject notice = result.getJSONObject(i);
    id[i] = notice.getString(KEY_ID);
    name[i] = notice.getString(KEY_NAME);
    date_from[i] = notice.getString(KEY_DATE_FROM);
    date_to[i] = notice.getString(KEY_DATE_TO);

    HashMap<String, String> temp= new HashMap<String, String>();
    temp.put(FIRST_COLUMN, id[i]);
    temp.put(SECOND_COLUMN, name[i]);
    temp.put(THIRD_COLUMN, date_from[i]);
    temp.put(FOURTH_COLUMN, date_to[i]);
    list.add(temp);
}
    ListViewAdapters adapter = new ListViewAdapters(this, list);
    listView.setAdapter(adapter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM