Same Image is getting Displayed

I have used Picasso library to display image.Everything is working fine and i am able to retrieve images from Flickr.The problem is all my imageview displays the same image? Please help
Thanks in advance

How are you loading the image? Can you share some code?

Below is the complete Code.I have used Picasso library to load the images.Some of the code i implemented is different from the book.
activity_main has a FrameLayout with id ,@+id/framelayout
list_item.xml has a ImageView with id ,@+id,imageview

fragment_photo_gallery.xml
RecyclerView and ProgressBar are in RelativeLayout

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:id="@+id/recyclerview"
    android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

<ProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/loading_indicator"
    style="@style/Widget.AppCompat.ProgressBar"
    android:layout_centerInParent="true"/>


FlickrFetchr.java
package pritish.sawant.com.photogallery;

import android.net.Uri;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**

  • Created by pritish on 11/7/17.
    */

public class FlickrFetchr {

private static final String TAG="TAG";
private static final String APIKEY="ed3b5852446a5a06ba8b81b6df09ce0a";
private static final String FETCH_RECENT_METHODS="flickr.photos.getRecent";
private static final String SEARCH_METHOD="flickr.photos.search";
private static final Uri ENDPOINT=Uri.parse("https://api.flickr.com/services/rest/")
        .buildUpon()
        .appendQueryParameter("api_key", APIKEY)
        .appendQueryParameter("format", "json")
        .appendQueryParameter("nojsoncallback", "1")
        .appendQueryParameter("extras", "url_s")
        .build();

public static String getData(String url){
    BufferedReader bufferedReader=null;
    try {
        URL url1=new URL(url);
        HttpURLConnection httpURLConnection=(HttpURLConnection)url1.openConnection();
        StringBuilder stringBuilder=new StringBuilder();
        bufferedReader=new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        String line;
        while ((line=bufferedReader.readLine())!=null){
            stringBuilder.append(line+"\n");
        }
        return stringBuilder.toString();

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    finally {
        if(bufferedReader!=null){
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}

private String buildURL(String method,String query){
    Uri.Builder builder=ENDPOINT.buildUpon().appendQueryParameter("method",method);
    if(method.equals(SEARCH_METHOD)){
        builder.appendQueryParameter("text",query);

    }
    return builder.build().toString();
}

public List<GalleryItem> fetchRecentPhotos(){
    String url=buildURL(FETCH_RECENT_METHODS,null);
    return downloadGalleyItem(url);
}

public List<GalleryItem> searchPhotos(String query){
    String url=buildURL(SEARCH_METHOD,query);
    return downloadGalleyItem(url);
}

//To receive the json format
public List<GalleryItem> downloadGalleyItem(String url){
    ArrayList<GalleryItem> galleryItemsList=new ArrayList<>();

    String jsonString=getData(url);

    try {
        JSONObject jsonObject=new JSONObject(jsonString);
        JSONObject jsonObjectphotos=jsonObject.getJSONObject("photos");
        JSONArray jsonArrayphoto=jsonObjectphotos.getJSONArray("photo");

        GalleryItem galleryItem=new GalleryItem();
        for(int i=0;i<jsonArrayphoto.length();i++){
            JSONObject jsonObject1=jsonArrayphoto.getJSONObject(i);
            galleryItem.setId(jsonObject1.getString("id"));
            galleryItem.setCaption(jsonObject1.getString("title"));

            if(!jsonObject1.has("url_s")){
                continue;

            }
            galleryItem.setUrl(jsonObject1.getString("url_s"));
            galleryItemsList.add(galleryItem);
        }


    } catch (Exception e) {
        e.printStackTrace();
    }


  return galleryItemsList;
}

}

GalleryItem.java
package pritish.sawant.com.photogallery;

/**

  • Created by pritish on 11/7/17.
    */

public class GalleryItem {

private String caption,Id,url;

public String getCaption() {
    return caption;
}

public void setCaption(String caption) {
    this.caption = caption;
}

public String getId() {
    return Id;
}

public void setId(String id) {
    Id = id;
}

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

@Override
public String toString() {
    return caption;
}

}

MainActivity.java
package pritish.sawant.com.photogallery;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setTitle("Photo Gallery");
    fragmentManager=getSupportFragmentManager();
    Fragment fragment=fragmentManager.findFragmentById(R.id.framelayout);
    if(fragment==null){
        fragment=new PhotoGalleryFragment();
        fragmentManager.beginTransaction().add(R.id.framelayout,fragment).commit();
    }
}

}

PhotoGalleryFragment.java
package pritish.sawant.com.photogallery;

import android.os.AsyncTask;
import android.os.Bundle;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**

  • A simple {@link Fragment} subclass.
    */
    public class PhotoGalleryFragment extends Fragment {

    private RecyclerView recyclerView;
    public ProgressBar progressBar;
    public List galleryItems=new ArrayList<>();

    public static PhotoGalleryFragment newInstance(){
    return new PhotoGalleryFragment();
    }

    public PhotoGalleryFragment() {
    // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    setHasOptionsMenu(true);
    updateItems();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // Inflate the layout for this fragment

     View view=inflater.inflate(R.layout.fragment_photo_gallery, container, false);
     progressBar=(ProgressBar)view.findViewById(R.id.loading_indicator);
     recyclerView=(RecyclerView)view.findViewById(R.id.recyclerview);
    
     recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
    
     progressBar.setVisibility(View.GONE);
     setUpAdapter();
     return view;
    

    }

    private void setUpAdapter(){
    //isAdded checks whether fragment has been added to the activity
    if(isAdded()){
    recyclerView.setAdapter(new PhotoAdapter(galleryItems));
    }
    }

    private class PhotoHolder extends RecyclerView.ViewHolder{

     private ImageView imageView;
    
     public PhotoHolder(View itemView) {
         super(itemView);
         imageView=(ImageView) itemView.findViewById(R.id.imageview);
     }
    
     public void bindItems(GalleryItem galleryItem){
    
         Picasso.with(getActivity()).load(galleryItem.getUrl()).into(imageView);
     }
    

    }

    private class PhotoAdapter extends RecyclerView.Adapter{

     private List<GalleryItem> galleryItems;
    
     public PhotoAdapter(List<GalleryItem> galleryItems) {
         this.galleryItems = galleryItems;
     }
    
     @Override
     public PhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         LayoutInflater layoutInflater=LayoutInflater.from(getActivity());
         View view=layoutInflater.inflate(R.layout.list_item,parent,false);
    
         return new PhotoHolder(view);
     }
    
     @Override
     public void onBindViewHolder(PhotoHolder holder, int position) {
         GalleryItem galleryItem=galleryItems.get(position);
         holder.bindItems(galleryItem);
     }
    
     @Override
     public int getItemCount() {
         return galleryItems.size();
     }
    

    }

    private class FetchTask extends AsyncTask<Void,Void,List>{

     private String query;
    
     public FetchTask(String query) {
         this.query = query;
     }
    
     @Override
     protected void onPreExecute() {
         super.onPreExecute();
        /* if(galleryItems.size()==0){
             progressBar.setVisibility(View.VISIBLE);
         }*/
     }
    
     @Override
     protected List<GalleryItem> doInBackground(Void... params) {
    
         if(query==null){
             return new FlickrFetchr().fetchRecentPhotos();
         }else{
             return new FlickrFetchr().searchPhotos(query);
         }
     }
    
     @Override
     protected void onPostExecute(List<GalleryItem> galleryItems1) {
         super.onPostExecute(galleryItems);
         progressBar.setVisibility(View.GONE);
         galleryItems=galleryItems1;
         setUpAdapter();
     }
    

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_main,menu);
    MenuItem menuItem=menu.findItem(R.id.searchview);
    final SearchView searchView=(SearchView)menuItem.getActionView();

     searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
         @Override
         public boolean onQueryTextSubmit(String query) {
             QueryPrefernces.setQuery(getActivity(),query);
             searchView.onActionViewCollapsed();
             updateItems();
             return true;
         }
    
         @Override
         public boolean onQueryTextChange(String newText) {
             return false;
         }
     });
    
     searchView.setOnSearchClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             //If there is a value in SharedPrefernce and you open the app and click on Searchview that value should be displayed
             String value=QueryPrefernces.getQuery(getActivity());
             searchView.setQuery(value,false);
         }
     });
    

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
    case R.id.clearview:
    QueryPrefernces.setQuery(getActivity(),null);
    updateItems();
    return true;
    default:
    return super.onOptionsItemSelected(item);
    }

    }

    public void updateItems(){
    String query=QueryPrefernces.getQuery(getActivity());
    new FetchTask(query).execute();
    }
    }


QueryPrefernces.java
package pritish.sawant.com.photogallery;

import android.content.Context;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.RequiresApi;

/**

  • Created by pritish on 15/7/17.
    */

public class QueryPrefernces {

//SharedPrefernce is used so that whatever you type in search is saved and when you reopen the app photos
//related to that search is displayed
private static final String SearchQuery="SearchQuery";


public static String getQuery(Context context){
    return PreferenceManager.getDefaultSharedPreferences(context).getString(SearchQuery,null);
}

public static void setQuery(Context context,String query){
     PreferenceManager.getDefaultSharedPreferences(context).edit()
            .putString(SearchQuery,query).apply();
}

}

output

I don’t see any obvious problem in your code. You should set a breakpoint on the line of code where you send a url to Picasso and use the debugger. At that breakpoint, take a look at the URL that you are giving to Picasso and see if it is the same each time and where it comes from (how is it set?).

I used debugger.It is using same url.How should it avaoid it?

So, use the debugger a step further and see when the url is getting set. Take a look at when the URL is set on the GalleryItem object and that should be the source of your problem.

Got it.Thanks alot for the help.