[英]Copy elements of a custom arrayList to a String
我正在尝试将自定义arrayList中的元素放到String中。 但是,当我尝试对其进行迭代时,它仅显示最后一个条目。 这适用于待办事项应用程序,该应用程序应具有任务名称,并根据任务是否完成而为1或0。
到目前为止,这是代码:
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;
}
那是因为您要覆盖每个条目的变量,而只保留最后一个元素。 我在您的代码上添加的内容将在字符串副本的末尾附加每个条目。
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;
}
您可以像下面这样使用
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.