AsycTask Throwing IllegalStateException - snippet not tied to action

I have the following AsyncTask in an android app. This AsyncTask is contained 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 explain to me why this is happening and suggest ways to solve this problem?

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

      

+3


source to share


2 answers


Since you are doing a background job in your application. there is no guarantee that the user will remain on one screen until the task is completed, so if the user navigates to another screen or presses the Home button before the task is completed; your fragment is separate from the activity. So always make sure you have a Fragment associated with an Activity. try checking with

if (isAdded) { //Do your UI stuff here }



add above check where you get callback

+4


source


Move the code from onCreate

to onActivityCreated

instead of trying getActivity

@ onCreate

.

This is because a fragment can be created when the activity is not ready yet, which is when you try to use it.



This is, of course, if you add a snippet to an activity like:

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

      

+3


source







All Articles