android - Gridview displaying infinite repeating item -


when load app should display 20 movie poster in 2 column 10 row gridview. reason when keep scrolling keep loading same 20 posters, pretty infinite scrolling. still new android development great!

movieadapter

public class movieadapter extends cursoradapter {     private final string log_tag = movieadapter.class.getsimplename();      public movieadapter(context context, cursor c, int flags){         super(context,c,flags);     }      private string convertcursorrowtouxformat(cursor cursor){         string poster = cursor.getstring(mainactivityfragment.col_movie_url);         return poster;     }       @override     public view newview(context context,cursor cursor,viewgroup parent){         view view = layoutinflater.from(context).inflate(r.layout.poster_image, parent, false);         return view;     }      @override     public void bindview(view view, context context, cursor cursor) {           final string posterimage_base_url = "http://image.tmdb.org/t/p/";         final string posterimage_size = "w500";          imageview posterimage = (imageview)view;         final string posterimage_url = posterimage_base_url + posterimage_size + convertcursorrowtouxformat(cursor);          picasso.with(context).load(posterimage_url).into(posterimage);         log.v(log_tag, "poster urls: " + posterimage_url);       }  } 

mainactivityfragment

public class mainactivityfragment extends fragment implements loadermanager.loadercallbacks<cursor>{     private static final int movie_loader = 0;      private final string log_tag = mainactivityfragment.class.getsimplename();      private static final string[] movie_columns = { //            moviecontract.movieentry.table_name + "." +             moviecontract.movieentry._id,             moviecontract.movieentry.column_movie_poster     };      static final int col_movie_id = 0;     static final int col_movie_url = 1;      private movieadapter mmovieadapter;      public mainactivityfragment() {     }      @override     public view oncreateview(layoutinflater inflater, viewgroup container,                              bundle savedinstancestate) {          mmovieadapter = new movieadapter(getactivity(),null,0);          final view rootview = inflater.inflate(r.layout.fragment_main, container, false);          gridview gridview = (gridview) rootview.findviewbyid(r.id.movieposter_image_gridview);         gridview.setadapter(mmovieadapter);         gridview.setonitemclicklistener(new adapterview.onitemclicklistener(){             @override             public void onitemclick(adapterview<?> adapterview, view view, int position, long l){                 cursor cursor = (cursor)adapterview.getitematposition(position);                 if(cursor != null) {                     intent intent = new intent(getactivity(), detailactivity.class)                             .setdata(moviecontract.movieentry.content_uri);                  startactivity(intent);                     log.d("debug", "selected item position " + position + ", id: " + l);                 }             }         });           return rootview;     }      @override     public void onactivitycreated(bundle savedinstancestate){         getloadermanager().initloader(movie_loader, null, this);         super.onactivitycreated(savedinstancestate);     }      private void updateapplication() {          fetchmovietask movietask = new fetchmovietask(getactivity());                 sharedpreferences prefs = preferencemanager.getdefaultsharedpreferences(getactivity());         string sortby = prefs.getstring(getstring(r.string.pref_sort_by_key),                 getstring(r.string.pref_popular_default));         movietask.execute(sortby);     }      @override     public void onstart() {         super.onstart();         updateapplication();      }      @override     public loader<cursor> oncreateloader(int i, bundle bundle){         uri movieuri = moviecontract.movieentry.content_uri;          return new cursorloader(getactivity(),         movieuri,         movie_columns,         null,         null,         null);     }      @override     public void onloadfinished(loader<cursor> cursorloader, cursor cursor){         mmovieadapter.swapcursor(cursor);     }      @override     public void onloaderreset(loader<cursor> cursorloader){         mmovieadapter.swapcursor(null);     }      } 

fetchmovietask

public class fetchmovietask extends asynctask<string, void, void> {      private final string log_tag = fetchmovietask.class.getsimplename();       private final context mcontext;      public fetchmovietask(context context) {         mcontext = context;     }      private boolean debug = true;      private void getmoviedatajson(string moviejsonstr, int result)             throws jsonexception {          final string mdb_result = "results";         final string mdb_poster = "poster_path";         final string mdb_movie_title = "original_title";         final string mdb_movie_plot = "overview";         final string mdb_movie_rating = "popularity";         final string mdb_release_date = "release_date";          try {             jsonobject moviejson = new jsonobject(moviejsonstr);             jsonarray moviearray = moviejson.getjsonarray(mdb_result);              vector<contentvalues> cvvector = new vector<>(moviearray.length());              (int = 0; < moviearray.length(); i++) {                 string poster;                 string title;                 string plot;                 string rating;                 string releasedate;                   //get thejson object representing movie                 jsonobject moviedetail = moviearray.getjsonobject(i);                  poster = moviedetail.getstring(mdb_poster);                 title = moviedetail.getstring(mdb_movie_title);                 plot = moviedetail.getstring(mdb_movie_plot);                 rating = moviedetail.getstring(mdb_movie_rating);                 releasedate = moviedetail.getstring(mdb_release_date);                  contentvalues moviedetailvalues = new contentvalues();                 moviedetailvalues.put(moviecontract.movieentry.column_movie_name, title);                 moviedetailvalues.put(moviecontract.movieentry.column_movie_poster, poster);                 moviedetailvalues.put(moviecontract.movieentry.column_movie_plot, plot);                 moviedetailvalues.put(moviecontract.movieentry.column_movie_rating, rating);                 moviedetailvalues.put(moviecontract.movieentry.column_movie_redate, releasedate);                  cvvector.add(moviedetailvalues);             }             int inserted = 0;              if (cvvector.size() > 0) {                 contentvalues[] cvarray = new contentvalues[cvvector.size()];                 cvvector.toarray(cvarray);                  inserted = mcontext.getcontentresolver().bulkinsert(moviecontract.movieentry.content_uri, cvarray);             }              log.d(log_tag, "fetchmovietask complete. " + inserted + " inserted");             } catch (jsonexception e) {             log.e(log_tag, e.getmessage(), e);             e.printstacktrace();         }      }          @override         protected void doinbackground (string...params){              if (params.length == 0) {                 return null;             }              httpurlconnection urlconnection = null;             bufferedreader reader = null;              string moviejsonstr = null;             int result = 20;              try {                  final string movie_base_url = "http://api.themoviedb.org/3/movie";                  uri builturi = uri.parse(movie_base_url).buildupon()                         .appendpath(params[0])                         .appendqueryparameter("api_key", buildconfig.movie_api_key)                         .build();                  url url = new url(builturi.tostring());                  log.v(log_tag, "built uri " + builturi.tostring());                  urlconnection = (httpurlconnection) url.openconnection();                 urlconnection.setrequestmethod("get");                 urlconnection.connect();                  inputstream inputstream = urlconnection.getinputstream();                 stringbuffer buffer = new stringbuffer();                  if (inputstream == null) {                     return null;                 }                  reader = new bufferedreader(new inputstreamreader(inputstream));                  string line;                  while ((line = reader.readline()) != null) {                     buffer.append(line + "\n");                 }                  if (buffer.length() == 0) {                     return null;                 }                  moviejsonstr = buffer.tostring();                 getmoviedatajson(moviejsonstr, result);              } catch (ioexception e) {                 log.e(log_tag, "error ", e);             }                 catch(jsonexception e){                     log.e(log_tag, e.getmessage(), e);                     e.printstacktrace();              } {                 if (urlconnection != null) {                     urlconnection.disconnect();                 }                 if (reader != null) {                     try {                         reader.close();                     } catch (final ioexception e) {                         log.e(log_tag, "error closing stream", e);                     }                 }             }              return null;         }      } 

movieprovider

public class movieprovider extends contentprovider {      // uri matcher used content provider.     private static final urimatcher surimatcher = buildurimatcher();     private moviedbhelper mopenhelper;      static final int movie = 100;       static urimatcher buildurimatcher(){          final urimatcher matcher = new urimatcher(urimatcher.no_match);         final string authority = moviecontract.content_authority;          matcher.adduri(authority,moviecontract.path_movie, movie);          return matcher;     }      @override     public boolean oncreate(){         mopenhelper = new moviedbhelper(getcontext());         return true;     }      @override     public string gettype(uri uri){          final int match = surimatcher.match(uri);          switch (match){             case movie:                 return moviecontract.movieentry.content_type;             default:                 throw new unsupportedoperationexception(("unknown uri:" + uri));         }     }      @override     public cursor query(uri uri, string[] projection, string selection, string[] selectionargs,                         string sortorder) {          cursor retcursor;          switch (surimatcher.match(uri)){              case movie: {                 retcursor = mopenhelper.getreadabledatabase().query(                         moviecontract.movieentry.table_name,                         projection,                         selection,                         selectionargs,                         null,                         null,                         null                 );                 break;             }              default:                 throw new unsupportedoperationexception("unknown uri: " + uri);         }          retcursor.setnotificationuri(getcontext().getcontentresolver(),uri);         return retcursor;     }      @override     public uri insert(uri uri, contentvalues values) {         final sqlitedatabase db = mopenhelper.getwritabledatabase();         final int match = surimatcher.match(uri);         uri returnuri;          switch (match) {                  case movie: {                     long _id = db.insert(moviecontract.movieentry.table_name,null,values);                     if(_id > 0) //                        returnuri = moviecontract.movieentry.buildmovieuri(_id);                             returnuri = moviecontract.movieentry.content_uri;                     else                         throw new android.database.sqlexception("failed insert row " + uri);                     break;}               default:                 throw new unsupportedoperationexception("unknown uri: " + uri);         }         getcontext().getcontentresolver().notifychange(uri,null);         db.close();         return returnuri;         }      @override     public int delete(uri uri, string selection, string[] selectionargs) {         final sqlitedatabase db = mopenhelper.getwritabledatabase();         final int match = surimatcher.match(uri);         int rowsdeleted;          if (null == selection) selection = "1";         switch (match){              case movie:                 rowsdeleted = db.delete(moviecontract.movieentry.table_name,selection,selectionargs);                 break;             default:                 throw new unsupportedoperationexception("unknown uri: " + uri);         }          if (rowsdeleted != 0) {             getcontext().getcontentresolver().notifychange(uri,null);         }         return rowsdeleted;     }     @override     public int update(             uri uri, contentvalues values, string selection, string[] selectionargs) {         final sqlitedatabase db = mopenhelper.getwritabledatabase();         final int match = surimatcher.match(uri);         int rowsupdated;          switch (match){              case movie:                 rowsupdated= db.update(moviecontract.movieentry.table_name,values,selection,selectionargs);                 break;             default:                 throw new unsupportedoperationexception("unknown uri: " + uri);         }          if (rowsupdated != 0) {             getcontext().getcontentresolver().notifychange(uri,null);         }         return rowsupdated;     }      @override     public int bulkinsert(uri uri,contentvalues[] values) {         final sqlitedatabase db = mopenhelper.getwritabledatabase();         final int match = surimatcher.match(uri);         switch (match) {             case movie:                 db.begintransaction();                 int returncount = 0;                 try {                     (contentvalues value : values) {                         long _id = db.insert(moviecontract.movieentry.table_name,null,value);                         if(_id != -1) {                             returncount++;                         }                     }                     db.settransactionsuccessful();                 } {                     db.endtransaction();                 }                 getcontext().getcontentresolver().notifychange(uri,null);                 return returncount;             default:                 return super.bulkinsert(uri,values);         }     }      @override     @targetapi(11)     public void shutdown() {         mopenhelper.close();         super.shutdown();     }        } 

use recyclerview instead of gridview


Comments