title: How to refresh GridView for Custom Image Adapter?
body: <p>I am currently working on an online android learning project and am facing issue with refreshing my grid view.</p>
  
  <p>My app displays a grid with several images initially. On click of the <strong>Refresh Button</strong> from the Menu, the GridView should be populated with the new images.Also,on click of any image, app goes to Detail Activity which shows the current image URL.</p>
  
  <p>Currently I first populate the GridView with sample images, using my custom adapter &amp; Picasso. Then an AsyncTask executes which gets the new image URLs from a JSON. This new imageURL List has to be fed to my adapter so that the grid displays the new images.</p>
  
  <p>However, I am not able to accomplish this. My initial grid shows images and on click of these, I get their URL on detail activity screen as expected. However, when I click on the <strong>Refresh</strong> in the menu, I don't see the new images. I am trying to set the adapter with the updated URL array in the onPostExecute().</p>
  
  <p>On click of the old image I see the new URL in the detail activity, however once I click back the image is still not updated and URL changes back to the old one. Sometimes when I scroll the new image shows up and then app crashes. </p>
  
  <p>So the basic issue is that even after getting the new URLs, I am unable to populate the GridView with new images. Any help on this will be appreciated. Thanks,</p>
  
  <p>Code Snippet:</p>
  
  <pre><code>public class MovieListFragment extends Fragment {
  public CustomAdapter customAdapter;
  public GridView gv;
  public List&lt;String&gt; allImages=new ArrayList&lt;String&gt;();
  public List&lt;String&gt; newImages=new ArrayList&lt;String&gt;();
  public String LOG_TAG=MovieListFragment.class.getSimpleName();
  public int abc=0;
  public MovieListFragment() {
  }
  
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
      View rootview= inflater.inflate(R.layout.movie_list_fragment, container, false);
  
  
      //Fake Data Creation for 1st time GridView load.
      allImages.add("http://www.pnas.org/site/misc/images/15-01065.500.jpg");
      allImages.add("http://41.media.tumblr.com/78335e84b3b353ad60c335b24a5f267e/tumblr_nz2bke3fJ51rldeoho1_500.jpg");
      allImages.add("http://41.media.tumblr.com/78335e84b3b353ad60c335b24a5f267e/tumblr_nz2bke3fJ51rldeoho1_500.jpg");
      allImages.add("http://41.media.tumblr.com/78335e84b3b353ad60c335b24a5f267e/tumblr_nz2bke3fJ51rldeoho1_500.jpg");
      allImages.add("http://41.media.tumblr.com/78335e84b3b353ad60c335b24a5f267e/tumblr_nz2bke3fJ51rldeoho1_500.jpg");
      allImages.add("http://www.pnas.org/site/misc/images/15-01065.500.jpg");
      allImages.add("http://www.pnas.org/site/misc/images/15-01065.500.jpg");
      allImages.add("http://www.pnas.org/site/misc/images/15-01065.500.jpg");
      allImages.add("http://www.pnas.org/site/misc/images/15-01065.500.jpg");
  
      //Set Adapter
      gv = (GridView) rootview.findViewById(R.id.gridview);
      customAdapter=new CustomAdapter(getActivity(),allImages);
      gv.setAdapter(customAdapter);
  
      //On Click Listener
      gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
              Intent intent = new Intent(getActivity(), DetailActivity.class);
              intent.putExtra("imageURL", allImages.get(position).toString());
              startActivity(intent);
          }
      });
  
      return rootview;
  }
  
  //My Custom Adapter
  public class CustomAdapter extends BaseAdapter{
  
      private Context mContext;
      private List&lt;String&gt; myImageList;
  
      public CustomAdapter(Context c, List&lt;String&gt; finalImageList) {
  
         mContext = c;
         myImageList=finalImageList;
         notifyDataSetChanged();
     }
  
     @Override
     public int getCount() {
         return myImageList.size();
     }
  
     @Override
     public Object getItem(int position) {
         return myImageList.get(position);
     }
  
     @Override
     public long getItemId(int position) {
         return 0;
     }
  
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
  
         ImageView imageView;
         if (convertView == null) {
             // if it's not recycled, initialize some attributes
             imageView = new ImageView(mContext);
             imageView.setLayoutParams(new GridView.LayoutParams(500, 500));
             imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
           //  imageView.setPadding(2, 2, 2, 2);
         } else {
             imageView = (ImageView) convertView;
         }
  
         Picasso.with(getActivity())
                 .load(myImageList.get(position))
                 .into(imageView);
  
         return imageView;
     }
  </code></pre>
  
  <p>}</p>
  
  <pre><code>@Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
      inflater.inflate(R.menu.movie_list_fragment_menu, menu);
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      int id=item.getItemId();
      if(id==R.id.action_refresh){
          updateMovieList();
          return true;
      }
  
      return super.onOptionsItemSelected(item);
  }
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setHasOptionsMenu(true);
  }
  
  private void updateMovieList() {
      FetchMovieDetailsTask fetchMovieDetailsTask=new FetchMovieDetailsTask();
      fetchMovieDetailsTask.execute("Popularity");
  }
  
  public class FetchMovieDetailsTask extends AsyncTask&lt;String, Void, String[]&gt;{
      public String LOG_TAG_SECOND=FetchMovieDetailsTask.class.getSimpleName();
  
  
      @Override
      protected String[] doInBackground(String... params) {
  
          HttpURLConnection urlConnection = null;
          BufferedReader reader = null;
  
          // Will contain the raw JSON response as a string.
          String movieDetailJsonStr = "";
          String filterType = "";
          String api_key = "e77c4d231a4c24ffe0357b694751910c";
  
          if (params[0].equals("Popularity")) {
              filterType = "vote_average.desc";
          } else if (params[0].equals("Rating")) {
              filterType = "popularity.desc";
          }
  
          try {
  
              final String MOVIEDETAIL_BASE_URL = "https://api.themoviedb.org/3/discover/movie?";
              final String FILTER_PARAM = "sort_by";
              final String APP_KEY_PARAM = "api_key";
  
              Uri builtUri = Uri.parse(MOVIEDETAIL_BASE_URL).buildUpon()
                      .appendQueryParameter(FILTER_PARAM, filterType)
                      .appendQueryParameter(APP_KEY_PARAM, api_key).build();
  
  
              URL url = new URL(builtUri.toString());
              Log.v(LOG_TAG_SECOND, builtUri.toString());
  
              urlConnection = (HttpURLConnection) url.openConnection();
              urlConnection.setRequestMethod("GET");
              urlConnection.connect();
  
              // Read the input stream into a String
              InputStream inputStream = urlConnection.getInputStream();
              StringBuffer buffer = new StringBuffer();
              if (inputStream == null) {
                  // Nothing to do.
                  return null;
              }
              reader = new BufferedReader(new InputStreamReader(inputStream));
  
              String line;
              while ((line = reader.readLine()) != null) {
  
                  buffer.append(line + "\n");
              }
  
              if (buffer.length() == 0) {
                  // Stream was empty.  No point in parsing.
                  return null;
              }
              movieDetailJsonStr = buffer.toString();
              Log.v(LOG_TAG_SECOND, " Movie Details JSON " + movieDetailJsonStr);
  
              try {
                  getMovieDetailsFromJSON(movieDetailJsonStr);
              } catch (JSONException e) {
                  e.printStackTrace();
              }
  
  
          } catch (IOException e) {
              Log.e(LOG_TAG, "Error ", e);
              return null;
  
          } finally {
              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;
      }
  
  
      private String[] getMovieDetailsFromJSON(String movieDetailsJSON) throws JSONException{
  
          final String MOV_TITLE = "title";
          final String MOV_OVERVIEW = "overview";
          final String MOV_RATING = "vote_average";
          final String MOV_POSTER_PATH = "poster_path";
  
          final String MOV_LIST = "results";
  
          JSONObject movieListJSON = new JSONObject(movieDetailsJSON);
          JSONArray movieListArray = movieListJSON.getJSONArray(MOV_LIST);
  
          int numOfMovies=8;
          allImages.clear();
          String[] resultStrs = new String[numOfMovies];
          String[] resultPosters= new String[numOfMovies];
  
          for(int i=0; i&lt;numOfMovies; i++){
  
              String title;
              String overview;
              String rating;
              String poster_path;
  
              JSONObject movieDetails=movieListArray.getJSONObject(i);
  
              overview=movieDetails.getString(MOV_OVERVIEW);
              title=movieDetails.getString(MOV_TITLE);
              rating=movieDetails.getString(MOV_RATING);
              poster_path=movieDetails.getString(MOV_POSTER_PATH);
  
              resultStrs[i]=title + "\n" + overview + "\n" + rating + "\n" + poster_path;
              resultPosters[i]=poster_path;
              makePosterURL(resultPosters[i]);
  
  
          }
  
          for (String s : resultStrs) {
              Log.v(LOG_TAG_SECOND, "MOVIE DETAILS: " + s);
          }
          return resultStrs;
  
  
      }
  
      private void makePosterURL(String resultPoster) {
          String baseURL="http://image.tmdb.org/t/p/w500";
          //resultPoster=resultPoster.replace("\\", "");
          String finalURL="";
          finalURL=baseURL+resultPoster;
          Log.v(LOG_TAG_SECOND, "Final Poster URL " + finalURL);
          allImages.add(finalURL);
      }
  
      @Override
      protected void onPostExecute(String[] strings) {
          if(strings!=null){
              customAdapter=new CustomAdapter(getActivity(), allImages);
              gv.invalidateViews();
              gv.setAdapter(customAdapter);
          }
         // super.onPostExecute(strings);
      }
  }
  </code></pre>