【发布时间】:2016-06-19 17:47:14
【问题描述】:
我是一般编程的新手,我正在尝试将项目添加到我创建的 ArrayList 中。然后我尝试在 Android TextView 中显示 ArrayList 以确认 ArrayList 的内容。简化代码如下:
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));
}
我知道共享首选项已正确保存,因为如果我单独检索它们,它们会按照我的预期出现。当我显示 ArrayList 的内容时,仅显示添加到我的 ArrayList 的最后一项。其余代码如下:
String listRepresentation = "";
for (String name : namesArray)
if ("".equals(listRepresentation))
listRepresentation = name; else
listRepresentation = ", " + name;
textView1.setText(listRepresentation );
同样,唯一出现的是在 for 循环中添加的姓氏。任何帮助将不胜感激 - 谢谢!
【问题讨论】:
-
只是为了获取逗号分隔的名称,您可以使用下面的代码。
String names = namesArray.toString(); textView1.setText(names.substring(1, names.length()-1));
标签: java android arraylist add