在使用保留的异步任务片段旋转屏幕后,片段的目标不在片段管理器中

时间:2014-09-07 12:23:54

标签: android android-fragments

我一直在关注Alex Lockwood(2013)的本教程,了解如何在配置更改后将线程报告回新的活动实例。

http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

所有工作都很好,直到我尝试在嵌套片段中执行此操作。基本上Activity添加片段A和片段A被片段B替换,片段B内部启动异步任务线程。

但是,如果我回到Fragment A(通过backstack)然后尝试旋转,我会得到标题中声明的以下异常。

这是代码

主要活动

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(savedInstanceState == null)
        {
             FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
             ft.add(android.R.id.content, new FragmentA()).commit();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

片段A

public class FragmentA extends Fragment implements OnClickListener
{

    private Button GoToFragmentB;
    private ViewGroup container;

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,  Bundle savedInstanceState)
    {
    // TODO Auto-generated method stub

    View view = inflater.inflate(R.layout.fragment_a, container, false);
    this.container = container;
    GoToFragmentB = (Button)view.findViewById(R.id.bGoToFragmentB);
    GoToFragmentB.setOnClickListener(this);
    return view;
    }

    @Override
    public void onClick(View v) 
    {
        // TODO Auto-generated method stub
        FragmentManager fragmentManager = getFragmentManager();
        FragmentB fb = new FragmentB();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(container.getId(), fb, FragmentB.class.getName());
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

}

片段B

public class FragmentB extends Fragment implements OnClickListener, ThreadFragment.AsyncTaskCallbacks{

    private ThreadFragment mThreadFragment;
    private ProgressBar progress_horizontal;
    private TextView percent_progress;
    private Button task_button;

    private static final String KEY_CURRENT_PROGRESS = "current_progress"; 
    private static final String KEY_PERCENT_PROGRESS = "percent_progress"; 


    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,  Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.fragment_b, container, false);

        progress_horizontal = (ProgressBar) view.findViewById(R.id.progress_horizontal);
        percent_progress = (TextView)view.findViewById(R.id.percent_progress);
        task_button = (Button)view.findViewById(R.id.task_button);
        task_button.setOnClickListener(this);



        return view;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) 
    {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        if(savedInstanceState != null)
        {
            progress_horizontal.setProgress(savedInstanceState.getInt(KEY_CURRENT_PROGRESS)); 
            percent_progress.setText(savedInstanceState.getString(KEY_PERCENT_PROGRESS)); 

        }

        FragmentManager fm = getActivity().getSupportFragmentManager();
        mThreadFragment = (ThreadFragment) fm.findFragmentByTag(ThreadFragment.class.getName());

        if(mThreadFragment == null)
        {
            mThreadFragment = new ThreadFragment();
            mThreadFragment.setTargetFragment(this, 0);
            fm.beginTransaction().add(mThreadFragment, ThreadFragment.class.getName()).commit();
        }

        if(mThreadFragment.isRunning() == true)
        {
            task_button.setText(getString(R.string.cancel));
        }
        else
        {
            task_button.setText(getString(R.string.start));
        }

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putInt(KEY_CURRENT_PROGRESS, progress_horizontal.getProgress()); 
        outState.putString(KEY_PERCENT_PROGRESS, percent_progress.getText().toString()); 

    }

    @Override
    public void onClick(View v) 
    {
        // TODO Auto-generated method stub
        if(mThreadFragment.isRunning() == true)
        {
            mThreadFragment.cancel();
        }
        else
        {
            mThreadFragment.start();
        }
    }


    @Override
    public void onPreExecute() 
    {
        // TODO Auto-generated method stub
        task_button.setText(getString(R.string.cancel));
        Toast.makeText(getActivity(), R.string.task_started_msg, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onProgressUpdate(int percent)
    {
        // TODO Auto-generated method stub
        progress_horizontal.setProgress(percent * progress_horizontal.getMax() / 100);
        percent_progress.setText(percent + "%");
    }


    @Override
    public void onCancelled() 
    {
        // TODO Auto-generated method stub
        task_button.setText("Start");
        progress_horizontal.setProgress(0);
        percent_progress.setText("0%");

    }


    @Override
    public void onPostExecute() 
    {
        // TODO Auto-generated method stub
        task_button.setText(getString(R.string.start));
        progress_horizontal.setProgress(progress_horizontal.getMax());
        percent_progress.setText(getString(R.string.one_hundred_percent));
        Toast.makeText(getActivity(), R.string.task_complete_msg, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        mThreadFragment.pause();
        super.onPause();
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        mThreadFragment.resume();
        super.onResume();
    }

}

线程片段

public class ThreadFragment extends Fragment {


    static interface AsyncTaskCallbacks
    {
        void onPreExecute();
        void onProgressUpdate(int percent);
        void onCancelled();
        void onPostExecute();
    }

    private AsyncTaskCallbacks mCallback;
    private boolean mRunning;
    private boolean isPause;

    private TestTask mTask;

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        if(!(getTargetFragment() instanceof AsyncTaskCallbacks))
        {
            throw new IllegalStateException("Target fragment must implement the AsyncTaskCallbacks interface.");
        }


        if(getTargetFragment() != null)
        {
        mCallback = (AsyncTaskCallbacks) getTargetFragment();
        }


    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        cancel();

    }

    public void start()
    {
        if(mRunning == false)
        {
            mTask = new TestTask();
            mTask.execute();
            mRunning = true;
        }
    }

    public void cancel()
    {
        if(mRunning == true)
        {
            mTask.cancel(false);
            mTask = null;
            mRunning = false;
            isPause = false;
        }
    }

    public void pause()
    {
        if(mRunning == true)
        {
            isPause = true;
        }
    }

    public void resume()
    {
        isPause = false;
    }

    public boolean isRunning()
    {
        return mRunning;
    }

    private class TestTask extends AsyncTask<Void, Integer, Void>
    {

        @Override
        protected void onPreExecute() 
        {
            // TODO Auto-generated method stub
            mCallback.onPreExecute();
            mRunning = true;
        }

        @Override
        protected Void doInBackground(Void... params) 
        {


                // TODO Auto-generated method stub
                for(int i = 0; !isCancelled() && i < 100; i++)
                {
                    if(isPause == true)
                    {
                        sleep();
                    }

                    SystemClock.sleep(100);
                    publishProgress(i);
                }



            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub
            mCallback.onProgressUpdate(values[0]);
        }

        @Override
        protected void onCancelled() {
            // TODO Auto-generated method stub
            mCallback.onCancelled();
            mRunning = false;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            mCallback.onPostExecute();
            mRunning = false;
        }

        private void sleep()
        {
            try
            {
                while(isPause)
                {
                Thread.sleep(500);
                }
            }
            catch(InterruptedException e)
            {
                e.printStackTrace();
            }
        }


    }



}

我的LogCat

09-06 19:49:31.068: E/AndroidRuntime(2402): FATAL EXCEPTION: main
09-06 19:49:31.068: E/AndroidRuntime(2402): java.lang.IllegalStateException: Failure saving state: ThreadFragment{40ce2700 #2 com.ersen.asynctaskpausetest.ThreadFragment} has target not in fragment manager: FragmentB{40d3a170}
09-06 19:49:31.068: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1699)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentActivity.onSaveInstanceState(FragmentActivity.java:547)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at android.app.Activity.performSaveInstanceState(Activity.java:1147)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1216)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3666)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at android.app.ActivityThread.access$700(ActivityThread.java:141)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1240)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at android.os.Looper.loop(Looper.java:137)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at java.lang.reflect.Method.invokeNative(Native Method)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at java.lang.reflect.Method.invoke(Method.java:511)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-06 19:49:31.068: E/AndroidRuntime(2402):     at dalvik.system.NativeStart.main(Native Method)

------------ 2014年9月8日编辑更新--------------------

我在破坏方法

上将其添加到我的片段B中
@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    mThreadFragment.setTargetFragment(null , -1);

}

我对片段B onActivityCreated进行了以下调整。请注意,如果fragmentManger.findFragmentByTag找到片段,则会调用else

if(mThreadFragment == null)
    {
        mThreadFragment = new ThreadFragment();
        mThreadFragment.setTargetFragment(this, 0);
        fm.beginTransaction().add(mThreadFragment, ThreadFragment.class.getName()).commit();
    }
    else
    {
        mThreadFragment.setTargetFragment(this, 0);
    }

我在线程片段

中对OnAttach进行了以下更改
if(getTargetFragment() != null)
{

    if((getTargetFragment().isVisible()) || getTargetFragment().isAdded())
    {
           mCallback = (AsyncTaskCallbacks) getTargetFragment();

    }
    else
    {
        mCallback = null;
    }
}

现在的区别是我不再得到上面提到的错误。我可以开始一项任务。 Destory片段b和旋转(配置更改)没有任何问题。但是,如果我回到片段b(自销毁后创建一个新实例),然后开始一个新任务。我收到这个新错误,说没有附加片段b。

09-08 14:07:28.495: E/AndroidRuntime(1650): java.lang.IllegalStateException: Fragment FragmentB{40cea860} not attached to Activity
09-08 14:07:28.495: E/AndroidRuntime(1650):     at android.support.v4.app.Fragment.getResources(Fragment.java:603)
09-08 14:07:28.495: E/AndroidRuntime(1650):     at android.support.v4.app.Fragment.getString(Fragment.java:625)
09-08 14:07:28.495: E/AndroidRuntime(1650):     at com.ersen.asynctaskpausetest.FragmentB.onPreExecute(FragmentB.java:119)
09-08 14:07:28.495: E/AndroidRuntime(1650):     at com.ersen.asynctaskpausetest.ThreadFragment$TestTask.onPreExecute(ThreadFragment.java:114)

它说片段b没有附加到活动上。这些是有问题的罪魁祸首。

@Override
public void onPreExecute() 
{
    // TODO Auto-generated method stub
    task_button.setText(getString(R.string.cancel));
    Toast.makeText(getActivity(), R.string.task_started_msg, Toast.LENGTH_SHORT).show();
}

因为访问字符串资源需要一个活动,但它很奇怪,因为如果我创建新的片段B不应该将它附加到活动吗?

最终更新:固定版本:使用Activity处理回调而不是片段B

以下是已更改的代码。

ThreadFragment:OnAttach

@Override
    public void onAttach(Activity activity)
    {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        if(!(activity instanceof AsyncTaskCallbacks))
        {
            throw new IllegalStateException("Target fragment must implement the AsyncTaskCallbacks interface.");
        }



        mCallback = (AsyncTaskCallbacks) activity;

    }

我删除了getTargetFragment并使用了活动引用

片段B

不再实现ThreadFragment.AsyncTaskCallbacks接口 删除了与setTargetFragment相关的所有代码。 ThreadFragment.AsyncTaskCallbacks实现的方法已保留,但不再被覆盖,因此活动可以调用这些方法来执行常规操作。

public void onPreExecute() 
    {
        // TODO Auto-generated method stub
        task_button.setText(getString(R.string.cancel));
        Toast.makeText(getActivity(), R.string.task_started_msg, Toast.LENGTH_SHORT).show();
    }



    public void onProgressUpdate(int percent)
    {
        // TODO Auto-generated method stub
        progress_horizontal.setProgress(percent * progress_horizontal.getMax() / 100);
        percent_progress.setText(percent + "%");
    }



    public void onCancelled() 
    {
        // TODO Auto-generated method stub
        task_button.setText("Start");
        progress_horizontal.setProgress(0);
        percent_progress.setText("0%");

    }



    public void onPostExecute() 
    {
        // TODO Auto-generated method stub
        task_button.setText(getString(R.string.start));
        progress_horizontal.setProgress(progress_horizontal.getMax());
        percent_progress.setText(getString(R.string.one_hundred_percent));
        Toast.makeText(getActivity(), R.string.task_complete_msg, Toast.LENGTH_SHORT).show();

主要活动

实现ThreadFragment.AsyncTaskCallbacks 添加了3个实例变量FragmentB,FragmentManger和一个布尔值。

public class MainActivity extends ActionBarActivity implements ThreadFragment.AsyncTaskCallbacks{

FragmentB FB;
FragmentManager fragmentManager;
boolean didFragmentBStartATask;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    fragmentManager = getSupportFragmentManager();

    if(savedInstanceState == null)
    {
         FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
         ft.add(android.R.id.content, new FragmentA()).commit();
    }
    else
    {
        didFragmentBStartATask = savedInstanceState.getBoolean("didFragmentBStartATask");
        if(didFragmentBStartATask)
        {
            FB = (FragmentB)fragmentManager.findFragmentByTag(FragmentB.class.getName());
        }

    }

}

在Create上将初始化片段管理器。 如果其恢复的实例获得布尔值,则检查片段b是否执行了任务。 如果为true,则按标记查找片段B.

在保存实例状态时,只需将布尔值放入包

@Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putBoolean("didFragmentBStartATask", didFragmentBStartATask);
    }

通过界面实现的方法

@Override
    public void onPreExecute() 
    {
        didFragmentBStartATask = true;
        if(FB == null)
        {
            FB = (FragmentB)fragmentManager.findFragmentByTag(FragmentB.class.getName());
        }

        FB.onPreExecute();

        // TODO Auto-generated method stub

    }

    @Override
    public void onProgressUpdate(int percent) {
        // TODO Auto-generated method stub
        FB.onProgressUpdate(percent);

    }

    @Override
    public void onCancelled() {
        // TODO Auto-generated method stub
        FB.onCancelled();

    }

    @Override
    public void onPostExecute() {
        // TODO Auto-generated method stub
        FB.onPostExecute();
        didFragmentBStartATask = false;

    }

在执行前,将布尔值设置为true 我们必须检查FB是否为null以防止空指针。如果为null,则找到片段(这需要首次启动)

之后只需使用FB实例调用方法就可以像以前那样调用它们。

在post post上将Boolean设置为false,因为它已完成

2 个答案:

答案 0 :(得分:3)

派对迟到了,但你应该考虑为你的“孩子”片段删除你对“setTargetFragment(this,0)”的调用。相反,当您想要从片段B创建“子片段”时,应该使用getChildFragmentManager()而不是getFragmentManager()。

然后在“子片段”中,您将使用getParentFragment()而不是getTargetFragment()来查找封闭片段。代码的两部分看起来像:

threadFragment = new ThreadFragment();
FragmentManager fm = getChildFragmentManager();
fm.beginTransaction().add(threadFragment, ThreadFragment.class.getName()).commit();

然后在你的ThreadFragment中,你将不再使用getTargetFragment()来查找你的片段B.相反,你将调用getParentFragment()。

if(!(getParentFragment() instanceof AsyncTaskCallbacks))
    {
        throw new IllegalStateException("Target fragment must implement the AsyncTaskCallbacks interface.");
    }

    if(getParentFragment() != null)
    {
    mCallback = (AsyncTaskCallbacks) getParentFragment();
    }

最后,在你的Fragment B中,你需要做一些修改才能找到你的ThreadFragment。您需要将其更改为使用ChildFragmentManager

FragmentManager fm = getChildFragmentManager();
mThreadFragment = (ThreadFragment) fm.findFragmentByTag(ThreadFragment.class.getName());

答案 1 :(得分:2)

来自setTargetFragment

的文档
  

public void setTargetFragment(Fragment fragment,int requestCode)此片段的可选目标。例如,如果这个片段是由另一个片段启动的话,这可能会被使用,并且当完成时想要将结果返回给第一个片段。

尝试这样做。

将其放入导致问题的片段中(在这种情况下可能在您的Fragment A中):

@Override
public void onSaveInstanceState(final Bundle outState) {
setTargetFragment(null, -1);
        ...
}

并记得在需要时将其设置为真正的目标片段。

修改

您可以尝试在Fragment B

中执行此操作
@Override
public void onSaveInstanceState(final Bundle outState) {
Fragment threadFrag = new ThreadFrag();
threadFrag.setTargetFragment(this , -1);
        ...
}