2

I'm trying to update listView items when application is running. I can make it work by using a String[] instead of List but my goal is make it work with List so I can add more items to listView while application is running.

private List<String> items;

I have made a List to MainActivity class.

ListView listView = (ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, items);
listView.setAdapter(adapter);

This doesn't work. I tried to hassle with items.ToArray(), but didn't found a solution. Tried Googling, but all results from Google redirects only to tutorials that shows how to make listView and every of tutorials were based on String[] array.

Application works fine if I use following:

private String[] items = {"Banana", "Lime"};

I want manage items real time when user adds them to list by using: "adapter.notifyDataSetChanged();"

I'm beginner on Java and especially about Android Developing so help is appreciated.

Weird E.
  • 66
  • 1
  • 2
  • 7
  • Assuming you initialized the arraylist, then your code should work. `adapter.add("hello")` would update the list without the need for `notifyDataSetChanged` – OneCricketeer Jul 31 '16 at 19:32

1 Answers1

1

You have two approach to do this:

  • Convert your List to Array (you can find a good example here).
  • Create your own Adapter and use List ( another good example here).

First Approach:

List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");

String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);

for(String s : stockArr)
    System.out.println(s);

Second Approach:

public class CustomAdapter extends BaseAdapter{   

    String [] result;
    Context context;
    int [] imageId;
    private static LayoutInflater inflater=null;

    public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
        // TODO Auto-generated constructor stub
        result=prgmNameList;
        context=mainActivity;
        imageId=prgmImages;
         inflater = ( LayoutInflater )context.
                 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
}
Community
  • 1
  • 1
Amir
  • 16,067
  • 10
  • 80
  • 119
  • Damn. Didn't found such information through Google. I guess I am at so beginning so I didn't knew good enough keywords. Thanks Amir. – Weird E. Jul 31 '16 at 19:22
  • @WeirdE. If answers gives you enough information you can accept them. – Amir Jul 31 '16 at 19:23
  • Sure. Waiting for it. Site requires 5 minutes before I can accept it. – Weird E. Jul 31 '16 at 19:24
  • You could extend ArrayAdapter instead of BaseAdapter. Otherwise, you left out that you need to implement `getCount` and such – OneCricketeer Jul 31 '16 at 19:31
  • @cricket_007 yes you're right. I just paste some piece of code which is necessary ¯\_(ツ)_/¯ – Amir Jul 31 '16 at 19:33