My class extends BaseAdapter and I am using Fragment but I am getting NullPointerException at this line:
this.myInflater = LayoutInflater.from(activity);
May I know what is the reason ? Why i am facing this issue ? How can i resolve this ?
Adapter code:
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
private ArrayList<Wallpaper> _wallPArray;
private LayoutInflater myInflater;
private ImageLoader imageLoader;
private Utils utils;
private ImageLoaderConfiguration config;
private DisplayImageOptions options;
public GridViewImageAdapter(Activity activity, ArrayList<Wallpaper> filePaths) {
this._activity = activity;
this._wallPArray = filePaths;
this.myInflater = LayoutInflater.from(activity); // getting NPE
imageLoader = ImageLoader.getInstance();
utils = new Utils(activity);
//Create configuration for ImageLoader
config = utils.ImgLoaderConfiguration();
// Creates display image options for custom display task
options = utils.DisplayImgOptions();
// Initialize ImageLoader with created configuration. Do it once.
imageLoader.init(config);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = myInflater.inflate(R.layout.layout_gridview_image, null);
holder = new ViewHolder();
holder.preview = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Logcat:
java.lang.NullPointerException
at android.view.LayoutInflater.from(LayoutInflater.java:211)
at com.test.data.GridViewImageAdapter.<init>(GridViewImageAdapter.java:42)
at com.test.data.PhotosFragment.jsonTaskComplete(PhotosFragment.java:112)
at com.test.data.PhotosFragment$JsonDownloaderTask.onPostExecute(PhotosFragment.java:149)
at com.test.data.PhotosFragment$JsonDownloaderTask.onPostExecute(PhotosFragment.java:118)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5061)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:603)
at dalvik.system.NativeStart.main(Native Method)
The reason is,
activity
is null. Check that you are instantiating the adapter, when you have a validContext
. E.g. insideonCreate
. Since you are using the Activity only to retrieve theLayoutInflater
you could also pass only the an instance ofLayoutInflater