in my application user can create an array of elements.E.g. he can assign a name of Array1 to Array2. My problem is that every time i launch the app, the Array2 arraylist is empty.
I define the array like this:
ArrayList<String> Array2 = new ArrayList<String>();
and this how i populate the arraylist:
Array2.add(strBuf.toString()); //strBuf is StringBuffer created from two strings
Do i miss something or should i save to array to a file or sg else?
Update:
I have two spinners and an OK button in a dialog. When user selects items from the spinners and clicks OK, an element is add the arraylist. This is done by concatenating two strings, one for the 1st spinner, one for the second (linkname1 and linkname2).
At first when the arraylist is empty, the item is added. When there is at least one item in the arraylist, there is a verification whether the item is already in the arraylist. If it is, it is overwritten, if not, it is added.
Button okbtn = (Button) dialog.findViewById(R.id.ButtonOK);
okbtn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if ((linkname1!="") && (linkname2!=""))
{
strBuf = new StringBuffer();
strBuf.append(linkname2);
strBuf.append(" ");
strBuf.append(linkname1);
if (Array2.size() < 1)
{
Array2.add(strBuf.toString());
}
else if (Array2.size() > 0)
{
for (int i=0; i<Array2.size(); i++)
{
spaceIndex4 = Array2.get(i).indexOf(' ');
if (spaceIndex4 > 0)
{
if (linkname1.equals(Array2.get(i).substring(spaceIndex4+1, Array2.get(i).length()))==true)
{
van=1;
Array2.remove(i);
Array2.add(strBuf.toString());
}
else
{
van=2;
}
}
}
}
}
dialog.dismiss();
if (van == 2)
{
Array2.add(strBuf.toString());
}
}
});
I use the items in the Arraylist later (when user clicks on specific items of a ListView, items of this ArrayList should appear).
When i quit the app, both in Eclipse and on my phone, and then open it again, the arraylist is empty (so the items are not appearing anymore when user clicks on an item of the ListView).
There is no Array2.clear() or such in the code.
Your ArrayList is just a variable. Variables die once the program closes, in any programming environment. You need to save your items somewhere permanent. Write it out to a file, or depending on how much you need to store, you can use SharedPreferences. Then just read it back in and repopulate the ArrayList in onCreate().