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

时间:2012-07-05 06:11:12

标签: android sharedpreferences

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

      }

}

 }

1 个答案:

答案 0 :(得分:2)

我认为错误就在这里 在保存之前,你试着获取共享偏好的价值

// 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

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