Home > Back-end >  Add a new item in ArrayList Adapter outside its area
Add a new item in ArrayList Adapter outside its area

Time:01-25

So I'm having here a problem adding a new item on a ArrayAdapter-ArrayList if I call a .add outside or inside another public void. I'm using a list view that is inside xml file and replace it with ArrayList Adapter

This is my code outside onCreate, just below the AppCompatActivity:

  List<String> recolis = new ArrayList<>();
    String [] startinglist = {};

And this is my code inside onCreate:

 ArrayList<String> recolis = new ArrayList<String>(Arrays.asList(startinglist));
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, recolis);
        recolist.setAdapter(adapter);

So my issue is, whenever I call a new recolis.add("new"); outside onCreate or in another public void. Let's say I have a switch case, it will call a new public void "insomnia();" Call new public void where it has the .add function

And inside "insomnia();" I want to add a new item to ArrayList, but the problem is it won't even add. This is a new public void

I tried to find any related problems but none of them works. I just want to add a new item in ArrayList outside its area.

I do really really appreciate for your any help. Thank you!

CodePudding user response:

Within your OnCreate function, you are reinitializing your recolis. Also, did you mean to type recolist.setAdapter(adapter); ? From the code you've provided, it seems recolis is what you meant. Anyway, instead of ArrayList<String> recolis = new ArrayList<String>(Arrays.asList(startinglist)); You should do recolis = new ArrayList<String>(Arrays.asList(startinglist)); This is because when you do ArrayList recolis, Java will take that as "Oh okay, this is a NEW variable, anything with this name is merely coincidence." That means, that when you go to actually update recolis, it will NOT update your recolis with the adapter, but the one you provided right below AppCompatActivity, meaning that while it is "adding" to the list, it's not actually going anywhere. Let me know if this works!

  • Related