Arrayadapter custom id

I have an array extending from baseadapter and using it with an arraylist to store data. I need to update a single item. So I need to provide an ID for each element when adding to the arraylist. Then I'll update it with a set

method like this:

randomsList.set(position,new Random(user,1));

      

I mean, I need a position value. Someone said that you need to implement map

for this. But I don't know how to do it. I need an example.

This is my class:

private static class Randoms{
    private List<Random> randoms=null;

    public Randoms(List<Random> randoms) {
        this.randoms=randoms;
    }
    public Random get(int position) {
        return randoms.get(position);
    }
    public int size() {
        return randoms.size();
    }
}

      

And this is my adapter:

private static class RandomsAdapter extends BaseAdapter{
    private Randoms randoms;
    private LayoutInflater inflater;
    private Context context;
    private RandomsAdapter(Context context,Randoms randoms) {
        this.randoms=randoms;
        this.inflater = LayoutInflater.from(context);
        this.context=context;
    }
    public void updateRandoms(Randoms randoms) {
        this.randoms=randoms;
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return randoms.size();
    }
    @Override
    public Random getItem(int position) {
        return randoms.get(position);
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    public View getView(int position,View convertView,ViewGroup parent) {

    }

}

      

+3


source to share


1 answer


If I understand you correctly, you want to use the position of the element in the list as the id value of the element:

You can create a wrapper class Random

that will contain the object Random

and its identifier.

class RandomWrapper {
    private Random rand;
    private int id;
    RandomWrapper(Random rand, int id) {
        this.rand = rand;
        this.id = id;
    }
    public Random getRand() {
        return this.rand;
    }
    public int getID() {
        return this.id;
    }
}

      

So, if you want to access yours Random

, call yourRandomWrapper.getRand()

, and if you want to get the id, callyourRandomWrapper.getID()



So, for example, adding 5 items to your list:

for(int i = 0; i < 5; i++) {
    randomsList.add(new RandomWrapper(yourRandomObj, i));
}

      

If you want to create a unique identifier for your objects, you can use the class java.util.UUID

. If you are interested in how it works you can check this answer or Oracle Docs

0


source







All Articles