简体   繁体   中英

Checkbox and sharedPreferences

I am using a grid view for a movie app. When the user clicks on a movie, details of the movie are revealed. Inside this new activity, the user can mark the movie as favorite. I'm using sharedPreferences to store the state of the checkbox when checked or unchecked. The problem is that, when i go back to the grid view to choose another movie to mark it as favorite, all the movies in the grid view show marked as favorite even though i did not explicitly check these movies. Please, what could be responsible for this behavior? Below is my detail activity code:

public class MovieDetails extends AppCompatActivity {

    private static final String SHARED_PF_NAME = "movieSP";
    private static final String CHECK_BOX_STATE = "check_state";
    private SharedPreferences sharedPreferences;
    CheckBox checkBox;



    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_details);
        getSupportActionBar().setTitle("Movie Details");

        /*//get values passed from main
        movie = getIntent().getParcelableExtra(MainActivity.MOVIE_IN_CURRENT_CLICKED_POSITION);

        // get movie id of the movie that was just passed
        final int movieIdOfMovieInCurrentlyClicked= movie.getMovieid();

        //get path for trailer and reviews
        String movieVideoPath = "https://api.themoviedb.org/3/movie/" + movieIdOfMovieInCurrentlyClicked+ "/videos?api_key=" + MovieDataSource.API_KEY;
        String movieReviewPath = "https://api.themoviedb.org/3/movie/" + movieIdOfMovieInCurrentlyClicked + "/reviews?api_key=" + MovieDataSource.API_KEY;
        // initiate asynctask
        new MovieTrailerAsyncTask().execute(movieVideoPath);
        new MovieReviewAsyncTask().execute(movieReviewPath);

        // trailer recycler
        trailerRecyclerview = findViewById(R.id.trailers_RecyclerView);
        trailerRecyclerview.setHasFixedSize(true);
        trailerRecyclerview.setLayoutManager(trailerLinearLayoutManager);
        movieTrailerRecyclerViewAdapter = new MovieTrailerRecyclerViewAdapter(MovieDetails.this, movieTrailerArrayList);
        trailerRecyclerview.setAdapter(movieTrailerRecyclerViewAdapter);



        //reviews recycler
        reviewRecyclerView = findViewById(R.id.reviews_recyclerview);
        trailerRecyclerview.setHasFixedSize(true);
        reviewRecyclerView.setLayoutManager(reviewLinearLayoutManager);
        movieReviewRecyclerViewAdapter = new MovieReviewRecyclerViewAdapter(MovieDetails.this, movieReviewsArrayList);
        reviewRecyclerView.setAdapter(movieReviewRecyclerViewAdapter);







        TextView movieTitleTextView = findViewById(R.id.movieTitle);
        ImageView movieImageView = findViewById(R.id.movieImage);
        TextView movieReleaseDateView = findViewById(R.id.movieReleaseDate);
        TextView movieRatingView = findViewById(R.id.movieRating);
        TextView movieDescriptionView = findViewById(R.id.movieDescription);





        Picasso.with(this)
                .load(movie.getMovieImagePath())
                .fit()
                .placeholder(R.drawable.progress_file)
                .error(R.drawable.ic_launcher_background)
                .into(movieImageView);

        movieTitleTextView.setText(movie.getMovieTitle());
        movieReleaseDateView.setText(movie.getMovieReleaseDate());
        movieRatingView.setText(String.format("%s%s", String.valueOf(movie.getMovieRating()), ratingDenominator));
        movieDescriptionView.setText(movie.getMovieDescripton());
*/
        checkBox= findViewById(R.id.checkbox_button);
        sharedPreferences = getSharedPreferences(SHARED_PF_NAME, Context.MODE_PRIVATE);



            checkBox.setChecked(sharedPreferences.getBoolean(CHECK_BOX_STATE, false));



            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {


            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sharedPreferences.edit().putBoolean(CHECK_BOX_STATE, isChecked).apply();

                if (isChecked){

                    Toast.makeText(getApplicationContext(), "checked",
                            Toast.LENGTH_LONG).show();

                }else {
                    Toast.makeText(getApplicationContext(), "not checked",
                            Toast.LENGTH_LONG).show();
                }




            }
        });




    }

Grid view Adapter:

    public class MovieDisplayAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<Movie> movies;

    MovieDisplayAdapter(Context context,ArrayList<Movie> movies) {
        this.context = context;
        this.movies = movies;
    }


    @Override
    public int getCount() {

        Log.i("count",String.valueOf(movies.size()));
        return movies.size();
    }

    @Override
    public Object getItem(int position) {
        return movies.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    class ViewHolder {
        ImageView imageView;

        ViewHolder(View view) {
            imageView = view.findViewById(R.id.imageView);
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {




        ViewHolder holder;
        LayoutInflater inflater = LayoutInflater.from(context);

        if (convertView == null) {

            convertView = inflater.inflate(R.layout.single_row, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);

        } else

        {
            holder = (ViewHolder) convertView.getTag();
        }

        Picasso.with(context)
                .load(movies.get(position).getMovieImagePath())
                .placeholder(R.drawable.progress_file)
                .fit()
                .error(R.drawable.ic_launcher_background)
                .centerCrop()
                .into(holder.imageView); // View where image is loaded.


        return convertView;
    }


}

MainActivity(intent code):

gridView.setAdapter(new MovieDisplayAdapter(MainActivity.this, movies));
                    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            movieIdOfMovieInCurrentlyClicked = movies.get(position).getMovieid();
                            moviePosition = position;
                            Intent intent = new Intent(MainActivity.this, MovieDetails.class);
                            //When clicked, the position of the current movie
                            Movie movieIncurrentClickedPosition = movies.get(moviePosition);
                            intent.putExtra(MOVIE_IN_CURRENT_CLICKED_POSITION, movieIncurrentClickedPosition);

                            startActivity(intent);

                        }
                    });
                }

You are using a single variable ( CHECK_BOX_STATE ) to store the favorite status of all the movies, rather than storing the favorite status for each movie. You need to create a different boolean entry in the SharedPreferences for each favourite movie, and then remove it when the movie is no longer favourite.

public class MovieDetails extends AppCompatActivity {
    private static final String SHARED_PF_NAME = "favoriteMovies";
    private Movie movie; // I'm guessing the class name is Movie
    private CheckBox checkBox;
    private SharedPreferences sharedPreferences;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_details);
        getSupportActionBar().setTitle("Movie Details");

        movie = getIntent().getParcelableExtra(
            MainActivity.MOVIE_IN_CURRENT_CLICKED_POSITION);
        final String key = Integer.toString(movie.getMovieId());

        // all the other stuff...

        sharedPreferences = getSharedPreferences(SHARED_PF_NAME, Context.MODE_PRIVATE);
        checkBox = findViewById(R.id.checkbox_button);
        checkBox.setChecked(sharedPreferences.getBoolean(key, false));
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    sharedPreferences.edit().putBoolean(key, true).apply();
                    Toast.makeText(getApplicationContext(), "checked",
                            Toast.LENGTH_LONG).show();
                } else {
                    sharedPreferences.edit().remove(key).apply();
                    Toast.makeText(getApplicationContext(), "not checked",
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}

这里的事情是您要保存一个检查状态,因此当您尝试检索该检查状态只是一个检查状态时,您必须通过每个电影的标识符来过滤每个检查状态...因为附加注释更好将该信息存储在本地数据库的电影对象中,因此您只需执行简单的查询即可更新和检索该状态

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM