简体   繁体   English

从破坏的活动/片段敬酒,getString问题

[英]Toast from destroyed activity/fragment, getString issue

I have a fragment with UI that is responsible for doing short async api-calls. 我的UI片段负责执行简短的异步api调用。 When an async task completes fragment triggers a Toast message with a result-string. 异步任务完成后,片段会触发带有结果字符串的Toast消息。

My issue is that if a user presses Back button without waiting for the result the app crushes due to a onPostExecute method, which in turn triggers Toast + getString(R.string.whatever) in the fragment that is already detached, because the activity is behind the onDestroy state. 我的问题是,如果用户在不等待结果的情况下按下“返回”按钮,则应用程序会由于onPostExecute方法而onPostExecute ,这又会触发已经分离的片段中的Toast + getString(R.string.whatever) ,因为活动是在onDestroy状态后面。

I can check whether the fragment is detached or use a ProgressDialog , which is modal but I think it would be nice to show the toasts without blocking or any other quirks. 我可以检查片段是否已分离,或使用ProgressDialog ,它是模式对话框,但我认为最好在不阻塞或没有其他怪异的情况下显示吐司。 Any suggestions on how to achieve it? 关于如何实现的任何建议? Broadcast receiver in the application class == overkill? 应用类中的广播接收器==过度杀伤力?

Thanks. 谢谢。

UPD logs: UPD日志:

01-24 12:01:29.626: E/AndroidRuntime(616): java.lang.IllegalStateException: Fragment HandsetSocialNetworksFragment{40612a78} not attached to Activity 01-24 12:01:29.626: E/AndroidRuntime(616): at android.support.v4.app.Fragment.getResources(Fragment.java:571) 01-24 12:01:29.626: E/AndroidRuntime(616): at android.support.v4.app.Fragment.getString(Fragment.java:593) 01-24 12:01:29.626:E / AndroidRuntime(616):java.lang.IllegalStateException:片段HandsetSocialNetworksFragment {40612a78}未附加到活动01-24 12:01:29.626:E / AndroidRuntime(616):在Android上。 support.v4.app.Fragment.getResources(Fragment.java:571)01-24 12:01:29.626:E / AndroidRuntime(616):at android.support.v4.app.Fragment.getString(Fragment.java:593 )

At the start of the async call, get the activity from the fragment, and get the application context from it. 在异步调用开始时,从片段中获取活动,并从中获取应用程序上下文。 Use that one later to get the string you need. 以后再使用该字符串即可获得所需的字符串。

Alternatively, you can fetch the string you need when you start the async call, instead of when you have to show the toast. 另外,您可以在启动异步调用时获取所需的字符串,而不必在必须显示烤面包时获取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM