Android – try to call the virtual method for the null object reference of SharedPreferences in the fragment of actionbaractivity

My application needs to access the shared preferences file in the background. Since I started using the actionbar activity of the v21 support library to save my fragments, my app force has been closed. Every time the fragments leave the screen, they are forced to close, but the asynchronous task is still running and tries to access the SharedPreferences file. Why throw this error and how can I solve it?

This is a stack trace:

12-22 23:49:49.469: E/AndroidRuntime(23016): FATAL EXCEPTION: AsyncTask #4
12-22 23:49:49.469: E/AndroidRuntime(23016): Process: com.bernard.beaconportal.activities, PID: 23016
12-22 23:49:49.469: E/AndroidRuntime(23016): java.lang.RuntimeException: An error occured while executing doInBackground()
12-22 23:49:49.469: E/AndroidRuntime(23016):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
12-22 23:49:49.469: E/AndroidRuntime(23016):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
12-22 23:49:49.469: E/AndroidRuntime(23016):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
12-22 23:49:49.469: E/AndroidRuntime(23016):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
12-22 23:49:49.469: E/AndroidRuntime(23016):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-22 23:49:49.469: E/AndroidRuntime(23016):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-22 23:49:49.469: E/AndroidRuntime(23016):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-22 23:49:49.469: E/AndroidRuntime(23016):    at java.lang.Thread.run(Thread.java:818)
12-22 23:49:49.469: E/AndroidRuntime(23016): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.support.v4.app.FragmentActivity.getSharedPreferences(java.lang.String, int)' on a null object reference
12-22 23:49:49.469: E/AndroidRuntime(23016):    at com.bernard.beaconportal.activities.Due_Tommorow_Fragment$Update.doInBackground(Due_Tommorow_Fragment.java:815)
12-22 23:49:49.469: E/AndroidRuntime(23016):    at com.bernard.beaconportal.activities.Due_Tommorow_Fragment$Update.doInBackground(Due_Tommorow_Fragment.java:1)
12-22 23:49:49.469: E/AndroidRuntime(23016):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
12-22 23:49:49.469: E/AndroidRuntime(23016):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-22 23:49:49.469: E/AndroidRuntime(23016):    ... 4 more

The following is the specific line of code where the error occurred:

    SharedPreferences userName = getActivity().getSharedPreferences(
            "Login_Info", Context.MODE_PRIVATE);

This is an asynchronous task with an error:

public class Update extends AsyncTask<String, Void, Void> {

        private final HttpClient Client = new DefaultHttpClient();

        @Override
        protected Void doInBackground(String... urls) {
            SharedPreferences bDay = getActivity().getSharedPreferences(
                    "Login_Info", Context.MODE_PRIVATE);

            String day1 = Integer.toString(bDay.getInt("Day", 0));

            String year1 = Integer.toString(bDay.getInt("Year", 0));

            String month1 = Integer.toString(1 + bDay.getInt("Month", 0));

            SharedPreferences userName = getActivity().getSharedPreferences(
                    "Login_Info", Context.MODE_PRIVATE);

            String day = day1.replaceFirst("^0+(?!$)", "");

            String month = month1.replaceFirst("^0+(?!$)", "");

            String year = year1.replaceFirst("^0+(?!$)", "");

            String birthday = month + "/" + day + "/" + year;

            System.out.println("Birthday = " + birthday);

            String user = userName.getString("username", "");

            // String user = (username).split("@")[0];

            System.out.println("Username = " + user);

            try {

                // HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                // HttpGet httpGet = new HttpGet(
                // "http://www.beaconschool.org/~markovic/lincoln.PHP");

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://www.beaconschool.org/~markovic/lincoln.PHP");

                try {
                    // Add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                            2);
                    nameValuePairs
                            .add(new BasicNameValuePair("username", user));
                    nameValuePairs.add(new BasicNameValuePair("birthday",
                            birthday));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // Execute HTTP Post Request
                    response = httpclient.execute(httppost);

                    Log.d("Http Response:", response.toString());

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                }

                try {
                    Log.d("receiver", "animation stopped and downloaded file");

                    String homework = new Scanner(response.getEntity()
                            .getContent(), "UTF-8").useDelimiter("\\A").next();

                    // String homework =
                    // Html.fromHtml(duetommorow_html).toString();

                    SharedPreferences.Editor localEditor = getActivity()
                            .getSharedPreferences("homework",
                                    Context.MODE_PRIVATE).edit();

                    SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "MM/dd hh:mm a");
                    Calendar cal = Calendar.getInstance();
                    String downloaded = dateFormat.format(cal.getTime());

                    localEditor.putString("homework_content", homework);

                    localEditor.putString("download_date", downloaded);

                    localEditor.apply();

                    localEditor.putString("homework_content", homework);

                    localEditor.apply();

                    Log.d("receiver", "information given to shared preferences");

                    due_tommorow_list.clear();

                    parse_due_tommorow_string();

                    parse_due_tommorow_content();

                } catch (IllegalStateException e) {

                    e.printStackTrace();
                } catch (IOException e) {

                    e.printStackTrace();
                } catch (NullPointerException e) {

                    due_tommorow_list.clear();

                    parse_due_tommorow_string();

                    parse_due_tommorow_content();

                    SharedPreferences.Editor localEditor = getActivity()
                            .getSharedPreferences("homework",
                                    Context.MODE_PRIVATE).edit();

                    localEditor.putString("download_error", "yes");

                    localEditor.apply();

                    e.printStackTrace();
                }

                catch (NoSuchElementException e) {

                    due_tommorow_list.clear();

                    parse_due_tommorow_string();

                    parse_due_tommorow_content();

                    SharedPreferences.Editor localEditor = getActivity()
                            .getSharedPreferences("homework",
                                    Context.MODE_PRIVATE).edit();

                    localEditor.putString("download_error", "yes");

                    localEditor.apply();

                    e.printStackTrace();
                }

                catch (RuntimeException e) {

                    due_tommorow_list.clear();

                    parse_due_tommorow_string();

                    parse_due_tommorow_content();

                    SharedPreferences.Editor localEditor = getActivity()
                            .getSharedPreferences("homework",
                                    Context.MODE_PRIVATE).edit();

                    localEditor.putString("download_error", "yes");

                    localEditor.apply();

                    e.printStackTrace();
                }

            } finally {

            }
            return null;

        }

        @Override
        protected void onPostExecute(Void result) {

            swipeLayout.setRefreshing(false);

            Log.d("sender", "Broadcasting message");

            Intent intent = new Intent("up_navigation");

            intent.putExtra("message", "This is my message!");
            LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(
                    intent);

            Toast.makeText(getActivity(), "Refresh Finished", 4000).show();

            SharedPreferences download_error = getActivity()
                    .getSharedPreferences("homework", Context.MODE_PRIVATE);

            String error = download_error.getString("download_error", "no");

            String download_date = "Download error, refreshed homework using homework downloaded at "
                    + download_error.getString("download_date", "");

            if (error.equals("yes")) {

                SharedPreferences.Editor localEditor = getActivity()
                        .getSharedPreferences("homework", Context.MODE_PRIVATE)
                        .edit();

                Toast.makeText(getActivity(), download_date, Toast.LENGTH_LONG)
                        .show();

                localEditor.putString("download_error", "no");

                localEditor.commit();

            }

            adapter.notifyDataSetChanged();

            swipeLayout.setRefreshing(false);

        }

    }

resolvent:

You have done some time-consuming things in asynctask. When you execute the getactivity () part, the activity has been destroyed. Therefore, it is very correct to refer to getactivity () and return null

What you should do is your thread or asynctask. You should always check whether getactivity () is null to prevent the activity managed by your fragment from being destroyed

I don't think @ I'm_ With_ Stupid's answer is a good practice because it's bad to hold an activity reference in your fragment and the fragment has done it for you

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>