-1

I am getting nullpointer exception when i am initializing ImageAdapter object. I have defined my IMageAdapter parameterized Constructor and calling it correctly(hopefully). I don't get where i am going wrong?

I have created separate ImageApdater java class and did not subclassed it, and by gridview for which i created this imageadapter is on a Fragment and this Fragment is Tab.

Here is my ImageAdapter class

public class ImageAdapter extends BaseAdapter {

Context mcontext;
int[] IMAGES;
int[] IMAGE_ID,  IMAGE_PRICE;
String[] IMAGE_NAME,  MODEL_TYPE;

public ImageAdapter(Context context, int[] images, int[] image_id, int [] image_price,   
String[] image_name, String[] model_type) {

    mcontext=context;
    this.IMAGES = images;
    this.IMAGE_ID=image_id;
    this.IMAGE_PRICE=image_price;
    this.IMAGE_NAME=image_name;
    this.MODEL_TYPE=model_type;
}//ImageAdapter Constructor

and i am calling it in Fragment class as below:

public class CommunityGalleryFragment extends Fragment {


    byte[] image = null;
    Bitmap bitmapImage = null;
    Context context;

  // images to be inflated in gallery view

// Images to be stored in database table
int[] IMAGES = { R.drawable.a, R.drawable.g, R.drawable.c,
        R.drawable.h, R.drawable.j, R.drawable.d, R.drawable.f,
        R.drawable.e, R.drawable.i, R.drawable.b };

// Spinner data
String[] VIEWALL_ITEMS = { "View All", "Glaze ", "Ceramic", "Plaster" };
String[] SORT_ITEMS = { "Sort By", "name", "Date" };

// Cursor to get records from table
Cursor initial_cursor;
RMLocalGalleryAdapter rmLocalGalleryAdapter;

// Data to be stored in database table

// Image ID's
int[] IMAGE_ID = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Image Price
int[] IMAGE_PRICE = { 32, 76, 25, 30, 50, 22, 33, 55, 65, 43 };
String[] IMAGE_NAME = {"a", "g","c", "h", "j", "d", "f", "e", "i","b"};

// Model Types
String[] MODEL_TYPE = { "Glaze", "Ceramic", "Ceramic", "Ceramic", "Glaze",
        "Glaze", "Plaster", "Plaster", "Plaster", "Plaster" };

String date;
// Declaring views
public Spinner viewAll_spinner, sort_spinner;
GridView gridView;

//boolean fromHomeActivity, fromLocalGallery;


public CommunityGalleryFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // inflating communitygallery_fragment layout from layout folder
    this.context = container.getContext();

    View view = inflater.inflate(R.layout.communitygallery_fragment, container, false);

    viewAll_spinner = (Spinner) view    
.findViewById(R.id.communityGallery_spinner_viewAll);
    sort_spinner = (Spinner) view.findViewById(R.id.communityGallery_spinner_sort);

    rmLocalGalleryAdapter = new RMLocalGalleryAdapter(getActivity());
    rmLocalGalleryAdapter.openDB();

    initial_cursor = rmLocalGalleryAdapter.getAllImagesByDate();

    // Setup UI
    gridView = (GridView) view.findViewById(R.id.communityGallery_gridView);


    // inserting data into sqlite database only if there is no data inserted previously
    if (initial_cursor.getCount() == 0) {
        // inserting data in multiple records---- it will be inserted as
        // many as images are available in IMAGES
        for (int i = 0; i < IMAGES.length; i++) {
            byte[] image = convertToByteArray(IMAGES[i]);

            // /calling insertValues method of Adapter class and passing all
            // paramenters
            rmLocalGalleryAdapter.insertValues(image, IMAGE_ID[i],  IMAGE_PRICE[i], 
IMAGE_NAME[i], MODEL_TYPE[i]);
        }// for
    }// if
        // closing cursor to avoid memory leaks
    initial_cursor.close();
    return view;
}// onCreateView

private byte[] convertToByteArray(int image) {
    Resources resources = getResources();
    Drawable drawable = resources.getDrawable(image);
    Bitmap bitmap =  ((BitmapDrawable)drawable).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress( Bitmap.CompressFormat.PNG, 100, stream);
    byte[] bitmapData = stream.toByteArray();

    return bitmapData;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);

    // creating adapter for " View All" Spinner
    ArrayAdapter<String> viewAll_Adapter = new ArrayAdapter<String>(
            getActivity(), android.R.layout.simple_spinner_dropdown_item, 
VIEWALL_ITEMS);

    // Creating adapter for " Sort By "Spinner
    ArrayAdapter<String> sortBy_Adapter = new ArrayAdapter<String>(
            getActivity(), android.R.layout.simple_spinner_dropdown_item, SORT_ITEMS);

    viewAll_spinner.setAdapter(viewAll_Adapter);
    sort_spinner.setAdapter(sortBy_Adapter);



    // setting ImageAdapter to the gridview


    //View spinner listener to handle selection in spinner
    viewAll_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,    int position, 
 long id) {
            // TODO Auto-generated method stub

            gridView.setAdapter(new ImageAdapter(context, IMAGES, IMAGE_ID, 
 IMAGE_PRICE, IMAGE_NAME, MODEL_TYPE ));

        }//view spinner 

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub

        }//view spinner
    });
    sort_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,    int position, 
long id) {
            // TODO Auto-generated method stub

            gridView.setAdapter(new ImageAdapter(context, IMAGES, IMAGE_ID, 
IMAGE_PRICE, IMAGE_NAME, MODEL_TYPE ));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub

        }
    });

}// onActivityCreated
}
Murli
  • 430
  • 5
  • 10
  • What is at line `44`? – M D Jul 08 '14 at 06:26
  • I have huge implementation after this constructor of this ImageAdapter, I have no errors in that as i successfully executed code by creating ImageAdapter as sub class, but when i make it as a separate java class I am getting this error. and also the logcat show this following error Nullpointerexception at com.galleryview.CommunityGalleryFragment$1.onItemSelected(CommunityGalleryFragment.java:149) (line 149 is where i am calling ImageAdapter constructor) – Murli Jul 08 '14 at 06:31
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Oleg Estekhin Jul 08 '14 at 06:36
  • hello murli i think you have to check in `ImageAdapter` class and please check `getview()` method of the `imageadapter` class is it return null then you will get null pointer exception. you have to inflate layout in 'getView()' method. thanks ;-) – bhavesh kaila Jul 08 '14 at 06:36
  • You are getting NPE at your ImageAdapter constructor. I think your context is null. Check your context object. – justDroid Jul 08 '14 at 06:40
  • @bhaveshkaila yes my getView() is not returning any null value, and i have inflated layout correctly..thanks :) – Murli Jul 08 '14 at 06:41
  • @justDroid yes i have referenced context in onCreateview by this.context = container.getContext(); so i guess context is not returning null. – Murli Jul 08 '14 at 06:43
  • Just debug your app. Without any null value you will not get NPE. Other parameters which you pass in constructor not seem to be null. – justDroid Jul 08 '14 at 06:48
  • and the code at line 41 in my ImageAdapter class is CommunityGalleryFragment communityGalleryFragment = new CommunityGalleryFragment(); /* this is line 41*/ int view_spinner_id =communityGalleryFragment.viewAll_spinner.getSelectedItemPosition(); int sort_spinner_id = communityGalleryFragment.sort_spinner.getSelectedItemPosition(); – Murli Jul 08 '14 at 06:52

1 Answers1

0

/* this is line 41*/ int view_spinner_id =communityGalleryFragment.viewAll_spinner.getSelectedItemPosition();

So communityGalleryFragment.viewAll_spinner is null. You're trying to use it too early.

If it is a spiner in a fragment as the name implies, you will have to wait for the fragment itself to initialize itself within the fragment lifecycle. In practice it's onCreateView() at earliest.

Also, referencing another class internals like this is not a good design practice.

laalto
  • 137,703
  • 64
  • 254
  • 280
  • yes, fragment is initializing the both the spinners and and i used arrayadapter to set data in it and it does execute in onCreateView. I want to get the selected item position of spinner in ImageAdapter class to use appropriate cursor object in my ImageApdater class to set the gridview..how should i get the selected cursor position in ImageAdapter class ? thanks for the suggestion :) – Murli Jul 08 '14 at 07:17