android - Why is GridView null on 2nd pass through onPostExecute() -


for fun i'm going through udacity popular movies app tutorial. have set there spinner in toolbar calls sortmovies(string sortby) method in mainactivityfragment. sortmovies() calls getmoviestask.execute(sortby).

when run program, works out fine. displays gridview of movie posters sorted popularity have called in oncreateview() of mainactivityfragment.

however, when click spinner , choose sort "highest rated" executes getmoviestask.execute (i checked json being returned), when gets time set gridview adapter, saying gridview null.

here mainactivity:

public class mainactivity extends appcompatactivity {  final string sort_popularity = "popularity.desc"; final string sort_highest_rated = "vote_average.desc";  @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main);      spinner spinner = (spinner) findviewbyid(r.id.spinner_sort_by);      arrayadapter spinneradapter = arrayadapter.createfromresource(this,             r.array.spinner_sort_options,             r.layout.simple_spinner_layout_item);      spinner.setadapter(spinneradapter);     spinneradapter.setdropdownviewresource(r.layout.simple_spinner_dropdown_item);     spinner.setselection(0, false);     spinner.setonitemselectedlistener(new adapterview.onitemselectedlistener() {         @override         public void onitemselected(adapterview<?> parent, view view, int position, long id) {              mainactivityfragment mainactivityfragment;             mainactivityfragment = new mainactivityfragment();              switch (position) {                 case 0:                     mainactivityfragment.sortmovies(sort_popularity);                     break;                 case 1:                     mainactivityfragment.sortmovies(sort_highest_rated);                     break;             }         }          @override         public void onnothingselected(adapterview<?> parent) {              // need nothing here         }     });      toolbar toolbar = (toolbar) findviewbyid(r.id.toolbar);     setsupportactionbar(toolbar);  }  @override public boolean oncreateoptionsmenu(menu menu) {     // inflate menu; adds items action bar if present.     getmenuinflater().inflate(r.menu.menu_main, menu);     return true; }  @override public boolean onoptionsitemselected(menuitem item) {     // handle action bar item clicks here. action bar     // automatically handle clicks on home/up button, long     // specify parent activity in androidmanifest.xml.     int id = item.getitemid();      //noinspection simplifiableifstatement     if (id == r.id.action_settings) {         return true;     }      return super.onoptionsitemselected(item); } } 

here mainactivityfragment:

public class mainactivityfragment extends fragment {  view rootview; gridview gridview; list<movie> movies = new arraylist<>();  public mainactivityfragment(){  }  @override public view oncreateview(layoutinflater inflater, viewgroup container,                          bundle savedinstancestate) {      rootview = inflater.inflate(r.layout.fragment_main, container, false);     gridview = (gridview) rootview.findviewbyid(r.id.gridview);      getmoviestask getmoviestask = new getmoviestask();     getmoviestask.execute("popularity.desc");      return rootview; }  @override public void onstart() {     super.onstart();    // getmoviestask getmoviestask = new getmoviestask();    // getmoviestask.execute();  }  public void sortmovies(string sortby) {      getmoviestask getmoviestask =  new getmoviestask();     getmoviestask.execute(sortby); }  public class getmoviestask extends asynctask<string, void, string[]> {       @override     protected string[] doinbackground(string... params) {          httpurlconnection urlconnection = null;         bufferedreader reader = null;         string sortby = params[0];         //contains json result         string moviesjson = null;          try {              final string api_base_url = "http://api.themoviedb.org/3/discover/movie?";             final string api_key = "b96087f4a03b686eaf542c5df8037005";             final string api_key_param = "api_key";             final string api_page = "page";             final string api_sort_by = "sort_by";              uri apiuri = uri.parse(api_base_url).buildupon()                     .appendqueryparameter(api_sort_by, sortby)                     .appendqueryparameter(api_page, "1")                     .appendqueryparameter(api_key_param, api_key)                     .build();              url url = new url(apiuri.tostring());              urlconnection = (httpurlconnection) url.openconnection();             urlconnection.setrequestmethod("get");             urlconnection.connect();             inputstream inputstream = urlconnection.getinputstream();             stringbuffer buffer = new stringbuffer();               if (inputstream == null) {                 moviesjson = null;             }else {                 reader = new bufferedreader(new inputstreamreader(inputstream));             }              string line;             while ((line = reader.readline()) != null) {                 buffer.append(line);             }              if (buffer.length() == 0) {                 moviesjson = null;             }              ////////////////////////////////////////////////////             //////////return json string containing movies////////////             moviesjson = buffer.tostring();          } catch (malformedurlexception e1) {             e1.printstacktrace();         } catch (ioexception e1) {             e1.printstacktrace();         } catch (networkonmainthreadexception e) {             log.d("error: ", e.tostring());         }          try {             return getmoviesfromjson(moviesjson);         } catch (jsonexception e) {             e.printstacktrace();         }          return null;     }      @override     protected void onpostexecute(string[] jsonmoviedata) {          if (jsonmoviedata != null) {             try {                 gridview.setadapter(new imageadapter(getcontext(), jsonmoviedata));                 gridview.setonitemclicklistener(new adapterview.onitemclicklistener() {                     public void onitemclick(adapterview<?> parent, view v,                                             int position, long id) {                          //pass movie detail activity                         intent = new intent(getactivity(), moviedetail.class);                         i.putextra("movie", movies.get(position));                         startactivity(i);                      }                 });             } catch (nullpointerexception e) {                 e.printstacktrace();             }          } else          {             toast.maketext(getcontext(), "nothing show :(",                     toast.length_long).show();         }      }          }       private string[] getmoviesfromjson(string jsonmoviedata) throws jsonexception {          //json object(s) extracted         final string tmdb_poster = "poster_path";         final string tmdb_original_title = "original_title";         final string tmdb_overview = "overview";         final string tmdb_vote_count = "vote_count";         final string tmdb_vote_average = "vote_average";         final string tmdb_backdrop = "backdrop_path";         final string tmdb_base_poster_path = "http://image.tmdb.org/t/p/w500/";         final string tmdb_results = "results";         final string tmdb_id = "id";          jsonobject moviesjson = new jsonobject(jsonmoviedata);         jsonarray moviesarray = moviesjson.getjsonarray(tmdb_results);          string[] posterpaths = new string[moviesarray.length()];           // extract movie data , build movie objects         for(int = 0; < moviesarray.length(); i++) {             movie movie = new movie();             jsonobject moviejson = moviesarray.getjsonobject(i);             movie.posterpath = tmdb_base_poster_path + moviejson.optstring(tmdb_poster).tostring();             posterpaths[i] = movie.posterpath;             movie.title = moviejson.optstring(tmdb_original_title).tostring();             movie.description = moviejson.optstring(tmdb_overview).tostring();             movie.title = moviejson.optstring(tmdb_original_title).tostring();             movie.backdrop = moviejson.optstring(tmdb_backdrop).tostring();             movie.voteaverage = moviejson.optstring(tmdb_vote_average).tostring();             movie.numofvotes = moviejson.optstring(tmdb_vote_count).tostring();             movies.add(movie);          }          return posterpaths;     } } 

as stated, when app loads, images load in gridview fine, when select 1 of spinners, in onpostexecute says:

02-02 16:03:13.323 19412-19412/com.ferr3t.don.gurumovies w/system.err: java.lang.nullpointerexception: attempt invoke virtual method 'void android.widget.gridview.setadapter(android.widget.listadapter)' on null object reference 02-02 16:03:13.333 19412-19412/com.ferr3t.don.gurumovies w/system.err:     @ com.ferr3t.don.gurumovies.mainactivityfragment$getmoviestask.onpostexecute(mainactivityfragment.java:161) 

i'm sure there simple solution overlooking, after 2 straight days, i've turned stackoverflow...any appreciated.

instead of creating new fragment mainactivityfragment mainactivityfragment; mainactivityfragment = new mainactivityfragment();

you should find existing fragment in current activity. when create new 1 fragment has not attached activity createview() method not called yet causing null pointer exception.

to find existing fragment:

get displayed fragment


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -