How to display item and subitem from HashMap in ListView

johhny.b :

I would like to display item and subitem from HashMap, item would be String (borrower name), subitem double(borrower loan). It's my first android app so be understanding :)

It's my layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="669dp">

    </ListView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <Button
            android:id="@+id/editButton"
            android:layout_width="244dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Dodaj" />

        <Button
            android:id="@+id/sumButton"
            android:layout_width="202dp"
            android:layout_height="wrap_content"
            android:text="Suma dlugow" />

    </LinearLayout>

</LinearLayout>

And backend

    listView = findViewById(R.id.listView);

    Map<String, Double> borrowers = new HashMap<>();
    ArrayList<String> arrayList = new ArrayList<>();

    borrowers.put("John", 300.0);
    arrayList.add(String.valueOf(borrowers));

    ArrayAdapter<Borrower> arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
    listView.setAdapter(arrayAdapter);

And app display only one item and it's look like {John=300.0}, i want to look like:

John
300.0

or just John \t 300

LeHaine :

Your current code is just grabbing the String value of the entire map. You need to iterate over the map to grab the key and value and then construct your new String and add it to your List.

for (Map.Entry<String, Double> entry : borrowers.entrySet()) {
    String key = entry.getKey();
    Double value = entry.getValue();
    arrayList.add(key + "\t" + value);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398688&siteId=1