【问题标题】:Best way to Handle FragmentTransaction in AsyncTask.onPostExecute after onDestroy is called调用 onDestroy 后在 AsyncTask.onPostExecute 中处理 FragmentTransaction 的最佳方法
【发布时间】:2014-01-11 15:43:18
【问题描述】:

在我的应用程序中,我总是需要在应用程序第一次打开时执行一些东西。当用户打开它时,应用程序会显示一个带有进度条的对话框,同时在后台执行AsyncTask,之后(在onPostExecute())我需要提交Fragment

所以,在我的 Main ActivityonCreate() 方法中,我有:

public class InitialActivity extends SherlockFragmentActivity{

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_initial);
        if(savedInstanceState == null) //Executes just at the firstTime
        {
            //ApplicationStarter -> It manages all execution to start my app, executes asynctask, shows dialogs..
            ApplicationStarter starter = new ApplicationStarter(this) {

                @Override
                public void afterFinish() {
                    //It Executes at onPostExecute when doInBackground() finishes
                    ItensFragment itensfrag = new ItensFragment();
                    frag.setTargetFragment(itensfrag , 0);
                    android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager()
                            .beginTransaction();
                    ft.replace(R.id.simple_fragment, itensfrag);
                    ft.commitAllowingStateLoss();   

                }
            };
            starter.start();
        }
    }
}

所以,一切正常,但如果用户旋转设备或在调用 onDestroy() 方法后应用程序崩溃。启动以下异常:

java.lang.IllegalStateException: Activity has been destroyed  

ft.commitAllowingStateLoss();

我四处搜索,发现on this post 像我尝试做的那样在异步回调方法中执行Fragment 转换不是一个好习惯。 And i saw this answer,也许我可以适应我的情况。但在此之前,我想知道是否有人对我正在尝试做的事情有更好的方法或建议。
提前致谢。

【问题讨论】:

  • 当方向改变你的活动被销毁并重新创建时发生。 Asynctask 顾名思义就是异步的
  • 如果有帮助,您可以查看此博客。 androiddesignpatterns.com/2013/04/…

标签: java android android-fragments android-asynctask android-activity


【解决方案1】:

@Raghunandan 如何建议,我关注了this post,一切正常。最大的不同是,现在我在我的 Fragment 的 onCreate 上调用我的 ApplicationStarter,它设置为 setRetainInstance(true)。 InitialActivity 有一个ItensFragment 的实例。我InitialActivityonCreate()中的代码是:

public class InitialActivity extends SherlockFragmentActivity {
private ItensFragment itensfrag;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_inicial);
    FragmentManager fm = getSupportFragmentManager();
    itensfrag= (ItensFragment) fm.findFragmentByTag("itensfrag");
    if (savedInstanceState == null) {
        if (itensfrag== null) {
            itensfrag= new ItensFragment();
          fm.beginTransaction().replace(R.id.simple_fragment, itensfrag, "itensfrag").commit();
        }
    }
}
}       

【讨论】:

    猜你喜欢
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多