我正在做一个活动,它将在活动执行任何功能之前就开始编辑共享的首选项。我被困住了,不知道该怎么办。我的应用程序仅在我关闭该应用程序或返回其他活动时才编辑共享首选项。我想在活动开始时编辑它们而不执行任何功能,即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

您应该在获取之前保存偏好设置
并确保它也打印日志

关于android - 关闭应用或 Activity 之前,共享的首选项不会保存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11338658/

10-11 22:52
查看更多