java.lang.IllegalStateException Fragment 未附加到 Activity

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36246270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:07:57  来源:igfitidea点击:

java.lang.IllegalStateException Fragment not attached to Activity

javaandroidandroid-fragments

提问by BVtp

After I receive a response with Volley, I have to get back to the main fragment. I have two different volley requests , depending on some condition, I'll call it 'a' in this example. The weird thing is the when a==1, popBackStack gets me successfullyto the main fragment . When a==0 it crashesand I receive java.lang.IllegalStateException Fragment not attached to ActivityI tried creating a new main fragment (transaction.commit....) but it didn't help.

在收到 Volley 的回复后,我必须回到主要片段。我有两个不同的截击请求,根据某些条件,在本例中我将其称为“a”。奇怪的是,当a==1 时,popBackStack 将我成功带到主片段。 当 a==0 它崩溃并且我收到 java.lang.IllegalStateException Fragment not attached to Activity我尝试创建一个新的主要片段(transaction.commit ....)但它没有帮助。

if( a == 0 )
{
    VolleyManager.add(jsnObj,
        new RequestListener() {

                    @Override
                    public <T> void onSuccess(T object) {
                        mFragmentManager.popBackStack(DataManager.BACK_STACK_KEY_MAIN_FRAGMENT, 0);
                    }
                    });
                }
else if( a==1 )
{
    VolleyManager.update(jsnObj,
        new RequestListener() {

                @Override
                public <T> void onSuccess(T object) {
                        mFragmentManager.popBackStack(DataManager.BACK_STACK_KEY_MAIN_FRAGMENT, 0);
                }   
                });
    }

Error -

错误 -

  java.lang.IllegalStateException: Fragment MainFragment{6aaaf7f} not attached to Activity
  at android.app.Fragment.getResources(Fragment.java

The problem seems to be with the getResources(), but I do the same thing when a==1 and I've got no problems at all.

问题似乎出在getResources(),但是当 a==1 时我做同样的事情并且我完全没有问题。

回答by Rohit Arya

It seems like that by the time AsyncTaskfinishes and calls onPostExecute, the MainFragmenthas been detached from its activity. So either the activityhas already been destroyed or fragmentwas never attached.

似乎到了AsyncTask完成和调用的时候onPostExecuteMainFragment已经从它的activity. 所以要么activity已经被销毁,要么fragment从未附加过。

So if fragment is notattached to the activity, it can't access resources because that requires contextand fragment doesn't have but activitydoes.

因此,如果片段附加到activity,则它无法访问资源,因为这需要context而片段没有但activity有。

So you should check if activityis nullor not before calling getResources.

所以你应该在调用之前检查是否activity是。nullgetResources

Update the code like this:

像这样更新代码:

if(getActivity()!=null){
    String streetFormat = getActivity().getResources().getString( R.string.address_name_string );
    ....
}

回答by MohammadReza

You have to cancel your requests on

您必须取消您的请求

onDestroyView()

onDestroyView()

method of the fragment or check if the fragment is already alive and added to host activity or not I'd go with something like this:

片段的方法或检查片段是否已经存在并添加到主机活动中我会使用这样的方法:

onDestroyView(){ Volley.cancelAllRequests() }

or

或者

onResponse(){ if(getActivity() != null && isAdded(){ // here handle the response and update views, otherwise just cache the response!}}

回答by Vucko

getResources()must be called from something that has Context, like the activity. The fragment itself does not have the Contextsince it does not implement it. If you're using getResources()in a fragment, you can try this:

getResources()必须从具有 的东西中调用Context,例如活动。片段本身没有 ,Context因为它没有实现它。如果你getResources()在片段中使用,你可以试试这个:

String streetFormat = getActivity().getResources().getString( R.string.address_name_string );