1

我正在制作一个活动,该活动将在活动开始之前在执行任何功能之前编辑共享首选项。我被卡住了,不知道该怎么做。我的应用程序仅在我关闭应用程序或返回另一个活动时编辑共享首选项。我想在活动开始时编辑它们而不执行任何功能,即checkpreferences(); .Precisely 如何在活动开始时编辑共享偏好?

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();

      }

}

 }
4

1 回答 1

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

您应该在获取之前保存首选项并确保它也打印日志

于 2012-07-05T06:16:35.297 回答