我正在使用 JSON 格式将一些数据保存在文件中。当我添加一两条记录时,一切都很好。我可以很容易地检查它们是否正确或按我的意愿处理它们。但是,当我添加第三条记录时,eclipse 和 AVD 冻结并且此后不再响应,所以我需要终止进程。我相信原因在于下面的代码。请告诉我如何处理这个问题。日志显示,该问题不在无限循环中。它可能是由 LinkedHashSet 引起的吗?
private void writeJSONtoFile(String jsnStr) {
FileOutputStream fos;
Set<String> copy = new LinkedHashSet<String>();
List<String> adds = new ArrayList<String>();
try {
File file = getBaseContext().getFileStreamPath("json_local.xml");
if(file.exists()){
JSONObject json1=null;
try {
json1 = new JSONObject(readData());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String fav = json1.toString();
String record = fav.substring(fav.indexOf('[')+1, fav.indexOf(']'));
Log.d("RECORD",record);
int stop = 0;
for (stop=0; stop < record.lastIndexOf('}');) {
String rec = record.substring(
record.indexOf('{', stop),
record.indexOf('}', stop + 1) + 1);
stop = record.indexOf('}', stop);
Log.d("RECORD",rec);
adds.add(rec);
}
}
String record = jsnStr.substring(jsnStr.indexOf('[')+1, jsnStr.indexOf(']'));
String rec = record.substring(record.indexOf('{'), record.indexOf('}')+1);
adds.add(rec);
copy.clear();
copy.addAll(adds);
adds.clear();
adds.addAll(copy);
int pages=(int) Math.ceil(adds.size()/10.0);
int total=adds.size();
String result = "{\"count_page\":"+pages+",\"count\":\""+total+"\",\"results\":[";
for (String temp : adds) {
result+=temp;
result+=",";
}
result = result.substring(0, result.length() - 1);
result+="]}";
fos = openFileOutput("json_local.xml", Context.MODE_WORLD_WRITEABLE);
fos.write(result.getBytes());
Log.i("json_convert", result);
fos.flush();
fos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.i("Favorites", "" + jsnStr);
Toast.makeText(getApplicationContext(),
item_title + " добавлено в избранное", Toast.LENGTH_SHORT)
.show();
}