房间查询在首次点击时返回null

时间:2018-07-16 16:14:40

标签: android sqlite android-room android-architecture-components

即使我知道对象存在,我的查询也会从数据库返回null时出现问题。我在这里已经阅读了几种解决方案并尝试了它,但是它没有用。所以这就是我想要做的,我有一个按钮,如果用户按下它,则在将数据库添加为收藏的电影之前,它会检查数据库;当用户再次点击该按钮时,它会检查该电影是否已存在于数据库中,如果是,则将其从数据库中删除。请这是我的代码...

//this is from my detail class to display the details of the movie selected
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.detail_activity);
            playTrailer = findViewById(R.id.playTrailer);
            playTrailer.setImageResource(R.drawable.play_icon);
            starButton = findViewById(R.id.floatingActionButton);
            movieViewModel = ViewModelProviders.of(this).get(MovieViewModel.class);
            populateUI();
        }


//here I receive an intent from the main activity then display all the movie information on the detail ACTIVITY. populates the UI
        public void  populateUI(){
            imageView = findViewById(R.id.imageView3);
            movieTitle = findViewById(R.id.textView2);
            moviePlot = findViewById(R.id.moviePlot2);
            ratings = findViewById(R.id.ratings);
            releaseDate = findViewById(R.id.releaseDate2);
            rateStar = findViewById(R.id.ratingBar);
            contentReview = findViewById(R.id.reviewContent);
            final Movie movieData =  getIntent().getParcelableExtra("MOVIE_DATA");
            movieID = movieData.getMovieId();
            setTitle(movieData.getMovieTitle());
            movieTitle.setText(movieData.getMovieTitle());
            moviePlot.setText(movieData.getMoviePlot());
            ratings.setText(movieData.getMovieRating());
            releaseDate.setText(movieData.getReleaseDate());
            rateStar.setRating(Float.parseFloat(movieData.getMovieRating()));
            if(movieData.getBackDrop().isEmpty() || movieData.getBackDrop().equals("null")){
                imageUrl.append("original/").append(movieData.getMovieImage());
                Picasso.with(getApplicationContext()).
                        load(imageUrl.toString())
                        .error(R.drawable.image1)
                        .placeholder(R.drawable.image1)
                        .into(imageView);
                return;
            }
            imageUrl.append("original/").append(movieData.getBackDrop());

            Picasso.with(getApplicationContext()).load(imageUrl.toString()).into(imageView);

            TrailerAsyncTask asyncTask1 = new TrailerAsyncTask();
            ReviewAsyncTask asyncTask2  = new ReviewAsyncTask();


            asyncTask1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,trailerUrl);
            asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, reviewsUrl);
            playTrailer = findViewById(R.id.playTrailer);
            trailerTextView = findViewById(R.id.playTrailer2);
            Log.v("change","the movie id before the click is: "+movieID);

            starButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Movie temp2 = movieViewModel.getMovieID(movieID);
                    if(temp2 == null){
                        Log.v("change", " movie is null");
                        movieViewModel.insert(movieData);
                    } else if (temp2.getMovieId().equals(movieData.getMovieId())){
                        Log.v("change", ": "+movieData.getMovieTitle()+ " was deleted from database");
                        movieViewModel.delete(movieID);
                    }

                }
            });
        } 


   // here is my movie repository which provided data to the view model which will then send data to the detail activity UI

    public class MovieRepository {
        private MovieDao mMovieDao;
        private LiveData<List<Movie>> mAllMovies;
        private static Movie temp;

        public MovieRepository(Application application){
            MovieRoomDatabase db = MovieRoomDatabase.getDatabase(application);
            mMovieDao = db.movieDao();
            mAllMovies = mMovieDao.getAllMovie();
            Log.v("change", "database constructor called");
        }

        public Movie getMovie(String movie){
            new getMovieIDAsyncTask(mMovieDao).execute(movie);
            return temp;
        }

        public LiveData<List<Movie>> getmAllMovies(){
            return mAllMovies;
        }


        public void insert(Movie movie){
            new insertMovieAsyncTask(mMovieDao).execute(movie);
        }

        public void delete(String movie){
            new deleteMovieAsyncTask(mMovieDao).execute(movie);
        }
        public static class getMovieIDAsyncTask extends AsyncTask<String,Void, Movie>{

            private MovieDao mMovieIDAsyncTask;

            getMovieIDAsyncTask(MovieDao dao){
                mMovieIDAsyncTask = dao;
            }
            @Override
            protected Movie doInBackground(String... movies) {
                temp = mMovieIDAsyncTask.getMovie(movies[0]);
                return temp;
            }
        }
        public static class insertMovieAsyncTask extends AsyncTask<Movie,Void,Void>{
            private MovieDao mMovieAsyncTaskDao;

            insertMovieAsyncTask(MovieDao dao){
                mMovieAsyncTaskDao = dao;
            }
            @Override
            protected Void doInBackground(final Movie... movies) {
               mMovieAsyncTaskDao.insert(movies[0]);
                return null;
            }
        }

        public static class deleteMovieAsyncTask extends  AsyncTask<String,Void,Void>{
            private MovieDao mMovieAsyncTaskDao;
            deleteMovieAsyncTask(MovieDao dao){
                mMovieAsyncTaskDao = dao;
            }
            @Override
            protected Void doInBackground(String... movies) {
                mMovieAsyncTaskDao.deleteMovie(movies[0]);
                return null;
            }
        }


    }

    // here is my Doa

    @Dao
    public interface MovieDao {
        @Insert(onConflict = OnConflictStrategy.REPLACE)
        void insert(Movie movie);

        @Delete
        void delete(Movie movie);

        @Query("SELECT * from movie_database ORDER BY title ASC")
       LiveData<List<Movie>> getAllMovie();

        @Query("SELECT * FROM MOVIE_DATABASE WHERE movieID = :movieID")
        Movie getMovie(String movieID);

        @Query("DELETE FROM MOVIE_DATABASE WHERE movieID = :movieID")
        void deleteMovie(String movieID);

    }

    //here is my view model
    public class MovieViewModel extends AndroidViewModel{
        private MovieRepository movieRepository;
        private MovieRepositoryNetwork movieRepositoryNetwork;
        private LiveData<List<Movie>> mAllMovies;
        private LiveData<List<Movie>> dataFromNetwork;

        public MovieViewModel(@NonNull Application application) {
            super(application);
    //        Log.v("change"," view model constructor is called");
            movieRepository = new MovieRepository(application);
             movieRepositoryNetwork = new MovieRepositoryNetwork();
        }



        public LiveData<List<Movie>> getFavoritesFromDatabase(){
    //        Log.v("change","favorite movies is called from view model");
            dataFromNetwork = movieRepository.getmAllMovies();
            return  dataFromNetwork;
        }

        public void getPopularMovies(){
    //        Log.v("change","popular movies is called from view model");
            dataFromNetwork = movieRepositoryNetwork.getPopularMoviesFromNetwork();
        }

        public void getHighRatedMovies(){
    //        Log.v("change","hih rated movies is called from view model");
            dataFromNetwork = movieRepositoryNetwork.getHighRatedFromNetwork();
        }

        public LiveData<List<Movie>> getDataFromNetwork(){
            return dataFromNetwork;
        }

        public void insert(Movie movie){
            movieRepository.insert(movie);
        }

        public void delete(String movie){
            movieRepository.delete(movie);
        }
        public Movie getMovieID(String movieID){
            return movieRepository.getMovie(movieID);
        }
    }
    // here's also a link to my GitHub page https://github.com/Ben-Rapha/android-movie-app-project

0 个答案:

没有答案