android - Using GridView Image in Fragment -


i developing android app uses gridview show images in class extends fragment. when run code, met error. error show: "nullpointerexception" in gridview setadapter. please me. sorry english, not good.

fragment class:

public class detailmore extends fragment{  gridview gridviewimage; private utils utils; private arraylist<string> imagepaths = new arraylist<string>(); private gridviewimageadapter adapter; private gridview gridview; private int columnwidth; @override public view oncreateview(layoutinflater inflater, viewgroup container,         bundle savedinstancestate) {      view view = inflater.inflate(r.layout.detail_more, null);      // create ui components here.     gridviewimage = (gridview)view.findviewbyid(r.id.grid_view);     utils = new utils(getactivity().getapplicationcontext());      // initilizing grid view     initilizegridlayout();   // loading image paths sd card     imagepaths = utils.getfilepaths();      // gridview adapter     adapter = new gridviewimageadapter(imagepaths,             columnwidth);      // setting grid view adapter     try {         gridview.setadapter(adapter);     } catch (exception e) {         // todo auto-generated catch block         e.printstacktrace();     }     //gridviewimage.setadapter(new gridviewimageadapter(activity, filepaths, imagewidth));      return view; }  private void initilizegridlayout() {     resources r = getresources();     float padding = typedvalue.applydimension(typedvalue.complex_unit_dip,             appconstant.grid_padding, r.getdisplaymetrics());      columnwidth = (int) ((utils.getscreenwidth() - ((appconstant.num_of_columns + 1) * padding)) / appconstant.num_of_columns);      gridviewimage.setnumcolumns(appconstant.num_of_columns);     gridviewimage.setcolumnwidth(columnwidth);     gridviewimage.setstretchmode(gridview.no_stretch);     gridviewimage.setpadding((int) padding, (int) padding, (int) padding,             (int) padding);     gridviewimage.sethorizontalspacing((int) padding);     gridviewimage.setverticalspacing((int) padding); } } 

gridviewadapter:

public class gridviewimageadapter extends baseadapter {  private arraylist<string> _filepaths = new arraylist<string>(); private int imagewidth;  public gridviewimageadapter(arraylist<string> filepaths,         int imagewidth) {           this._filepaths = filepaths;     this.imagewidth = imagewidth; }  @override public int getcount() {     return this._filepaths.size(); }  @override public object getitem(int position) {     return this._filepaths.get(position); }  @override public long getitemid(int position) {     return position; }  @override public view getview(int position, view convertview, viewgroup parent) {     imageview imageview;     if (convertview == null) {         imageview = new imageview(_activity);     } else {         imageview = (imageview) convertview;     }      // screen dimensions     bitmap image = decodefile(_filepaths.get(position), imagewidth,             imagewidth);      imageview.setscaletype(imageview.scaletype.center_crop);     imageview.setlayoutparams(new gridview.layoutparams(imagewidth,             imagewidth));     imageview.setimagebitmap(image);     return imageview; }   public static bitmap decodefile(string filepath, int width, int hight) {     try {          file f = new file(filepath);          bitmapfactory.options o = new bitmapfactory.options();         o.injustdecodebounds = true;         bitmapfactory.decodestream(new fileinputstream(f), null, o);          final int required_width = width;         final int required_hight = hight;         int scale = 1;         while (o.outwidth / scale / 2 >= required_width                 && o.outheight / scale / 2 >= required_hight)             scale *= 2;          bitmapfactory.options o2 = new bitmapfactory.options();         o2.insamplesize = scale;         return bitmapfactory.decodestream(new fileinputstream(f), null, o2);     } catch (filenotfoundexception e) {         e.printstacktrace();     }     return null; }  } 

appconstant:

public class appconstant {  // number of columns of grid view public static final int num_of_columns = 3;  // gridview image padding public static final int grid_padding = 8; // in dp  // sd card image directory public static final string photo_album = "festival";  // supported file formats public static final list<string> file_extn = arrays.aslist("jpg", "jpeg",         "png");   } 

utils:

public class utils {  private context _context;  // constructor public utils(context context) {     this._context = context; }  // reading file paths sdcard public arraylist<string> getfilepaths() {     arraylist<string> filepaths = new arraylist<string>();      file directory = new file(             android.os.environment.getexternalstoragedirectory()                     + file.separator + appconstant.photo_album);      // check directory     if (directory.isdirectory()) {         // getting list of file paths         file[] listfiles = directory.listfiles();          // check count         if (listfiles.length > 0) {              // loop through files             (int = 0; < listfiles.length; i++) {                  // file path                 string filepath = listfiles[i].getabsolutepath();                  // check supported file extension                 if (issupportedfile(filepath)) {                     // add image path array list                     filepaths.add(filepath);                 }             }         } else {             // image directory empty             toast.maketext(                     _context,                     appconstant.photo_album                             + " empty. please load images in !",                     toast.length_long).show();         }      } else {         alertdialog.builder alert = new alertdialog.builder(_context);         alert.settitle("error!");         alert.setmessage(appconstant.photo_album                 + " directory path not valid! please set image directory name appconstant.java class");         alert.setpositivebutton("ok", null);         alert.show();     }      return filepaths; }  // check supported file extensions private boolean issupportedfile(string filepath) {     string ext = filepath.substring((filepath.lastindexof(".") + 1),             filepath.length());      if (appconstant.file_extn             .contains(ext.tolowercase(locale.getdefault())))         return true;     else         return false;  }  /*  * getting screen width  */ @suppresswarnings("deprecation") @suppresslint("newapi") public int getscreenwidth() {     int columnwidth;     windowmanager wm = (windowmanager) _context             .getsystemservice(context.window_service);     display display = wm.getdefaultdisplay();      final point point = new point();     try {         display.getsize(point);     } catch (java.lang.nosuchmethoderror ignore) { // older device         point.x = display.getwidth();         point.y = display.getheight();     }     columnwidth = point.x;     return columnwidth; }  } 

detail_more.xml:

<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <gridview android:id="@+id/grid_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:numcolumns="auto_fit" android:gravity="center" android:stretchmode="columnwidth" android:background="#000000">  </gridview>  </linearlayout> 

your gridview not initialized , hence error @ gridview.setadapter(adapter);.

the call,

 gridview gridview; 

only declares gridview, in order use must initialize

gridview = new gridview(context); 

or

gridview = (gridview) view.findviewbyid(your id); 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -