简体   繁体   English

从Android内部存储读取JSON错误

[英]Reading json from android internal storage error

This is my code of saving 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;
    }

The question is: code of saving json is correct, but when I run my application on my phone, create new crime, and restart the app, json stored before cannot be read. 问题是:保存json的代码是正确的,但是当我在手机上运行应用程序,创建新犯罪并重新启动应用程序时,无法读取之前存储的json。 What makes me more confused is that when I run it on an emulator, it works well. 让我更加困惑的是,当我在模拟器上运行它时,它运行良好。 Why? 为什么?

I know what is wrong. 我知道怎么了 Android Studio 2.0 cannot save the changes you have made in your codes if the change is very small. 如果更改很小,Android Studio 2.0将无法保存您在代码中所做的更改。 The solution is that building apk before running your application. 解决方案是在运行应用程序之前先构建apk。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM