将数据保存在文件onStop中并在onCreate中读取

时间:2015-04-26 16:30:37

标签: android

我正在基础活动的onPause中创建并保存文件中的数据,但我正在读取其他活动的onCreate中的信息。问题是,onPause保存已被调用,并且似乎没有错误出现在logcat中。但是,如果我尝试阅读onCreate中的信息,我会收到我在那里的旧内容,而不是我保存的新内容。

    public String parseToJsonString(Object object){
            String json = gson.toJson(object);
            return json;
        }

     public static boolean save(Context ctx, String filename, String content){
            boolean wasSaved = false;

            FileOutputStream fos = null;
            try {
                fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
                fos.write(content.getBytes());
                fos.flush();
                wasSaved = true;
                Log.d(TAG, content);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(fos != null)
                        fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return wasSaved;
        }

     @Override
        protected void onPause() {
            super.onPause();
            Log.d(TAG, "onPause");
            String jsonSettings = APP().parseToJsonString(settings);
            FileUtil.save(this, getString(R.string.file_settings_preferences), jsonSettings);
        }

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            if(getResources().getBoolean(R.bool.phone_size))
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

            setContentView(R.layout.att_base_activity);
            preferences = APP().getSecuredPreferences();
            workflow = APP().createWorkflow();

            settings = getAttendanceSettings();
            Log.d(TAG, settings.toString());

            toolbar = (Toolbar) findViewById(R.id.ab_tool_bar);
            setSupportActionBar(toolbar);
        }

public AttSettings getAttendanceSettings() {
        AttSettings settings = null;

        try {
            JSONObject jsonSettings = FileUtil.getJSONContentFromFile(this,
                    getString(R.string.file_settings_preferences));
            if (jsonSettings != null)
                settings = new AttSettings(jsonSettings);
            else
                settings = new AttSettings();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return settings;
    }

我真的不知道我做错了什么,请帮助。

0 个答案:

没有答案