3

I am getting java.lang.NullPointerException when I try to get getApplicationContext(). I am getting this error from users and not able to reproduce this on my phone.

Could it be that I am calling getActivity().getApplicationContext() before the complete Fragment/Activity has been loaded? If that's the problem, what function in the fragment can I be calling the getActivity().getApplicationContext() earliest from?

Should I be putting the getActivity().getApplicationContext() in onResume() that comes last in the lifecycle of the Fragment becoming active?

Basically, I need to call it sometime after the fragment loads.

onCreateView in my Fragment:

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    ctxt = getActivity().getApplicationContext();

    v = inflater.inflate(R.layout.fragment_test,
            container, false);

    //MODE CODE HERE THAT I AM NOT SHOWING  

    //THIS LINE BELOW IS GIVING THE NULL POINTER EXCEPTION - Am I calling getActivity().getApplicationContext() too early in the Fragment's lifecycle?
    _adapter_lv_blockedApps2 = new Adapter_BlockedApps(
                    getActivity().getApplicationContext(), holder);

    return v;

}

Below is the stack trace I am getting from users' phones.

java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.ContextWrapper.getApplicationContext()' on a null object reference
at com.mavdev.focusoutfacebook.fragments.scheduledblocks.Fragment_scheduled_newdetail$populateLV_blockedAppsFromSystem.doInBackground(Fragment_scheduled_newdetail.java:2597)
at com.mavdev.focusoutfacebook.fragments.scheduledblocks.Fragment_scheduled_newdetail$populateLV_blockedAppsFromSystem.doInBackground(Fragment_scheduled_newdetail.java:2486)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
... 4 more

The complete function: private class populateLV_AppsFromSystem extends AsyncTask {

    @Override
    protected Void doInBackground(Void... params) {
        if (!isCancelled()) {
            ArrayList<Datamodel> holder = new ArrayList<Datamodel>();

            Map<String, Drawable> map_Apps = new HashMap<String, Drawable>();

            List<String> Apps_List = Arrays.asList(TextUtils.split(
                    ToDisplay.getApps(), ","));

            if (Apps_List != null) {
                for (String s : Apps_List) {
                    String s_appName = "";

                    try {
                        s_appName = mAppInfo.getAppNamefromPackage(s,
                                getActivity().getApplicationContext());
                    } catch (Exception e) {
                        s_appName = "Unknown";
                    }
                    Drawable d = mAppInfo.getIconDrawablefromAppName(
                            s_appName, getActivity());
                    map_Apps.put(s_appName, d); 
                }
            }

            /****************************************************
             * GETTING THE ADAPTER
             ****************************************************/
            for (Map.Entry<String, Drawable> entry : map_Apps
                    .entrySet()) {

                if (isCancelled()) {
                    return null;
                }

            }

            **//THIS IS WHERE THE APP IS CRASHING WITH NULL POINTER**  
            _adapter_lv_Apps2 = new Adapter_Apps(
                    getActivity().getApplicationContext(), holder);

        } else {
            _adapter_lv_Apps2 = null;
        }

        /****************************************************/

        return null;
    }
user1406716
  • 9,565
  • 22
  • 96
  • 151
  • not possible, there is no onCreateView in the stacktrace ... and of course getActivity returns null ... from lifecycle of fragment should be obvious when you can use getActivity safety – Selvin Jun 26 '15 at 15:53
  • Is the line giving a `NullPointerException` part of `doInBackground` method of an `AsyncTask`? – TheoK Jun 26 '15 at 15:56
  • @TheoK Yes, I tried to remove a bunch of the code to make the question short, but let me add everything. – user1406716 Jun 26 '15 at 15:56
  • more than 2597 lines? are you calling getView on not attached fragment? – Selvin Jun 26 '15 at 15:57
  • Since you are defining in your fragment a `ctxt = getActivity().getApplicationContext();` try defining it as `final` variable and use that instead of calling it again in the arguments of the `Adapter_BlockedApps` – TheoK Jun 26 '15 at 16:00
  • @TheoK - Good tip, I will just try that. I could also do a check that if the first time `if(ctxt==null`, just all abort/error on the Fragment and take user back to where they came from with an error message. Thanks. – user1406716 Jun 26 '15 at 16:00
  • @Selvin I am calling the AsyncTask that contains the `getApplicationContext()` from the onCreateView – user1406716 Jun 26 '15 at 16:03
  • You are starting the AsyncTask in onCreateView which ends after fragment is detached – Selvin Jun 26 '15 at 16:04
  • @Selvin - How can you know that? I am starting the AsyncTask right before onCreateView finishes. Where should I be calling the AsyncTask? in `onResume`? – user1406716 Jun 27 '15 at 06:10
  • IIf you are calling this on a second activity or class, try to call `getApplicationContext()` on the parent activity, send a reference of parent activity, just a suggestion – Bibaswann Bandyopadhyay Sep 09 '15 at 14:52
  • I had same issue. But this link helped me: http://stackoverflow.com/questions/16920942/getting-context-in-asynctask – Uchechukwu Nnabugwu Aug 27 '16 at 02:42

0 Answers0