1

I have Activity called FilmActivity.java in this class there is an inner class called OpenDbConnection extends AsyncTask in OpenDbConnection i open connection to Database

 public AppDatabase db = Room.databaseBuilder(getApplicationContext(),
            AppDatabase.class, "FilmDatabase").fallbackToDestructiveMigration().build();

And in FilmActivity.java there is A method called setFavButton

public void setFavButton(View view) {
    String pos = getStringFromIntent("position");
    Toast.makeText(this, pos, Toast.LENGTH_SHORT).show();
    ImageView favButton = findViewById(R.id.activity_film_fav_button);
    if (isPressedButton) {
        favButton.setImageResource(R.drawable.ic_like);
        isPressedButton = false;
        Toast.makeText(this, "Removed From Favourite Film", Toast.LENGTH_SHORT).show();
    } else {
        favButton.setImageResource(R.drawable.ic_like_activated);
        isPressedButton = true;
        Toast.makeText(this, "Added To Favourite Film", Toast.LENGTH_SHORT).show();
    }
    filmList.get(Integer.valueOf(pos)).setFavFilm(String.valueOf(isPressedButton));
}

That Connected With Layout with onClick

 <ImageView
                android:id="@+id/activity_film_fav_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/ativity_film_text_header"
                android:onClick="setFavButton"
                android:paddingTop="4dp"
                android:src="@drawable/ic_like" />

I want when user Click on this image (when setFavButton is called ) he change the photo and he should update something in database i have the method in database that Update But , How Can I Called The DataBase Object which called db From inner class to FilmActivity class

I tried to Create Object From Inner class in setFavButton But the app crashed and it say that i can call the Database in main thread

The setFavButton Method Should be like that

public void setFavButton(View view) {
    String pos = getStringFromIntent("position");
    Toast.makeText(this, pos, Toast.LENGTH_SHORT).show();
    ImageView favButton = findViewById(R.id.activity_film_fav_button);
    if (isPressedButton) {
        favButton.setImageResource(R.drawable.ic_like);
        isPressedButton = false;
        Toast.makeText(this, "Removed From Favourite Film", Toast.LENGTH_SHORT).show();
    } else {
        favButton.setImageResource(R.drawable.ic_like_activated);
        isPressedButton = true;
        Toast.makeText(this, "Added To Favourite Film", Toast.LENGTH_SHORT).show();
    }
    filmList.get(Integer.valueOf(pos)).setFavFilm(String.valueOf(isPressedButton));
    // here should update the list in Database
    db.userDao().updateFilmList(filmList);
}

But it crashed !! because i can't use the database in main thread

What Should i do ???

luadham
  • 17
  • 4

0 Answers0