Null Pointer exception in ViewPager Fragment with GridView and custom Adapter-Collection of common programming errors

I am getting a null pointer exception on the line where I am setting the adapter (at mGrid.setAdapter(new AppsAdapter());. As far as I can see everything in the adapter is pointing to something valid. I am trying to display a grid of icons that are the App icons found in the app drawer (and the app list in Settings).

Here is the code for the Fragment:

public class Tab3_fragment extends Fragment {

GridView mGrid;
private List mApps = new ArrayList();


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    return inflater.inflate(R.layout.tabfragment3, container, false);

}

@Override
public void onStart() {
    super.onStart();

    loadApps();
    mGrid = (GridView) getActivity().findViewById(R.id.myGrid);
    mGrid.setAdapter(new AppsAdapter());

}

@Override
public void onResume() {
    super.onResume();
    loadApps();
}

private void loadApps() {
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    mApps = getActivity().getPackageManager().queryIntentActivities(mainIntent, 0);
}

public class AppsAdapter extends BaseAdapter {
    public AppsAdapter() {
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i;

        if (convertView == null) {
            i = new ImageView(getActivity().getApplicationContext());
            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            i.setLayoutParams(new GridView.LayoutParams(50, 50));
        } else {
            i = (ImageView) convertView;
        }

        ResolveInfo info = mApps.get(position);
        i.setImageDrawable(info.activityInfo.loadIcon(getActivity().getPackageManager()));

        return i;
    }


    public final int getCount() {
        return mApps.size();
    }

    public final Object getItem(int position) {
        return mApps.get(position);
    }

    public final long getItemId(int position) {
        return position;
    }
  } 
}

Here is the code for the Layout (which is included the “tab3fragment.xml” inside a scrollView):



When I swipe over to the second tab (of 3) it suddenly crashes and gives me these errors:

04-27 21:31:51.337: D/libEGL(16874): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
04-27 21:31:51.369: D/libEGL(16874): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
04-27 21:31:51.369: D/libEGL(16874): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
04-27 21:31:51.627: D/OpenGLRenderer(16874): Enabling debug mode 0
04-27 21:31:51.634: I/Choreographer(16874): Skipped 110 frames!  The application may be doing too much work on its main thread.
04-27 21:32:22.994: D/AndroidRuntime(16874): Shutting down VM
04-27 21:32:22.994: W/dalvikvm(16874): threadid=1: thread exiting with uncaught exception (group=0x41c92930)
04-27 21:32:23.009: E/AndroidRuntime(16874): FATAL EXCEPTION: main
04-27 21:32:23.009: E/AndroidRuntime(16874): java.lang.NullPointerException
04-27 21:32:23.009: E/AndroidRuntime(16874):    at com.rdx.themetesterplus.Tab3_fragment.onStart(Tab3_fragment.java:36)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.support.v4.app.Fragment.performStart(Fragment.java:1484)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:941)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:807)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.support.v4.app.FragmentManagerImpl.startPendingDeferredFragments(FragmentManager.java:1112)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1461)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.support.v4.view.ViewPager.populate(ViewPager.java:1012)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.support.v4.view.ViewPager.populate(ViewPager.java:881)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.support.v4.view.ViewPager$3.run(ViewPager.java:237)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.view.Choreographer.doCallbacks(Choreographer.java:562)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.view.Choreographer.doFrame(Choreographer.java:531)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.os.Handler.handleCallback(Handler.java:725)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.os.Looper.loop(Looper.java:137)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at android.app.ActivityThread.main(ActivityThread.java:5226)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at java.lang.reflect.Method.invokeNative(Native Method)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at      java.lang.reflect.Method.invoke(Method.java:511)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
04-27 21:32:23.009: E/AndroidRuntime(16874):    at dalvik.system.NativeStart.main(Native Method)

Any help would be appreciated. Thanks in advance 🙂

  1. Just an observation, not sure if its the issue or not, but from my understanding onStart() and onResume() happen right after each other in the start of the life cycle of a Fragment 1. I noticed loadApps() happens in each. From what I can tell, the loadApps() function is called twice on start up. Correct me if Im wrong, just thought I would mention it.

    Im not sure if you can reference the mGrid until the View has been setup first. Usually, once the view has been set, then you can use the findViewByID() method.

    Source Fragment Life Cycle Source

  2. Try putting

    loadApps();
    mGrid = (GridView) getActivity().findViewById(R.id.myGrid);
    mGrid.setAdapter(new AppsAdapter());
    

    your data setup code in onActivityCreated() method instead of onStart().This should resolve your problem. Let me know if you are still getting same prob.