【发布时间】:2016-04-26 04:03:40
【问题描述】:
我正在使用 android studio 并尝试使用数据填充 ListView,这些数据存储在设备内部存储的文件中。我可以创建一个包含确切数量的项目的列表,因为有文件,但它们都应该显示不同的信息。目前,它们都显示与 ArrayList 中的第一项相同的数据。
代码如下:
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
int counter = 0;
int fileNameNumber = 1;
filename = "newAssessment(" + fileNameNumber + ").json";
internalFile = new File(directory, filename);
JSONObject jsonObject;
while (internalFile.exists()) {
files.add(counter, internalFile);
try {
FileInputStream fis = new FileInputStream(internalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
}catch(IOException e){
e.printStackTrace();
}
try {
jsonObject = new JSONObject(myData);
String assessmentDate = jsonObject.getString("assessmentDate");
String orchard = jsonObject.getString("orchard");
data.add(counter, assessmentDate + " : " + orchard);
}catch(JSONException e){
e.printStackTrace();
}
counter++;
fileNameNumber++;
filename = "newAssessment(" + fileNameNumber + ").json";
internalFile = new File(directory, filename);
}
LVAssessments.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data));
我可以确认正在存储不同的数据。更改最先出现的项目是数组更改所有项目。
感谢您的帮助。
【问题讨论】:
-
你在哪里初始化数据?
-
是类变量
private List<String> data = new ArrayList<>(); -
在你的方法中声明
-
@KishuDroid 在 while 循环内初始化不是一个好主意。如果我们尝试这样初始化,那么只会添加最后一个数据,所有其他数据都不会添加,因为每次 List 都会重置
-
@Amsheer:是的,我明白了你的意思,这就是为什么我评论说要在方法中初始化
标签: java android listview arraylist android-internal-storage