-4

So I have arraylist modelData that populates a recyclerview using sqlite database in some activity.! Now in my MainActivity I want an string arraylist of names from the modelData !

that's what did so far..

 // inside the onCreate of MainActivity 

//code ..
db = new DBHandler(this, null, null, 1);
modelData = new ArrayList<AzkarModel>();
modelData = db.getDataFromDB();

for (AzkarModel o : modelData) {
   ArrayList<String> names = new ArrayList<>();
   names.add(o.getName());
}

for (int i = 0; i< modelData.size();i++){
  names.add(modelData.get(i).getName());
 Log.i("The List Log", names);

}

Two problems

1) [FIXED] The names arraylist is showing the same element twice at first and end

  I/ The List Log: [Mike, John, Sam, Nora, Mike]

2) The arraylist names doesn't get updated..! when I add/edit/delete from the recycler and go back to the MainActivity I don't see the new changes unless I close the app then open it again..! I can't use notifyDataSetChanged since there's no adapter here.!

Alaa AbuZarifa
  • 1,171
  • 20
  • 39
  • 2
    why are you creating new object of aarylist in for loop? – Divyesh Patel May 29 '17 at 12:42
  • 1
    Please post the correct code, this is not going to compile because a scope issue in the for loop with: ArrayList names = new ArrayList<>(); – ΦXocę 웃 Пepeúpa ツ May 29 '17 at 12:44
  • @DivyeshPatel I'll fix that – Alaa AbuZarifa May 29 '17 at 12:48
  • see the update guys – Alaa AbuZarifa May 29 '17 at 12:49
  • First off, your AzkarModel simply have two models with same name. That's on you, it is not related to the code you posted in here (or not yet). Secondly, `onCreate` indeed means that this is done only once when app is created. If you want a live list, then you shold have this code elsewhere. – M. Prokhorov May 29 '17 at 12:52
  • @M.Prokhorov what do u mean that `AzkarModel` have two models with same name!? I have a model class called `AzkarModel` and has name variable with setters and getters and it connected to the db..!! I think you don't understand me correctly..read the question again to know why I used this code inside MainActivity – Alaa AbuZarifa May 30 '17 at 06:24
  • nevermind ,, I found a solution.. you are right.. I moved the code from onCreate to onResume instead and works now..! – Alaa AbuZarifa May 30 '17 at 06:39

1 Answers1

2

Once you have an array list object, populate it inside a loop

ArrayList<String> modelNames = new ArrayList<>();

for (AzkarModel model : modelData) {
    modelNames.add(model.getName());
}

Now you have an array list with model names inside. Concerning the second question, please use an recyclerview adapter here you can find a nice tutorial.

Alex Kamenkov
  • 891
  • 1
  • 6
  • 16