javaandroidlistviewandroid-adaptersimpleadapter

ListView / SimpleAdapter doesn't refresh - Android


I want to add to a ListView with the click of a button, but the ListView doesn't refresh. The HashMap itself refreshes, but the ListView doesn't.

Here's my code:

final ListView grupidView = (ListView) findViewById(R.id.grupiList);
final HashMap<String,String> uusGrupp = new HashMap<>();

Button gruppNupp = findViewById(R.id.lisaGrupp);

final List<HashMap<String, String>> grupiLiikmed = new ArrayList<>();

final SimpleAdapter adapter = new SimpleAdapter(this, grupiLiikmed, R.layout.list_items,
        new String[]{"First line", "Second line"},
        new int[]{R.id.text1, R.id.text2});

Iterator it = uusGrupp.entrySet().iterator();

while(it.hasNext()){
    HashMap<String,String > gruppResult = new HashMap<>();
    Map.Entry pair = (Map.Entry)it.next();
    gruppResult.put("First line", pair.getKey().toString());
    gruppResult.put("Second line", pair.getValue().toString());
    grupiLiikmed.add(gruppResult);
}

grupidView.setAdapter(adapter);

gruppNupp.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        EditText grupp = findViewById(R.id.grupp);
        if(!grupp.getText().toString().equals("")) {
            uusGrupp.put(grupp.getText().toString(), "Grupp");
            grupp.setText("");
            grupidView.invalidateViews();
            adapter.notifyDataSetChanged();

        }
    }
}

Solution

  • It doesn't look like you're adding anything to the list backing the adapter grupiLiikmed in your onClick call. You'll have to call something like this to update the adapter:

    HashMap<String,String> newItem = new HashMap<>();
    newItem.put("First line", "something");
    newItem.put("Second line", "else");
    grupiLiikmed.add(newItem);
    adapter.notifyDataSetChanged();