Wdej Wdej - 5 months ago 8
Java Question

Only the last item added in ArrayList shows

I am new to programming in general and am trying to add items to an ArrayList I created. I am then trying to display the ArrayList in an Android TextView to confirm the contents of the ArrayList. The simplified code is as follows:

public TextView textView1;
public ArrayList<String> namesArray = new ArrayList<>();
public static final String DEFAULT= "N/A";

public void contactsArray() {
loadArrayButton = (Button) findViewById((R.id.loadArrayButton));
loadArrayButton.setOnClickListener(new View.OnClickListener() {
@Override

public void onClick(View view) {
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
int howMany = sharedPreferences.getAll().size();

for (int i = 1; i < howMany; i ++) {
String name = sharedPreferences.getString("name" + i, DEFAULT);
namesArray.add(sharedPreferences.getString("name" + i, DEFAULT));
}


I know the shared preferences are correctly saved because if I retrieve them individually they come up how I would expect them. When I display the contents of the ArrayList only the last item added to my ArrayList shows. The remaining code is as follows:

String listRepresentation = "";
for (String name : namesArray)
if ("".equals(listRepresentation))
listRepresentation = name; else
listRepresentation = ", " + name;
textView1.setText(listRepresentation );


Again the only thing that comes up is the last name added on in the for loop. Any help would be appreciated- Thanks!

Answer

In your loop to display the result you overwrite the string at every index.

Use += to fix the issue:

 String listRepresentation = "";
 for (String name : namesArray) {
     if ("".equals(listRepresentation)) {
          listRepresentation += name;
      } else {
          listRepresentation += ", " + name;
      }
 }
 textView1.setText(listRepresentation );

The operator += is equal to listRepresentation = listRepresentation + ...;

Comments