-1

How to add item in Arraylist android

I have Model (Not have Constructor, have setter and getter)

private int user_id;
private String firstname;
private String lastname;
private String pic;

and my code

List<MeModel> meModels = new ArrayList<>();

meModels.clear();
meModels.get(0).setFirstname("Hello");
meModels.get(0).setLastname("World");

it's not working.

How to add this, thanks!

Aldeguer
  • 821
  • 9
  • 32
ARR.s
  • 769
  • 4
  • 20
  • 39

4 Answers4

5

After applying List#clear() will empty your list so you will no longer have the access to any item

List<MeModel> meModels = new ArrayList<>();

meModels.clear();
meModels.add(new MeModel(...));
// ^^^^^ add item
meModels.get(0).setFirstname("Hello"); // get item
meModels.get(0).setLastname("World");
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • i am glad that i could help , don't worry and you don't have to comment about yourself , sometime it happens, happy coding – Pavneet_Singh Sep 20 '17 at 16:04
2

It must be returns IndexOutOfBoundsException. Because there is no item in the list. Why don't you create a constructor for your model? If I were you, I would create a constructor and do something like this:

Model model = new Model();
model.setBlahBlah(..);
meModels.add(model);
fena coder
  • 217
  • 4
  • 17
0

As suggested by Pavneet_Singh you must first add an item and then you can accesss it. Like this

List<MeModel> meModels = new ArrayList<>();
meModels.clear();
meModels.add(new MeModel());
meModels.get(0).setFirstname("Hello");
meModels.get(0).setLastname("World");

Anyhow a more performant approach is to costruct first the object and then to add it to the ArrayList, like this:

List<MeModel> meModels = new ArrayList<>();
meModels.clear();
MeModel meMod = new MeModel()
meMod.setFirstname("Hello");
meMod.setLastname("World");
meModels.add(meMod);

This because as you can see by this way you save a call for each row, that is get(0). It may seems a stupid thing, but in a big iteration or on an old and less powerful device it could be important

firegloves
  • 5,581
  • 2
  • 29
  • 50
0

After clearing data how can you access that object. First add object using add() method then you can access those models

SaurabhG
  • 173
  • 1
  • 11