在 Android 2.2 中使用 Fragment 和 Activity 时应用程序崩溃
我正在开发一个应用程序,它从数据库加载大量数据,因此我使用 AsyncTasks 来完成同样的任务。
这是我正在创建的内容的总体视图。我有 2 个活动,即 ActivityA 和 AcitivityB。 ActivityB 有许多从数据库加载数据的片段。因此,我为加载数据的每个片段使用了不同的 AsyncTask。
现在我的问题是,当我在加载片段以返回 ActivityA 时按下设备的后退按钮时,应用程序崩溃,因为 ActivityB 不再可用。我该如何解决这个问题?
我正在使用 Android 2.2 的支持库。
I am developing an application which does lots of data loading from database so I am using AsyncTasks for the same.
Here is a overall view on what I am creating. I have 2 activities say ActivityA and AcitivityB. ActivityB have number of fragments which load data from database. So I have used different AsyncTask for each fragments which loads data.
Now my issue is that when I press back button of my device while the fragment is getting loaded to go back to ActivityA the application crashes, because ActivityB is no more available. How do I fix this issue?
I am using support libs for Android 2.2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不太喜欢使用 try catch 块来吞掉异常。您没有解决根本原因。
这就是我认为正在发生的事情。
当您按后退按钮返回 ActivityA 时,Activity B 中的片段视图将被销毁,但您启动的 AsyncTask 会继续执行,并且当其完成时,将从 UI 线程调用 AsyncTask 的 onPostExecute(result) 方法。我假设这是您更新片段视图的地方。但是,如果视图已经被销毁,您会得到一个 NullPointerException,这就是为什么在尝试更新片段视图之前检查它们是否为 null 总是一个好主意。
I am not a big fan of try catch block to swallow exceptions. You are not addressing the root cause.
Here is what i think is happening.
When you press the back button to go back to ActivityA the fragments' views in Activity B are destroyed but the AsyncTask you've started continues to execute and when its done the the AsyncTask's onPostExecute(result) method is called from the UI thread. I'm assuming this where you update your fragments views. But if the views have already been destroyed you get a NullPointerException and that's why its always a good idea to check the fragments' views for null before trying to update them.
最好在进程在后台运行时显示
ProgressDialog
并使其不可取消,这样当您单击后退按钮时,它就不允许执行任何操作。在onPreExecute()
中显示对话框并在onPostExecute()
中关闭。在后台加载数据时无法返回导航。您将获得 UI 线程的更新,并且不会出现任何异常以及应用程序崩溃。It is better to show
ProgressDialog
while process is running in background and make it not cancelable so that when you click back button it will not allow any action. Show the Dialog inonPreExecute()
and dismiss inonPostExecute()
. There is no chance of back navigation while loading data in background. You will get updated on UI thread as well as no chance of any exceptions as well as app crashing.我得到了答案。只需将所有代码添加到 try catch 块中,即使活动/片段抛出异常,也可以防止应用程序崩溃。
I got the answer. Just add all the code to a try catch block which will prevent the application to crash even if the activity/fragment throws an exception.