Android 在关闭应用程序或活动之前,共享首选项不会保存

Android 在关闭应用程序或活动之前,共享首选项不会保存,android,sharedpreferences,Android,Sharedpreferences,我正在制作一个活动,它将在活动开始执行任何功能之前编辑共享首选项。我被困住了,不知道该怎么做。我的应用程序仅在我关闭应用程序或返回到其他活动时编辑共享首选项。我想在活动开始时编辑它们,而不执行任何函数ie checkpreferences();。确切地说,如何在活动开始时编辑共享首选项 public class MyActivity extends Activity { private SharedPreferences app_preferences; @Override public v

我正在制作一个活动,它将在活动开始执行任何功能之前编辑共享首选项。我被困住了,不知道该怎么做。我的应用程序仅在我关闭应用程序或返回到其他活动时编辑共享首选项。我想在活动开始时编辑它们,而不执行任何函数ie checkpreferences();。确切地说,如何在活动开始时编辑共享首选项

public class MyActivity extends Activity {

private SharedPreferences app_preferences;

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  // Get the app's shared preferences
  app_preferences = PreferenceManager.getDefaultSharedPreferences(this);

  final int id = 42;

  int idd = app_preferences.getInt("idd", 0);
  // I am Stuck in this part
  SharedPreferences.Editor editor = app_preferences.edit();  
    editor.putInt("idd", 43);
    editor.commit(); // Very important

  final int iddd = idd;
  checkpreferences(id, iddd);

        }

private void checkpreferences(int di, int dii) {
      if(di == dii) {
        Toast.makeText(AudioActivity.this,"id is same"+dii+"="+di , Toast.LENGTH_SHORT).show();
      }else{

            Toast.makeText(AudioActivity.this,"id is different"+dii+"!="+di, Toast.LENGTH_SHORT).show();

      }

}

 }
我认为错误就在这里 您正在尝试在保存共享首选项之前先对其进行筛选

// Fetching of value

    int idd = app_preferences.getInt("idd", 0);

Log.e("value " , " is "  + idd);
as at this time there shall be no value in  preference 

    // and commitng after it 



      SharedPreferences.Editor editor = app_preferences.edit();  
        editor.putInt("idd", 43);
        editor.commit(); // Very important
您应该在获取之前保存首选项 为了确保它也能打印日志