-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!

3
  • 1
    where is meModels.add(new MeModel(...)) and clear delete everything from list Commented Sep 20, 2017 at 15:51
  • @Pavneet_Singh ohhhh ,thanks!!!! I forget it! Commented Sep 20, 2017 at 15:54
  • Why you are doing clear the list? How is it possible to get data from the list after clearing? Commented Sep 20, 2017 at 15:56

4 Answers 4

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");
Sign up to request clarification or add additional context in comments.

1 Comment

i am glad that i could help , don't worry and you don't have to comment about yourself , sometime it happens, happy coding
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);

Comments

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.