SharedPrefenrences不存储布尔值

时间:2017-11-13 12:03:32

标签: java android sharedpreferences android-sharedpreferences

尝试在sharedPreferences中保存boolean FAVORITE数据。当手机旋转或关闭时。它不工作它采取默认值。我不知道这段代码有什么问题。我无法弄清楚问题是什么,有人可以告诉我代码的问题

//Context context =this;

 String FAVOURITE = "selected";

boolean favourite = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState!=null){
        favourite = savedInstanceState.getBoolean(FAVOURITE,false);
        Toast.makeText(this,""+favourite,Toast.LENGTH_SHORT).show();

    }

    final Bundle queryBundle = new Bundle();

    movieObject=(CardsClass)getIntent().getSerializableExtra("movieObject");

    setTitle(movieObject.getmTitle());

    setContentView(R.layout.activity_details);

    final ImageView fav = (ImageView)findViewById(R.id.fav);

    fav.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (favourite == false) {

                favourite = true;

                fav.setImageResource(R.drawable.fav_on);

                Toast.makeText(DetailsActivity.this, favourite + " is added to favourites", Toast.LENGTH_SHORT).show();

                queryBundle.putBoolean(FAVOURITE,favourite);

            }

            else if(favourite){

                favourite=false;

                fav.setImageResource(R.drawable.fav_off);

                queryBundle.putBoolean(FAVOURITE,favourite);

                Toast.makeText(DetailsActivity.this, movieObject.getmTitle() + " is removed from favourites", Toast.LENGTH_SHORT).show();


            }
        }
    });

2 个答案:

答案 0 :(得分:1)

实际上,你做错了事。你应该做点什么:

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean(FAVOURITE, favorite); // then you can check the favorite value in onCreate as well.
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    this.favorite = savedInstanceState.getBoolean(FAVOURITE);
    // do something here when restore.
    super.onRestoreInstanceState(savedInstanceState);
}

答案 1 :(得分:1)

SharedPreferences

中撰写或阅读

写:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(FAVORITE, favorite);
editor.commit();

读:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Boolean favorite = sharedPref.getBoolean(FAVORITE, true);