这是我保存json的代码:
public void saveCrimes (ArrayList<Crime> crimes) throws JSONException, FileNotFoundException, IOException {
JSONArray jsonArray = new JSONArray();
for (Crime c:crimes)
{
jsonArray.put(c.convertToJson());
}
Writer writer = null;
OutputStream out = context.openFileOutput(fileName, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(out);
writer.write(jsonArray.toString());
writer.close();
out.close();
}
And this is my code of reading json :
public ArrayList<Crime> loadCrimes () throws IOException, JSONException {
ArrayList<Crime> crimes = new ArrayList<Crime>();
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
String line = null;
try {
InputStream in = context.openFileInput(fileName);
reader = new BufferedReader(new InputStreamReader(in));
while((line = reader.readLine()) != null)
builder.append(line);
JSONArray array = (JSONArray)new JSONTokener(builder.toString()).nextValue();
for(int i = 0; i < array.length(); i++)
{
crimes.add(new Crime(array.getJSONObject(i)));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if (reader != null)
reader.close();
}
return crimes;
}
问题是:保存json的代码是正确的,但是当我在手机上运行我的应用程序时,创建新的犯罪,并重新启动应用程序,json存储之前无法读取。让我更困惑的是,当我在模拟器上运行它时,它运行良好。为什么呢?
答案 0 :(得分:0)
我知道出了什么问题。如果更改非常小,Android Studio 2.0无法保存您在代码中所做的更改。解决方案是在运行应用程序之前构建apk。