加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – AsycTask抛出IllegalStateException – 片段未附加到Act

发布时间:2020-12-15 04:21:46 所属栏目:Java 来源:网络整理
导读:我的 Android应用程序中有以下AsyncTask.此AsyncTask包含在扩展PreferenceFragment的类的OnCreate()方法中. public class NotificationsPreferenceFragment extends PreferenceFragment {private static Context context;public NotificationsPreferenceFrag
我的 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;
        }
    });
}
}

我收到以下异常:

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)

有人可以向我解释为什么会发生这种情况并建议解决此问题的方法吗?

更新:

以下是活动的代码:

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);
}
}

解决方法

由于您在应用中执行后台任务.在任务完成之前,无法保证用户将保持在同一屏幕上,因此如果用户在任务完成之前导航到其他屏幕或按下主页按钮;你的片段与活动分离.因此,请务必确保您在活动中附加了片段.
尝试检查

if(isAdded){
//在这里做你的UI
}

在上面的任何地方添加以上检查回调

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读