I am getting error while creating a Toast
Toast toast = Toast.makeText(this, text, duration);
I am getting cannot resolve ma
In the onClick(View view)
click listener within a RecyclerView.ViewHolder
the context is retrieved with view.getContext()
, as in:
```
public class MyHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public MyHolder(View itemView) {
super(itemView);
//...
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "the message",
Toast.LENGTH_SHORT).show();
}
```
Grab the context from the calling activity (eg. this or MainActivity.this) and pass it into the method your Toast resides in. That way it lives together with the calling activity.
Application context, which you get from getApplicationContext() and getContext() is mainly for long running processes. Using it for short lived processes can lead to memory leaks.
this in your case might not be the object of the activity. You might be using the Toast.makeText method inside you Click Listener object. To resolve this you need to use getApplicationContext() :
Toast.makeText(getApplicationContext() , "Your Message", Toast.LENGTH_LONG);
This might be helpful if you are trying to use Toast in Fragment:
Toast.makeText(Your_Fragment_Name.super.getContext(), "Added", Toast.LENGTH_SHORT).show();
Instead of
Toast toast = Toast.makeText(this, text, duration);
Add your activity name before "this" word
Toast toast = Toast.makeText(MyActivity.this, text, duration);
in the onClick method try this
Toast.makeText(view.getContext(), "sorry", Toast.LENGTH_LONG).show();
it did work form me.