0

My ArrayList contains has two records:

Item 1

Item 2

Here is the loop I am using to get these records

String global = null;

for(int i=0; i<arrayList.size(); i++) {
    String name = arrayList.get(i).getName().toString();
}

global = global+name+", ";
Log.d("items:", global);

Output:

D/items:: nullItem 2,

Whereas I was expecting

Item 1, Item 2 
1
  • 1
    try to do global = global + ", " +arrayList.get(i).getName().toString(); inside a loop Commented Apr 1, 2016 at 9:17

4 Answers 4

1

Initialize String global to empty string instead of null. Concatenation should not be done between null and a string object.

String global ="";
global = global +"item"; // global is now item;

If you initalize global to null

String global = null;
global = global + "item"; // treated as "null" + "item"

Modify global variable inside the loop, you are trying to access name variable outside its scope, so name variable is overwritten for each iteration in loop even if you declare name outside the loop.

for(int i=0; i<arrayList.size(); i++) {
  String name = arrayList.get(i).getName().toString();
  global = global+name+", ";
}
Sign up to request clarification or add additional context in comments.

Comments

1
StringBuilder global = new StringBuilder();

for(int i=0; i<arrayList.size(); i++) {
    global.append(arrayList.get(i).getName().toString());
}

Log.d("items:", global.toString());

1 Comment

edit global.append(", " +arrayList.get(i).getName().toString());
1
String global = "";

for(int i=0; i<arrayList.size(); i++) {
    global+ = arrayList.get(i).getName().toString();
}

Log.d("items:", global);

Comments

1

You could use a for each loop to avoid having to manage a loop index:

StringBuilder global = new StringBuilder();
for (Yourclass object : arrayList) {
    global.append(object.getName().toString());
}
Log.d("Items: ", global);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.