How do I use List<String> for ArrayAdapter values (Java, Android)

Weird E. picture Weird E. · Jul 31, 2016 · Viewed 8.2k times · Source

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.

Answer

Amir picture Amir · Jul 31, 2016

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);
    }
}