java AsycTask 抛出 IllegalStateException - 片段未附加到活动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25262994/
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
AsycTask Throwing IllegalStateException - Fragment Not Attached To Activity
提问by COBOL
I have the following AsyncTask in my Android application. This AsyncTask is contained with within the OnCreate() method of a class that extends PreferenceFragment.
我的 Android 应用程序中有以下 AsyncTask。此 AsyncTask 包含在扩展 PreferenceFragment 的类的 OnCreate() 方法中。
public class NotificationsPreferenceFragment extends PreferenceFragment {
private static Context context;
public NotificationsPreferenceFragment() {
}
public NotificationsPreferenceFragment(Context context) {
this.context = context;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notifications);
getPreferenceManager().findPreference(getString(R.string.send_all_notifications))
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
class NotificationSendTask extends DialogAsyncTask {
public static final String TAG = "NotificationFragment";
public NotificationSendTask(Activity activity, String dialogMsg) {
super(activity, dialogMsg);
}
@Override
protected String doInBackground(String... params) {
String url = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(getString(R.string.notification_web_service_url), getString(R.string.default_notification_web_service_url));
if (NetworkingHelper.isNetworkAvailable(getActivity())) {
NotificationDao notificationDao = new NotificationDaoImpl(DatabaseManager.getInstance(getActivity().getApplicationContext()), getActivity().getApplicationContext());
List<Notification> unsentNotificationList = notificationDao.findAllNotSent();
if (unsentNotificationList.size() != 0) {
NotificationSenderTask ns = new NotificationSenderTask(url, context);
try {
if (ns.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (unsentNotificationList)).get()) {
return getString(R.string.success);
}
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
} catch (ExecutionException e) {
Log.e(TAG, e.getMessage());
}
return getString(R.string.failed_to_send_notifications);
} else {
return getString(R.string.no_notifications_to_send);
}
} else {
return getString(R.string.no_connection_notifications);
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null && dialog.isShowing()) {
dialog.hide();
}
Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
}
}
NotificationSendTask notificationSendTask = new NotificationSendTask(getActivity(), "Sending unsent notifications...");
notificationSendTask.execute();
return true;
}
});
getPreferenceManager().findPreference(getString(R.string.export_notifications)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
NotificationExportTask notificationExportTask = new NotificationExportTask(NotificationsPreferenceFragment.this.getActivity(), 1);
notificationExportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return true;
}
});
}
}
I am getting the following exception:
我收到以下异常:
java.lang.IllegalStateException: Fragment NotificationsPreferenceFragment{416092f8} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:741)
at android.app.Fragment.getString(Fragment.java:763)
Can someone please explain to me why this is happening and suggest ways to fix this issue?
有人可以向我解释为什么会发生这种情况并建议解决此问题的方法吗?
UPDATE:
更新:
Here is the code for the Activity:
这是活动的代码:
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
}
回答by Amol Desai
Since you are performing background task in your app. there is no guarantee that user will stay on same screen until task finishes so if user navigates to other screen or presses home button before task is completed; your fragment is detached from activity. So always make sure that you have fragment attached with the Activity. try checking with
由于您正在应用程序中执行后台任务。不能保证用户在任务完成之前会停留在同一屏幕上,因此如果用户在任务完成之前导航到其他屏幕或按下主页按钮;您的片段与活动分离。因此,请始终确保将片段附加到 Activity。尝试检查
if (isAdded) {
//Do your UI stuff here
}
if (isAdded) {
//Do your UI stuff here
}
add above check wherever you get callback
在您收到回调的任何地方添加上面的检查
回答by Simas
Move your code from onCreate
to onActivityCreated
instead of trying to getActivity
@ onCreate
.
将您的代码从onCreate
to移动onActivityCreated
而不是尝试getActivity
@ onCreate
。
That's because the fragment can be created when the activity is not yet ready, that's when you are trying to use it.
那是因为可以在活动尚未准备好时创建片段,这就是您尝试使用它的时候。
That is of course ifyou are adding the fragment to an activity like:
当然,如果您要将片段添加到活动中,例如:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.content, new PreferenceFragment()).commit();