0
これはJSONを保存する私のコードです:アンドロイド内部ストレージエラーから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は読み込めません。私をもっと混乱させる原因は、エミュレータで実行するとうまくいくことです。どうして?
あなたはどんなエラーがありますか?ファイルがない?または何らかのエラーdurignの書き込み?デバッグしましたか? –
'新しい犯罪を作成し、アプリケーションを再起動します。以前に保存されたjsonは読み取れません。あなたは、最後に保存された犯罪だけを読むことができ、古いものは読むことができないことを意味しますか? – greenapps
'builder.toString()'が正しいテキストを出力しているかどうか最初に確認する必要があります。それを記録またはトーストする。 – greenapps