简体   繁体   中英

I want to display Toast message on Retrofit failure in ViewModel Class

Hi I have this App where it displays movies from TMDB I am having an issue where I can't display a feedback to users that may lead them to keep unnecessarily waiting When my app starts without internet or server returns no data

 public MainViewModel(@NonNull Application application) {
        super(application);
        AppDatabase appDatabase = AppDatabase.getInstance(this.getApplication());
        favoriteMovies = appDatabase.favoriteDao().loadAllFavorites();
        Call<ApiResults> call = Network.buildAPICall(Network.POPULAR);
        call.enqueue(new Callback<ApiResults>() {

            @Override
            public void onResponse(Call<ApiResults> call, Response<ApiResults> response) {

                if (response.message().contentEquals("OK")) {
                    popularMovies.setValue(response.body().getMovies());
                } else {

                    Log.e(TAG, "Something unexpected happened to our request: " + response.message());
                }
            }

            @Override
            public void onFailure(Call<ApiResults> call, Throwable t) {
                Log.i(TAG, "Something unexpected happened to our request: " );
                Log.e(TAG, t.getMessage());

            }
        });

I want to display the message "Something unexpected happened to our request: " when there is no internet access to the mainActivity the problem is I can't display a toaster in the view model class Here is my main Activity code snippet

public void setupViewModel() {

        com.example.popularmovies.UI.MainViewModel viewModel = ViewModelProviders.of(this).get(com.example.popularmovies.UI.MainViewModel.class);

        Log.i("Test",""+ viewModel);

        viewModel.getFavoriteMovies().observe(this, new Observer<List<MovieData>>() {
            @Override
            public void onChanged(@Nullable List<com.example.popularmovies.Data.MovieData> favoriteEntries) {
                Log.d(TAG, "Receiving changes from LiveData");

                if (mSortOrder.contentEquals(FAVORITE)) {
                    List<com.example.popularmovies.Data.MovieData> movieList = new ArrayList<com.example.popularmovies.Data.MovieData>();

                    if (favoriteEntries != null) {
                        for (com.example.popularmovies.Data.MovieData fave : favoriteEntries) {
                            fave.setFavorite(1);
                        }
                        setAdapter(favoriteEntries);
                    }
                }
            }
        });

        viewModel.getTopRatedMovies().observe(this, new Observer<List<com.example.popularmovies.Data.MovieData>>() {
            @Override
            public void onChanged(@Nullable List<com.example.popularmovies.Data.MovieData> movieData) {
                Log.i("Test",""+ movieData);

                if (movieData != null && mSortOrder.contentEquals(com.example.popularmovies.Utils.Network.TOP_RATED)) {
                    setAdapter(movieData);
                }
            }
        });

        viewModel.getPopularMovies().observe(this, new Observer<List<com.example.popularmovies.Data.MovieData>>() {

            @Override
            public void onChanged(@Nullable List<com.example.popularmovies.Data.MovieData> movieData) {
                Log.i("Test",""+ movieData);
                if (movieData != null && mSortOrder.contentEquals(com.example.popularmovies.Utils.Network.POPULAR)) {
                    setAdapter(movieData);
                }
            }
        });
    }

Any suggestions how to do that?

Use LiveData, An Observable data holder class, also and Lifecycle aware in your case Activity Lifecycle.

Declare Variable

private MutableLiveData<String> toastMessageObserver = new MutableLiveData();

Set Value

toastMessageObserver.setValue("Something unexpected happened to our request: "+response.message()); // Whenever you want to show toast use setValue.

Getter Method

Define getter method in viewModel

public LiveData<String> getToastObserver(){
    return toastMessageObserver;
}

In activity inside setupViewModel

viewModel.getToastObserver().observe(this, message -> {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).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