AsycTask抛出IllegalStateException异常 - 碎片没有连接到活动 [英] AsycTask Throwing IllegalStateException - Fragment Not Attached To Activity

查看:361
本文介绍了AsycTask抛出IllegalStateException异常 - 碎片没有连接到活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Andr​​oid应用程序下面的AsyncTask。这AsyncTask的包含一类的OnCreate()方法,扩展了preferenceFragment内。

 公共类通知preferenceFragment扩展$ P $ {pferenceFragment私有静态上下文的背景下;公众通知preferenceFragment(){}公众通知preferenceFragment(上下文的背景下){
    this.context =背景;
}@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    加preferencesFromResource(R.xml pref_notifications);    获得preferenceManager()。找到preference(的getString(R.string.send_all_notifications))
            .setOn preferenceClickListener(新preference.On preferenceClickListener(){
                @覆盖
                在preferenceClick(preference preference)公共布尔{                        类NotificationSendTask扩展DialogAsyncTask {                            公共静态最后的字符串标记=NotificationFragment;                            公共NotificationSendTask(活动活动,弦乐dialogMsg){
                                超(活动,dialogMsg);
                            }                            @覆盖
                            保护字符串doInBackground(字符串... PARAMS){
                                字符串URL = $p$pferenceManager.getDefaultShared$p$pferences(getActivity()).getString(getString(R.string.notification_web_service_url),的getString(R.string.default_notification_web_service_url));                                如果(NetworkingHelper.isNetworkAvailable(getActivity())){
                                    NotificationDao notificationDao =新NotificationDaoImp​​l(DatabaseManager.getInstance(getActivity()getApplicationContext()),getActivity()getApplicationContext());                                    清单<通知和GT; unsentNotificationList = notificationDao.findAllNotSent();
                                    如果(unsentNotificationList.size()!= 0){
                                        NotificationSenderTask NS =新NotificationSenderTask(URL,背景);
                                        尝试{
                                            如果(ns.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,(unsentNotificationList))。获得()){
                                                返回的getString(R.string.success);
                                            }
                                        }赶上(InterruptedException的E){
                                            Log.e(TAG,e.getMessage());
                                        }赶上(为ExecutionException E){
                                            Log.e(TAG,e.getMessage());
                                        }                                        返回的getString(R.string.failed_to_send_notifications);
                                    }其他{
                                        返回的getString(R.string.no_notifications_to_send);
                                    }
                                }其他{
                                    返回的getString(R.string.no_connection_notifications);
                                }
                            }                            公共无效onPostExecute(字符串结果){
                                super.onPostExecute(结果);
                                如果(对话= NULL&放大器;!&安培; dialog.isShowing()){
                                    dialog.hide();
                                }
                                Toast.makeText(活动,结果,Toast.LENGTH_SHORT).show();
                            }
                        }
                        NotificationSendTask notificationSendTask =新NotificationSendTask(getActivity()发送未发送通知...);
                        notificationSendTask.execute();
                        返回true;                }
            });    get$p$pferenceManager().find$p$pference(getString(R.string.export_notifications)).setOn$p$pferenceClickListener(new preference.On preferenceClickListener(){
        @覆盖
        在preferenceClick(preference preference)公共布尔{
            NotificationExportTask notificationExportTask =新NotificationExportTask(通知preferenceFragment.this.getActivity(),1);
            notificationExportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            返回true;
        }
    });
}
}

我收到以下异常:

  java.lang.IllegalStateException:片段通知$ P $ {pferenceFragment} 416092f8未连接到活动
在android.app.Fragment.getResources(Fragment.java:741)
在android.app.Fragment.getString(Fragment.java:763)

为什么这是发生在我身上能有人请解释,并建议如何解决这个问题?

更新:

下面是code的活动:

 公共类SettingsActivity扩展$ P $ {pferenceActivity@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
}@覆盖
保护无效的onDestroy(){
    super.onDestroy();
}@覆盖
@TargetApi(Build.VERSION_ codeS.HONEYCOMB)
公共无效onBuildHeaders(列表<页眉和GT;目标){
    loadHeadersFromResource(R.xml pref_headers,目标);
}
}


解决方案

的onCreate 移动你的code到 onActivityCreated ,而不是试图 getActivity @ 的onCreate

这是因为可以在活动还没有准备好要创建的片段,当你试图使用它。

这是当然的如果您要添加的片段的活动,如:

  FragmentTransaction英尺= getFragmentManager()调用BeginTransaction()。
ft.replace(android.R.id.content,新的preferenceFragment())提交()。

I have the following AsyncTask in my Android application. This AsyncTask is contained with within the OnCreate() method of a class that extends PreferenceFragment.

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

解决方案

Move your code from onCreate to onActivityCreated instead of trying to 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 if you are adding the fragment to an activity like:

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.content, new PreferenceFragment()).commit();

这篇关于AsycTask抛出IllegalStateException异常 - 碎片没有连接到活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆