Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing resources in fragment background task returns illegalStateException often

I am making an asynchronous network request to fetch reviews and trailers.

If the reviews and trailers are present then they are set as TextView texts. If there are no reviews present then I am setting the textview test as "No reviews"(message_no_reviews) which is a predefined string variable in strings.xml file.

Now in order to display that text when no reviews are available I am fetching that using

getResources().getString(R.string.message_no_reviews)

The problem is that call to getResources().getString(R.string.message_no_reviews) returns java.lang.IllegalStateException: Fragment MovieDetailFragment{1fdfd76} not attached to Activity many times whereas call to getResources().getString(R.string.api_key) does not cause any Exception.

Following is the code snippet.

public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getReviews();
        getTrailers();
    } 

public void getReviews(){


    Call<JsonObject> getReviewsCall = apiService.getReview(movie.getId(),getResources().getString(R.string.api_key));


    getReviewsCall.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Response<JsonObject> response, Retrofit retrofit) {

            if (response.body() != null) {

                JsonArray reviews=(JsonArray) response.body().get("results");
                System.out.println(reviews);
                if(reviews.size()>0) {
                    tvReviewText.setText(((JsonObject) reviews.get(0)).get("content").getAsString());
                    tvReviewAuthor.setText(((JsonObject) reviews.get(0)).get("author").getAsString());

                }
                else{

                    tvReviewAuthor.setText(getResources().getString(R.string.message_no_reviews));
                    tvReviewText.setText("");
                }

            }

        }

        @Override
        public void onFailure(Throwable t) {

        }

    });


}

Any thoughts on why this might be happening?

below is the logcat

 FATAL EXCEPTION: main
 Process: com.vipin.www.popularmovies, PID: 21580
 java.lang.IllegalStateException: Fragment MovieDetailFragment{1fdfd76} not attached to Activity
     at android.support.v4.app.Fragment.getResources(Fragment.java:636)
     at com.vipin.www.popularmovies.MovieDetailFragment$2.onResponse(MovieDetailFragment.java:168)
     at retrofit.ExecutorCallAdapterFactory$ExecutorCallback$1.run(ExecutorCallAdapterFactory.java:86)
     at android.os.Handler.handleCallback(Handler.java:739)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:135)
     at android.app.ActivityThread.main(ActivityThread.java:5221)
     at java.lang.reflect.Method.invoke(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:372)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
like image 370
vipin agrahari Avatar asked Apr 20 '16 13:04

vipin agrahari


2 Answers

Your fragment is not attached to activity means:your fragment is not visible to user at that time since you made a network call from a button it create a another background thread and then you either backStack fragment or remove it from activity . So when response comes to onResponse method its context not available.

So You should use:

Fragment.this.getResources().getString(R.string.message_no_reviews)); 

or create a boolean whether fragment is attached or not in onCreate() and onDestroy()

like image 86
Yogeshwar Sharma Avatar answered Oct 02 '22 13:10

Yogeshwar Sharma


tvReviewAuthor.setText(getActivity().getResources().getString(R.string.message_no_reviews)); This should do the work You need Context Object to access String Resources

like image 40
pratham kesarkar Avatar answered Oct 02 '22 12:10

pratham kesarkar