java.lang.IllegalStateException: Fragment not attached to Activity

前端 未结 12 1210
名媛妹妹
名媛妹妹 2020-11-28 02:28

I am rarely getting this error while making an API call.

java.lang.IllegalStateException: Fragment  not attached to Activity

I tried puttin

12条回答
  •  不知归路
    2020-11-28 02:47

    I adopted the following approach for handling this issue. Created a new class which act as a wrapper for activity methods like this

    public class ContextWrapper {
        public static String getString(Activity activity, int resourceId, String defaultValue) {
            if (activity != null) {
                return activity.getString(resourceId);
            } else {
                return defaultValue;
            }
        }
    
        //similar methods like getDrawable(), getResources() etc
    
    }
    

    Now wherever I need to access resources from fragments or activities, instead of directly calling the method, I use this class. In case the activity context is not null it returns the value of the asset and in case the context is null, it passes a default value (which is also specified by the caller of the function).

    Important This is not a solution, this is an effective way where you can handle this crash gracefully. You would want to add some logs in cases where you are getting activity instance as null and try to fix that, if possible.

提交回复
热议问题