Skip to content
Advertisement

ListView is not updating once I add elements to the array

package com.example.pillappreal;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    public ArrayList<Drug> list = new ArrayList<>();
    public ArrayList<String> nameList = new ArrayList<>();
    public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    ArrayAdapter<String> adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        nameList.add("Test Drug");
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, nameList);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = findViewById(R.id.listView1);
        listView.setAdapter(adapter);
        nameList.add("Test Drug 3");
    }

    public void addNewDrug(View view) {
        Intent intent = new Intent(this, AddNewDrugActivity.class);
        startActivity(intent);
    }

    public void testMethod(View view) {
        Intent intent = new Intent(this, MainActivity.class);
    }

    public void addNewDrug(Drug drug) {
        list.add(drug);
        nameList.add(drug.name);
        nameList.add("Test Drug 2");
        adapter.notifyDataSetChanged();
    }
}

I want my ListView to update as I add things to the array. It doesn’t work. I added a notifyDataSetChanged() to the updater code, but it does nothing. I’ve used Log.d tags to make sure the Arrays actually have their values, at pretty much every point of the code and they do. The issue seems to be that the ListView doesn’t update since its in onCreate which runs once. I can’t put it anywhere else though.

Advertisement

Answer

I think an other solution is that you call the notifyDatasetChange() in the onResume() function (You should override the onResume() function)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement