Sekar Anindya
Sekar Anindya

Reputation: 83

getActivity in Activity

I'm having trouble with getActivity() in Activity. It says can't resolve method getActivity(). I'm using it to make onClick in recyclerView.

Here is my code

 mRecyclerView.setAdapter(mAdapter);
 mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), this));

What should I change getActivity with? Thanks in advance

Upvotes: 3

Views: 10192

Answers (5)

Ajay Chauhan
Ajay Chauhan

Reputation: 1551

All of the mentioned answers are correct. However, sometimes 'this' can't referenced as your Activity ,mostly when we try to pass it from inside one of callback methods like :

view.setOnClickListener(v->showToast(this));

In such cases ,pass the activity using the whole name of the class like this :

view.setOnClickListener(v->showToast(Sample.this));

Upvotes: 0

Vikrant Shah
Vikrant Shah

Reputation: 547

You can pass parameters like this:

mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, mRecyclerView));

Or for detail information you can refer this bolg :- Android - RecyclerView: Implementing single.

Upvotes: 0

Sekar Anindya
Sekar Anindya

Reputation: 83

I forgot to implements the recyclerclicklistener. After I implements the method and change

getActivity

to

this

it worked fine

extends AppCompatActivity implements RecyclerItemClickListener.OnItemClickListener

Upvotes: 1

Newtron Labs
Newtron Labs

Reputation: 819

You have declared your code inside of an Activity. Therefore you can simply use this to reference the Activity you are in.

mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, this));

Upvotes: 3

Matthew Shearer
Matthew Shearer

Reputation: 2795

change it to

this

this is a reference to the class your in, like MainActivity.this

Upvotes: 1

Related Questions