Search code examples
androidlistviewcustom-adapter

Using a string array with a custom adapter to listview?


So i have a string array that I have. I am trying to pass each individual item from that string array to the custom adapter. I'm having trouble figuring out how to use the string that i pass in the custom adapter?

String[] that I pass

 String favorites = String.valueOf(FavList.get(0).get("favorites_list"));

                String[] separated = favorites.split(",");

                for (String s: separated) {
                    //Do your stuff here
                    FavoritesAdapter.add(s);
                }

Adapter.class

public class FavoritesAdapter extends ArrayAdapter<favoriteList> {
private final Context mContext;
private List<favoriteList> favlist;
private TextView favorites;
private TextView favDetail;

public FavoritesAdapter(Context context, ArrayList<favoriteList> objects) {
    super(context, R.layout.favorites_listview_single, objects);
    this.mContext = context;
    this.favlist = objects;
}


public View getView(final int position, View convertView, final ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
        convertView = mLayoutInflater.inflate(R.layout.favorites_listview_single, null);
    }


   // Here is where i cant figure out how to get the string that I passed.






    return convertView;
}

}


Solution

  • It would seem like you are only passing strings in, so I am not sure why you are using an ArrayAdapter<favoriteList>.

    If you change your adapter class to this:

    public class FavoritesAdapter extends ArrayAdapter<String> {
        private final Context mContext;
        private ArrayList<String> favlist;
        private TextView favorites;
        private TextView favDetail;
    
        public FavoritesAdapter(Context context, ArrayList<String> objects) {
            super(context, R.layout.favorites_listview_single, objects);
            this.mContext = context;
            this.favlist = objects;
        }
    
        public View getView(final int position, View convertView, final ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
                convertView = mLayoutInflater.inflate(R.layout.favorites_listview_single, null);
            }
    
            String favoriteItem = favlist.get(position) //get the string you passed 
    
    
            return convertView;
        }
    
        //...more code
    }
    

    Then when you pass the string, pass it like so:

    String favorites = String.valueOf(FavList.get(0).get("favorites_list"));
    ArrayList<String> favlist = (ArrayList<String>)Arrays.asList(favorites.split(","));
    
    FavoritesAdapter adapter = new FavoritesAdapter(getApplicationContext(), favlist);
    listView.setAdapter(adapter); //where listView is the view you declared previously