Search code examples
androidandroid-fragmentsandroid-recyclerviewonclicklistener

how to passing data when clicked on item fragment with recyclerview to activity


I have a question about passing clicked cardview data to activity How when the user clicks the item, it will open the PlayerActivity.class, and change Details layout title, urlimage, with clicked item title, and the same for description. Here are my files :

myadapter.java

public class NettvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final List<item_kenh> recyclerViewItems;
private final Context mContext;
Tab1_Fragment fragmenttab1;


public NettvAdapter(Context context, List<item_kenh> recyclerViewItems,Tab1_Fragment fragmenttab1) {
    this.mContext = context;
    this.recyclerViewItems = recyclerViewItems;
    this.fragmenttab1 = fragmenttab1;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

    View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_kenh, null);
    return new MenuItemViewHolder(itemLayoutView);
}



@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,final int position) {

    MenuItemViewHolder menuItemHolder = (MenuItemViewHolder) holder;
    final item_kenh fp = (item_kenh) recyclerViewItems.get(position);

    //menuItemHolder.titles.setText(fp.getTitle());
   // menuItemHolder.profile.setText(fp.getProfiles());
    String url = fp.getUrl_images();
    Picasso.get().load(url).into(menuItemHolder.thumb);

    menuItemHolder.thumb.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           fragmenttab1.clikcData(fp.getUrl_images());


        }
    });

   // menuItemHolder.titles.setOnClickListener(new View.OnClickListener() {
    //    @Override
   //     public void onClick(final View v) {
    //        fragmentone.clikcData(fp.getTitle());
    //    }
    //});
}


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


public class MenuItemViewHolder extends RecyclerView.ViewHolder {
   // public TextView titles;
    public ImageView thumb;
   // public TextView profile;
   // public LinearLayout lineLayout;

    MenuItemViewHolder(View itemLayoutView) {
        super(itemLayoutView);

       // titles      = (TextView) itemLayoutView.findViewById(R.id.title);
        thumb       = (ImageView) itemLayoutView.findViewById(R.id.imageView);
        //profile     = (TextView) itemLayoutView.findViewById(R.id.profiles);
        //lineLayout = (LinearLayout) itemLayoutView.findViewById(R.id.midlelayout);


    }
}

}

tab_1.java ( fragment )

public class Tab1_Fragment extends Fragment {


public static final String TAG = "MYTAG";
RequestQueue QUEUE;
String URLHTTP;

private List<item_kenh> mRecyclerViewItems = new ArrayList<>();
private RecyclerView.Adapter mAdapter;
RecyclerView rv;

public static Tab1_Fragment getInstance()
{
    Tab1_Fragment fragmenttab1 = new Tab1_Fragment();
    return fragmenttab1;
}

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
}
public Tab1_Fragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final  View rootView = inflater.inflate(R.layout.fragment_tab1,container,false);
    rv = (RecyclerView)rootView.findViewById(R.id.rv_tab1);

    rv.setHasFixedSize(true);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));
    rv.setLayoutManager(new GridLayoutManager(getContext(), 3));
    mAdapter    = new NettvAdapter(getContext(),mRecyclerViewItems,this);
    QUEUE = Volley.newRequestQueue(getContext());
    URLHTTP = getResources().getString(R.string.urlserver);
    httpGET(URLHTTP);
    mRecyclerViewItems.clear();
    return rootView;


}


public void httpGET(String url)
{
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    parsingData(response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            try {
                String responseBody = new String(error.networkResponse.data,"utf-8");
                Log.d(TAG,"ERROR "+responseBody);
            }catch (UnsupportedEncodingException errorr){
                Log.d(TAG,errorr.toString());
            }
        }
    }
    );
    QUEUE.add(stringRequest);


}
public void parsingData(String jsonData)
{
    try {
        JSONObject obj = new JSONObject(jsonData);
        JSONArray m_jArry = obj.getJSONArray("data");

        for (int i = 0; i < m_jArry.length(); i++) {
            JSONObject jo_inside = m_jArry.getJSONObject(i);
            String url_img = jo_inside.getString("url_img");
            item_kenh stationItem = new item_kenh(url_img);
            mRecyclerViewItems.add(stationItem);

        }

        rv.setAdapter(mAdapter);
    } catch (JSONException e) {
        e.printStackTrace();
    }

}


public void clikcData(String datatitle)
{

    Intent int_detail = new Intent(getContext(), PlayerActivity.class);
    int_detail.putExtra("url_img", position);
    getActivity().startActivity(int_detail);

}

PlayerActivity.java

public class PlayerActivity extends AppCompatActivity {




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_player);

    ImageView imageView = findViewById(R.id.image);

    Intent intent = getIntent();
    String imageUrl = intent.getStringExtra("url_img");
    Picasso.get().load(imageUrl).fit().centerInside().into(imageView);
}

}

Hope someone will help me, thanks


Solution

  • First create a new interface anywhere like below (ClickListener.java):

    interface ClickListener {
        void onClickData(String value);
    }
    

    Then add it in the Adapter as a constructor parameter.
    Also there is no need for the Context parameter in the Adapter (at least I haven't found any context requirement.)
    However if you need context in onBindViewHolder, you should use holder.itemView.getContext()

    public class NettvAdapter extends RecyclerView.Adapter<NettvAdapter.MenuItemViewHolder> {
    private final List<item_kenh> recyclerViewItems;
    private listener ClickListener;
    
    
    public NettvAdapter(List<item_kenh> recyclerViewItems, ClickListener listener) {
        this.recyclerViewItems = recyclerViewItems;
        this.listener = listener;
    }
    
    @Override
    public NettvAdapter.MenuItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    
        View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_kenh, null);
        return new MenuItemViewHolder(itemLayoutView);
    }
    
    
    
    @Override
    public void onBindViewHolder(NettvAdapter.MenuItemViewHolder holder, final int position) {
    
        final item_kenh fp = (item_kenh) recyclerViewItems.get(holder.getAdapterPosition());
    
        //menuItemHolder.titles.setText(fp.getTitle());
       // menuItemHolder.profile.setText(fp.getProfiles());
        String url = fp.getUrl_images();
        Picasso.get().load(url).into(holder.thumb);
    
        holder.thumb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               listener.onClickData(fp.getUrl_images());
            }
        });
    }
    
    
    @Override
    public int getItemCount() {
        return recyclerViewItems.size();
    }
    
    
    public class MenuItemViewHolder extends RecyclerView.ViewHolder {
       // public TextView titles;
        public ImageView thumb;
       // public TextView profile;
       // public LinearLayout lineLayout;
    
        MenuItemViewHolder(View itemLayoutView) {
            super(itemLayoutView);
    
           // titles      = (TextView) itemLayoutView.findViewById(R.id.title);
            thumb       = (ImageView) itemLayoutView.findViewById(R.id.imageView);
            //profile     = (TextView) itemLayoutView.findViewById(R.id.profiles);
            //lineLayout = (LinearLayout) itemLayoutView.findViewById(R.id.midlelayout);
    
    
        }
    }
    

    Then implement ClickListener in your Fragment:

    Tab1_Fragment extends Fragment implements ClickListener {
    
    @Override 
    void onClickData(String clickedValue) {
        Intent int_detail = new Intent(getContext(), PlayerActivity.class);
        int_detail.putExtra("url_img", clickedValue);
        getActivity().startActivity(int_detail);
      }
    }
    

    And initialise your Adapter same as before:
    mAdapter = new NettvAdapter(mRecyclerViewItems, this);