0

I want to pass the data from the Activity containing a recyclerview to it's recyclerAdapter class. I just want to use a String in the adapter but I don't know how to get it from the activity. Is there any way to do this? Please keep in mind I want data from Activity to Adapter and not vice a versa

Edit: So in my activity, I have defined a public method:

public String getName(){
return f_name;
}

Now how do I call this in my adapter class? I'm not able to access my getName() method here !

Chirag
  • 98
  • 8

2 Answers2

0

Sure. You should create the adapter with a parameter. For example:

class MyAdapter(val string: String) : RecyclerView.Adapter()

and then you create the adapter in the activity:

recyclerView.adapter = MyAdapter(myString)

And that's it. You didn't specify a language so I used kotlin.

Lheonair
  • 468
  • 5
  • 14
  • Sorry! I see now that you specified Java in the tags. This solution works for me in kotlin, and the Java version should work for you. Are you able to translate this to kotlin or you need a hand on that matter? – Lheonair Jul 22 '20 at 14:08
0

Agustine's answer is for kotlin, here's the java version

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>() {
    private String myString;
    private Context context;
    
    MyAdapter(Context context, String myString) {
        this.context = context;
        this.myString = myString;
    }
}

and then in your activity

MyAdapter adapter = new MyAdapter(this, "string you want to pass to adapter")

That's it. You can learn more about recyclerview and recyclerAdapter here

tony
  • 466
  • 6
  • 22