3

I have an arrayadapter extending from baseadapter and using it with an arraylist for store data.I need to update individual item.So I need to give an id for each item when adding to arraylist.Then I will update it with set method like this:

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

I mean I need a position value.Somebody said you need do implement of map for this.But I don't know how can I 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) {

    }

}
Serkay Sarıman
  • 465
  • 1
  • 10
  • 17

1 Answers1

0

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

You can create a wrapper class for Random that will hold the Random object and its id.

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

This way, if you want to access your Random, call yourRandomWrapper.getRand() and if you want to get the id, call yourRandomWrapper.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 generate a unique ID for your objects, you can use the java.util.UUID class. If you are interested in how it works, you can check out this answer or the Oracle Docs

Community
  • 1
  • 1
nem035
  • 34,790
  • 6
  • 87
  • 99