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;
}
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;
}
You can use like below
public String getShareData() {
copy="";
for (Entry n : mEntries) {
name1 = n.getS();
i = boolToInt(n.isB());
if(copy.length()==0)
copy = name1 + "\t" + i + "\n";
else
copy = copy + name1 + "\t" + i + "\n";
}
return copy;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.