codelover codelover - 1 month ago 6
Java Question

Copy elements of a custom arrayList to a String

I am trying to put the elements from my custom arrayList to a String. But when i tried to iterate over it, it only prints the last entry. This is for a todolist app that should have the name of the task and either 1 or 0 depending on whether the task is done or not.

This is the code so far:

Entry.java

public class Entry {
String S;
boolean b;
public Entry(String S, boolean b) {
this.S = S;
this.b = b;
}
public String getS() {
return S;
}

public void setS(String S) {
this.S = S;
}

public void setB(boolean b) {
this.b = b;
}

public boolean isB() {
return b;
}


}

MainActivity.java

ArrayList<Entry> mEntries;
String copy;
String name1;
int i;
public String getShareData() {

for (Entry n : mEntries) {
name1 = n.getS();
i = boolToInt(n.isB());
copy = name1 + "\t" + i + "\n";
}
return copy;
}

public int boolToInt(boolean b) {
return b ? 1 : 0;
}

Answer

That's because you are overwriting your variable for each entry, only keeping the last element. What I added on your code will append each entry at the end of the String copy.

ArrayList<Entry> mEntries;
String copy;
String name1;
int i;
public String getShareData() {
    copy = "";
    for (Entry n : mEntries) {
        name1 = n.getS();
        i = boolToInt(n.isB());
        copy += name1 + "\t" + i + "\n";
    }
    return copy;
}

public int boolToInt(boolean b) {
    return b ? 1 : 0;
}
Comments