Add a new item in ArrayList Adapter outside its area - java

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!

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

Why do "ArrayList.remove" remove both in local variable and in myApplicationClass? [duplicate]

This question already has answers here:
Why does one arraylist change when a copy of it is modified
(6 answers)
Closed 5 years ago.
I have a MyApplicationClass into which I stock An ArrayList, then I create a variable ArrayList in my MainActivity and assign it the variable in MyApplciationClass and finally I call remove to the local variable to remove a value but the value is removed from both MyApplicationClass and the localvariable and it can be possible because I just retrieve the list from MyApplicationClass I didin't make anything else ?
Here is my code:
MyApplicationClass:
private ArrayList<String> text = new ArrayList<>();
public ArrayList<String> getText() {
return text;
}
public void addTest(String input) {
text.add(input);
}
MainActivity:
//When click on a button:
final MyApplicationClass myApplicationClass = (MyApplicationClass) getApplicationContext();
//I add some example values
myApplicationClass.addTest("1");
myApplicationClass.addTest("2");
//Here I retrieve the variable in MyApplicationClass to put in into a local variable:
ArrayList<String> testlocal = myApplicationClass.getText();
//And here I remove a value from the localvariable testlocal:
test.remove(1);
But when I debug and see variable I can see that the value is correctly deleted in testlocal but too in text in MyApplicationClass but I just want to remove a value from textlocal.
Thanks a lot.
The two variables refers to the same ArrayList object.
This assignment makes testlocal refers to the ArrayList object of the MyApplicationClass instance :
ArrayList<String> testlocal = myApplicationClass.getText();
To create a new ArrayList, you have to create a new object by using the new operator :
ArrayList<String> testlocal = new ArrayList<>(myApplicationClass.getText());
Now removing (or even adding) one element in any of these two ArrayList objects will never be reflected in the other ArrayList object.
But note that new ArrayList(Collection c) will not make a deep copy of the elements copied.
So modifying the state of any element in one or the other ArrayList object will be still reflected in the other.
In your actual case, it is not a problem as the Lists store only String values that are de facto immutable.
You need to create a copy of the original list. Also, generally it's better to depend on the List interface instead of the ArrayList class.
You can create the copy in the getText() method. This is easy because you need to modify the code on only one place. On the other hand, no outer class will be able to change your MyApplicationClass:
public List<String> getText() {
return new ArrayList<>(text);
}
Alternatively, you can create a local copy whenever you retrieve it:
List<String> testlocal = new ArrayList<>(myApplicationClass.getText());

What's wrong with this java code

private static final List<String> datas = new List<String>() {{
add("aaaa");
add("bbbb");
System.out.println(datas);
}};
I have declared a list and added some data. Then I want to print the data stored within that list. But the code does not work. Could you explain why?
You are using here what is refered to as double brace initialization. Basically, this creates an anonymous class with an initializer that does some processing, like adding data to the list.
Written with added line breaks, this is what it really looks like:
private static final List<String> datas = new List<String>() {
{
// this is the initializer block
add("aaaa");
add("bbbb");
System.out.println(datas);
}
// huh? no methods of List are implemented here!
};
The first problem is that you are trying to create an anonymous class of List but you are not overriding any of its abstract methods. This results in a compilation error.
The second "problem", is that the System.out.println class is inside the initializer, but as this moment, the variable datas is null, so that's will be printed (and that's probably not what you want).
So first, what you want is to create an anonymous class derived from ArrayList, or some other list implementation, so that you don't have to override any methods. Second, you don't want to print the content of the variable inside the initializer, but outside of it. Third, and probably most important: you don't want to use double brace initialization at all!
You need to implement the methods of the java.util.List interface. and your code is not inside a method or static block.
I think it's easier
// Creating an empty array list
ArrayList<String> list = new ArrayList<String>();
// Adding items to arrayList
list.add("Item1");
list.add("Item2");
Your code is implementing List interface as anonymous class, so you have to implement all List methods. I think you had in mind static list initialization that should be done like:
private static final List<String> datas = new ArrayList<String>();
static{
datas.add("aaaa");
datas.add("bbbb");
System.out.println(datas);
};

How to append items to ArrayList?

I've got a function to create syllables for words.
I use it like this: syllables(word1field); - creates List with syllables: aa,bb,cc
and syllables(word2field); - creates List with syllables: dd,ee,ff
And in the result I get dd,ee,ff, but I need aa,bb,cc,dd,ee,ff.
Is there possibility to append second list to first?
You get dd,ee,ff because when you call the same method again, it overrides the first ArrayList that is created.
The best thing you could do, that I can think of, is to make your ArrayList global because currently you just keep getting rid of the previous values and create a new ArrayList with the new values you give it. Try doing something like:
public class MyClass {
private List<String> myArray;
public MyClass() {
myArray = new ArrayList<String>();
}
public void syllables(wordfield) {
// do whatever you need to with wordfield
myArray.add(syllable);
}
I don't know how you've got everything laid out but this is the best solution I can think of.

ArrayList<String> Object assignment

I have two separate objects ArrayList<String> in two separate packages Top and top10. I assign the value of top10 to Top in my activity. And now if I remove an element from Top it also gets removed from top10. I don't know why is this happening? I feel totally dumbfounded. Is there something I don't know about java? Or is it android?
This is my activity code:
ArrayList<String> Top = new ArrayList<String>();
// ServiceCall is the name of the class where top10 is initialized.
Top = ServiceCall.top10;
System.out.println("top WR: "+ServiceCall.top10);
if(Top.get(0).equals("Please Select")) Top.remove(0);
System.out.println("top WR: "+ServiceCall.top10);
The second printed out statement has one element less than the one before.
You are pointing to the same Object.
Top = ServiceCall.top10;
is not creating a new Object, but making a reference to the other one, hence all changes in both pointers will be reflected in the same Object.
You'll have to create a new one passing the other one as parameter:
List<String> Top = new ArrayList<String>(ServiceCall.top10);
You are pointing Top to top10, not creating a new list (your initializer is effectively unused right now, as you are just repointing it to the other list.)
You should do:
ArrayList<String> Top = new ArrayList<String>(ServiceCall.top10);
This will create a shallow copy.

Elements in java ArrayList taking up two places

I have made a LinkedList to store State objects which is a class I have created. I can add states to the list as expected, but whenever I try the size() method on the list it always returns twice the amount of elements I have added. Why is it doing this and how can I then use the get(n) method if each element has 2 values of n?
Here's the code used to create and add to the list:
static ArrayList<State> stateTable = new ArrayList<State>();
stateTable.add(new State(new Item(0,0)));
I will add that the adding to the list is done inside the constructor for State objects so that all created States get put in the stateTable.
Thanks
I will add that the adding to the list is done inside the constructor
for State objects so that all created States get put in the
stateTable.
If you already add the states to your list inside the constructor and additionally have the line
stateTable.add(
new State(new Item(0,0)) // <= first time inside new State(...)
); // <= second time explicitely in this line
then you are indeed adding it twice.
search for .add( and make sure you are not calling it in multiple places.
If your ArrayList is not marked as private mark it as private.
If you return your ArrayList from a method do return a read-only version via: Collection.unmodifiableList(stateTable);
If you load the data in one method or the constructor and do not intend to do it anywhere else than do it something like:
private static final List<State> stateTable;
static
{
final List<State> temp;
temp = new ArrayList<State>();
temp.add(new State(new Item(0,0)));
stateTable = Collections.unmodifiableList(stateTable);
}
Using the unmodifiableList will cause your program to crash if you add objects into it.

Categories