我正在与 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));
我可以确认正在存储不同的数据。更改第一个项目是数组更改所有项目。
感谢您的帮助。
最佳答案
您没有在外部 while 循环中初始化 myData。因此,请在外部 while 循环中初始化 myData。
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++;
myData = "";
filename = "newAssessment(" + fileNameNumber + ").json";
internalFile = new File(directory, filename);
}
LVAssessments.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data));
关于java - 使用 ArrayList 中的数据填充 Android ListView 是将每个项目设置为与第一个项目相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36855053/