Getting recyclerview position and passing object on click

11,422

We handling the click events, I have tried below method Create an interface RecyclerOnItemClickListener

import android.view.View;

/**
 * A click listener for items.
 */
public interface RecyclerOnItemClickListener {
    /**
     * Called when an item is clicked.
     *
     * @param childView View of the item that was clicked.
     * @param position  Position of the item that was clicked.
     */
    public void onItemClick(View childView, int position);
}

In the adapter class, you can take the RecyclerOnItemClickListener object which is implemented in the calling Activity/Fragment

RecyclerOnItemClickListener mItemClickListener;

You can then initialize that variable in the constructor of the adapter

mItemClickListener = recyclerOnItemClickListener;

The activity/Fragment implements the RecyclerOnItemClickListener interface, so it will have onItemClick method implemented. You can write the code for passing data in the next activity here

@Override
    public void onItemClick(View childView, int position)
    {
        Intent intent = new Intent(getActivity(), NextActivity.class);
        intent.putExtra("ITEM", mModels.get(position));
        startActivity(intent);
    }

In the adapter class, you will need to initialize the ViewHolder class as shown below:

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
    TextView content;
    TextView proba;
    ImageView imageView;


    public ViewHolder(View itemView) {
        super(itemView);

        content = (TextView) itemView.findViewById(R.id.textView);
        proba = (TextView) itemView.findViewById(R.id.textView2);
        imageView = (ImageView) itemView.findViewById(R.id.imageView);


    }

        @Override
        public void onClick(View v)
        {
            if (mItemClickListener != null)
            {
                mItemClickListener.onItemClick(v, getPosition());
            }
        }
}

Hope this helps you..

Share:
11,422
IDontEvenKnow
Author by

IDontEvenKnow

Updated on June 04, 2022

Comments

  • IDontEvenKnow
    IDontEvenKnow about 2 years

    I really need your help here guys, i'm stuck. In short i have made recyclerview to show my parsed json data. What i'm stuck at is on how to get recyclerview position and pass json object to new activity trough intent. Here is my code so you can see whats going on. MainActivity:

    public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
    
    ArrayList<Item> end = new ArrayList<Item>();
    RecyclerView recyclerView;
    Adapter adapter;
    List<Item> mModels;
    Context context = this;
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList("KEY2", end);
    
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // View view = LayoutInflater.from(this).inflate(R.layout.activity_main, null, false);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.RecylerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new Adapter(this);
        recyclerView.setAdapter(adapter);
    
    
        if (isAvailable() && savedInstanceState == null)
        //Check if network is available
        {
            jsonreq();
        } else if (savedInstanceState != null)
    
        {
            end = savedInstanceState.getParcelableArrayList("KEY2");
            adapter.list(end);
    
    
        } else {
            Toast.makeText(this, "Molimo, ukljucite internet.", Toast.LENGTH_LONG).show();
    
        }
    
    
    }
    
    
    private boolean isAvailable() {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        Boolean isAvail = false;
        if (networkInfo != null && networkInfo.isConnected()) {
            isAvail = true;
        }
        return isAvail;
    
    }
    
    public void jsonreq() {
        String url = "http://www.json-generator.com/api/json/get/cfOhbHcpki?indent=2";
        RequestQueue requestQueue = VolleySingelton.getrequestQueue();
    
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
    
            @Override
            public void onResponse(JSONObject response) {
                end = getdata(response);
                adapter.list(end);
    
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
    
            }
        });
        requestQueue.add(request);
    
    }
    
    private ArrayList<Item> getdata(JSONObject response) {
        ArrayList<Item> listy = new ArrayList<Item>();
    
        try {
    
            JSONArray array = response.getJSONArray("items");
    
            for (int i = 0; i < array.length(); i++) {
                JSONObject object1 = array.getJSONObject(i);
                String content = object1.getString("caption");
                String url = object1.getString("url");
                String proba = object1.getString("proba");
                // ImageView image = process(url,imageView);
                Item I = new Item(content, url, proba);
                listy.add(I);
    
            }
    
    
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(this, "Error" + e, Toast.LENGTH_LONG).show();
        }
        Log.d("mohak", "" + response.length());
    
        return listy;
    
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem menuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView.setIconifiedByDefault(true);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return true; // handled
            }
    
            @Override
            public boolean onQueryTextChange(String newText) {
    
               adapter.getFilter().filter(newText);
    
                return true;
            }
        });
        return true;
    }
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar Item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
    
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
    
        return super.onOptionsItemSelected(item);
    }
    
    
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }
    
    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }
    

    This is adapter:

    public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> implements  Filterable{
    
    public static final String LIST_DETAIL_KEY = "list";
    
    public Item item;
    
    private LayoutInflater inflater;
    Context context;
    ArrayList<Item> fin = new ArrayList<Item>();
    
    
    Adapter(Context context) {
        inflater = LayoutInflater.from(context);
        this.context = context;
    }
    
    public void list(ArrayList<Item> fin) {
        this.fin = fin;
        Search search = new Search(fin);
        notifyItemRangeChanged(0, fin.size());
    }
    
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    
        View view = inflater.inflate(R.layout.rac, viewGroup, false);
        ViewHolder holder = new ViewHolder(view);
    
        return holder;
    }
    
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }
    
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int i) {
    
        Item current = fin.get(i);
        viewHolder.content.setText(current.content);
        viewHolder.proba.setText(current.proba);
    
    
        //  Uri uri = Uri.parse(current.url);
        //  Context context = viewHolder.imageView.getContext();
        Picasso.with(context).load(current.url).into(viewHolder.imageView);
    
    }
    
    @Override
    public int getItemCount() {
        return fin.size();
    }
    
    @Override
    public Filter getFilter() {
        Search search = new Search(fin);
        return search;
    }
    
    
    class ViewHolder extends RecyclerView.ViewHolder {
        TextView content;
        TextView proba;
        ImageView imageView;
    
    
        public ViewHolder(View itemView) {
            super(itemView);
    
            content = (TextView) itemView.findViewById(R.id.textView);
            proba = (TextView) itemView.findViewById(R.id.textView2);
            imageView = (ImageView) itemView.findViewById(R.id.imageView);
    
    
        }
    }
    }
    

    Thank you in advance.

  • IDontEvenKnow
    IDontEvenKnow over 8 years
    Can you give me an example of how to fill this in: // you get the unique id of every item and perform your desired operation // Here you can send data to another activity according to position // You get each item data object With for example opening a new intent with putExtra object proba?
  • IDontEvenKnow
    IDontEvenKnow over 8 years
    Ok, i think i got it, kinda. But, i have another question. How do i set my intent in that onClick that can pass object to the new activity?
  • Rohit Heera
    Rohit Heera over 8 years
    Yes you can create a intent object and setdata in extras and call context.startActivity(intent)
  • Rohit Heera
    Rohit Heera over 8 years
    See in class Listener you have this object Item data; this data object give you the unique item according to the position
  • IDontEvenKnow
    IDontEvenKnow over 8 years
    So something like this? Intent intent = new Intent(context, Example.class); data.setProba(proba.getText().toString()); intent.putExtra("proba", data.toString()); context.startActivity(intent);