简体   繁体   English

为什么我的 SharedPreferences 在应用程序启动后没有立即加载?

[英]Why aren't my SharedPreferences loading right after application launch?

I'm using SharedPreferences to store user input so that when application is closed and then re-launched the user input stays there and not auto deletes itself.我正在使用SharedPreferences来存储用户输入,以便当应用程序关闭然后重新启动时,用户输入会保留在那里并且不会自动删除自身。 But, when I re-launch the application after closing it the user input doesn't appear on screen until the user adds another input.但是,当我在关闭应用程序后重新启动应用程序时,用户输入不会出现在屏幕上,直到用户添加另一个输入。 After the user adds another input, the inputs that were added in the session before closing the application now appear on screen.在用户添加另一个输入之后,在关闭应用程序之前在 session 中添加的输入现在会出现在屏幕上。 Any idea why this might be happening?知道为什么会发生这种情况吗? Thanks!谢谢!

This is what's happening in case a visual example is needed.如果需要视觉示例,就会发生这种情况。

This is the method that's in charge of loading what the user inputed and I call this method on the onCreate method:这是负责加载用户输入内容的方法,我在onCreate方法上调用此方法:

    public void loadSemesters() {
        sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString("SEMESTER_LIST", null);
        Type type = new TypeToken<ArrayList<Semester>>() {
        }.getType();
        mySemesters = gson.fromJson(json, type);

        if (mySemesters == null) {
            mySemesters = new ArrayList<>();
        }
    }

This method is in charge of saving the user input:此方法负责保存用户输入:

   public void saveSemesters() {
        sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        Type type = new TypeToken<ArrayList<Semester>>() {
        }.getType();
        String json = gson.toJson(mySemesters, type);
        editor.putString("SEMESTER_LIST", json);
        editor.apply();
    }

As a solution i guess you forgot to set the data to your views ( Update UI ) after the app restarts so you need to update your UI作为一种解决方案,我猜您在应用重新启动后忘记将数据设置为您的视图(更新 UI),因此您需要更新您的 UI

public void loadSemesters() {
       sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
       Gson gson = new Gson();
       String json = sharedPreferences.getString("SEMESTER_LIST", null);
       Type type = new TypeToken<ArrayList<Semester>>() {
       }.getType();
       mySemesters = gson.fromJson(json, type);

       //Your have your semeters arraylist , now get the data from the list and 
       //set it to 
      // your views

       if (mySemesters == null) {
           mySemesters = new ArrayList<>();
       }
   }

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

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