Ad

Pass String From Adapter To Fragment Using Interface

This is question is based on this answer.

I'm trying to pass a string from my RecyclerView.Adapter to my fragment.

In my adapter I added the following:

onItemClickListner onItemClickListner;

public void setOnItemClickListner(VideoAdapter.onItemClickListner onItemClickListner) {
    this.onItemClickListner = onItemClickListner;
}

public interface onItemClickListner{
    void onClick(String str);//pass your object types.
}

I pass the following string once the amount of items in my adapter is less then one (adapter is empty):

onItemClickListner.onClick("TESTING");

Then, in my fragment I add the following:

//I do the following after setting my adapter
videoAdapter.setOnItemClickListner(new VideoAdapter.onItemClickListner() {
        @Override
        public void onClick(String str) {
            Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
        }
    });

For some reason the string is empty/null and the crash points to onItemClickListner.onClick("TESTING");.

Can someone please have a look and see what I might be doing wrong?


Edit:

I call onItemClickListner.onClick("TESTING"); inside my OnMenuItemClickListener as shown below:

popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {

                case R.id.delete:

                    onItemClickListner.onClick("TESTING");

                return true;

}

I did not provide my entire fragment because I just add the above inside onCreateView.

Ad

Answer

Firstly, thank you for all the answers and comments.

I fixed this issue by doing the following.


In my Adapter I added the following:

private UpdateInterface listner;

public interface UpdateInterface {
    void recyclerviewOnUpdate(int amount);
}

public VideoAdapter(Context context, ArrayList<PathModel> thumbPathList, ArrayList<PathModel> videoPathList, UpdateInterface listner) {
    this.context = context;
    this.thumbPathList = thumbPathList;
    this.videoPathList = videoPathList;
    //I added this
    this.listner=listner;
}

I call the interface the same way as I did in my question:

//Passing the amount of items in adapter
listner.recyclerviewOnUpdate(getItemCount());

It's very similar to what I've done above but now I implement the interface in my fragment like this:

public class VideoFragment extends Fragment implements VideoAdapter.UpdateInterface

and now I have a method to work with, shown below:

@Override
public void recyclerviewOnUpdate(int amount) {
    //Now I can get the int and check if the adapter is empty after removing a item
    if (amount<1) {
        txtEmptyAdapter.setVisibility(View.VISIBLE);
    }
}
Ad
source: stackoverflow.com
Ad