1

I am new to android. I am trying to make a wallpaper app and for that I am showing different categories of images in different fragments in tab layout. I am stuck in Adapter. When I try send the clicked image from the fragment to new Activity, it crashes. But if I comment the the line 'intent.putExtra' it loads the new Activity. Please help, I cant figure out what's the problem.

Here is my WallpaperAdapter.java

public class WallpaperAdapter extends RecyclerView.Adapter<WallpaperViewHolder> {
private Fragment6 context;
private List<WallpaperModel> wallpaperModelList;
private OnImageItemClickListener imageItemClickListener;



public WallpaperAdapter(Fragment6 context, List<WallpaperModel> wallpaperModelList) {
    this.context = context;
    this.wallpaperModelList = wallpaperModelList;
}

@NonNull
@Override
public WallpaperViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.image_item,parent,false);
        WallpaperViewHolder wallpaperViewHolder= new WallpaperViewHolder(view);
        return new WallpaperViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull WallpaperViewHolder holder, int position) {
    Glide.with(context).load(wallpaperModelList.get(position).getMediumUrl()).into(holder.imageView);


}

@Override
public int getItemCount() {
    return wallpaperModelList.size();
}

public interface OnImageItemClickListener {
    public void onImageClicked(WallpaperModel wallpaperModel);
}

}

class WallpaperViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
View view;
ImageView imageView;
private List<WallpaperModel> wallpaperModelList;


public WallpaperViewHolder(@NonNull View itemView) {
    super(itemView);
    imageView = itemView.findViewById(R.id.itemImage);
    view=itemView.findViewById(R.id.imageItemLayout);

    view.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    int position = getAdapterPosition();
    Toast.makeText(v.getContext(), "Image Clicked", Toast.LENGTH_SHORT).show();
    Intent intent= new Intent(v.getContext(),Fullscreen.class);
    //intent.putExtra("original",wallpaperModelList.get(position).getOriginalUrl());
    v.getContext().startActivity(intent);


}

}

And here is my Fragment6.java

public class Fragment6 extends Fragment implements WallpaperAdapter.OnImageItemClickListener{
RecyclerView recyclerView;
WallpaperAdapter wallpaperAdapter;
List<WallpaperModel> wallpaperModelList;

int pageNumber=1;
Boolean isScrolling= false;
int currentItem,totalItems,scrollOutItems;



String natureUrl="URL";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.fragment_6, container, false);
    recyclerView=view.findViewById(R.id.recyclerView);

    wallpaperModelList= new ArrayList<>();
    wallpaperAdapter = new WallpaperAdapter(this,wallpaperModelList);

    recyclerView.setAdapter(wallpaperAdapter);

    GridLayoutManager gridLayoutManager= new GridLayoutManager(getContext(),2);
    recyclerView.setLayoutManager(gridLayoutManager);

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if(newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){
                isScrolling= true;
            }
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            currentItem = gridLayoutManager.getChildCount();
            totalItems = gridLayoutManager.getItemCount();
            scrollOutItems = gridLayoutManager.findFirstVisibleItemPosition();

            if(isScrolling && (currentItem+scrollOutItems==totalItems)){
                isScrolling = false;
                fetchWallpaper();
            }
        }
    });
    fetchWallpaper();

    return view;
}

 private void fetchWallpaper() {



    StringRequest request= new StringRequest(Request.Method.GET, natureUrl, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            //On response
            try {
                JSONObject jsonObject= new JSONObject(response);

                JSONArray jsonArray= jsonObject.getJSONArray("photos");

                int length=jsonArray.length();
                for(int i= 0;i<length;i++)
                {
                    JSONObject object= jsonArray.getJSONObject(i);
                    int id=object.getInt("id");
                    JSONObject objectImages = object.getJSONObject("src");
                    String originalUrl= objectImages.getString("original");
                    String mediumUrl= objectImages.getString("medium");

                    WallpaperModel wallpaperModel= new WallpaperModel(id,originalUrl,mediumUrl);
                    wallpaperModelList.add(wallpaperModel);


                }

                wallpaperAdapter.notifyDataSetChanged();
                pageNumber++;

            }catch (JSONException e){

            }

        }}, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //On error response

        }}){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            params.put("Authorization","key");


            return params;

        }
    };

    RequestQueue requestQueue= Volley.newRequestQueue(getContext());
    requestQueue.add(request);
}

@Override
public void onImageClicked(WallpaperModel wallpaperModel) {


}

}

Shrawan77
  • 41
  • 1
  • It's very difficult to debug a crash without a stack trace. See [Unfortunately MyApp has stopped. How can I solve this?](/q/23353173) for Android-specific advice, and [What is a stack trace, and how can I use it to debug my application errors?](/q/3988788) for advice on what to do once you have the stack trace. If you still need help, edit your question to include the **complete stack trace**, as well as **which line of your code** the stack trace points to. – Ryan M May 24 '21 at 23:23

1 Answers1

0

Can you show what error you are getting?

It is always better not to handle the click events directly within the view holder since you might need to do something else other than opening an activity after item click, there is another concrete way through which you can achieve the same. i.e by using interfaces.

I can see that you have created the click interface but did not use it.The issue is you have made the OnImageItemClickListener interface and implemented it in the fragment but you have not invoked the interface at any place, you did create the click listener interface as param in the adapter but you did not pass the instance of the interface to the adapter and also you did not pass it to its view holder. Because you must invoke it from the view holder to get it called in the fragment.

Follow the below steps to achieve this.

  1. You must pass the instance of the item click interface to the adapter and then from the adapter to its view holder.

edit the existing line of adapter creation to this

wallpaperAdapter = new WallpaperAdapter(this,wallpaperModelList,this);
  1. Now on the click listener of the button in the view holder you must make use of that interface instance to invoke the item click function of the interface. While you pass any of the data from the view holder through the interface to your activity.

  2. Meanwhile in the activity or fragment you will handle the item click through the implemented interface i.e onImageClicked() which will get called when you invoke it from the view holder.

     @Override
     public void onImageClicked(WallpaperModel wallpaperModel)
     {
      //start the activity from here.
     }
    
thebadassdev
  • 156
  • 9