Albert
Albert

Reputation: 63

Unable to show toast in fragment using this

I am new in android development. I am trying to show Toast in fragment using following code which i got from other sites:

Toast.makeText(this, "count is " + count, Toast.LENGTH_SHORT).show();

But I am getting an issue in the first parameter. Can anyone help?

Upvotes: 0

Views: 1589

Answers (5)

KamDroid
KamDroid

Reputation: 102

use getActivity()

Toast.makeText(getActivity(), "count is " + count, Toast.LENGTH_SHORT).show();

Upvotes: 0

Nagendra
Nagendra

Reputation: 193

Override fragments onAttach(Context) method and store context for all calls which requires context.

class MyFragment extends Fragment{
   private Context _context;
   @Override
   protected void onAttach(Context context){
     _context = context;
   }

  private void showToast(){
     Toast.makeText(_context, "count is " + count, Toast.LENGTH_SHORT).show();`
  }    
}

Upvotes: 0

Nanda Gopal
Nanda Gopal

Reputation: 2699

1) You can use getActivity() instead of using this keyword. The code will be like below,

Toast.makeText(getActivity(), "Count is" + count, Toast.LENGTH_SHORT).show();

Upvotes: 0

appersiano
appersiano

Reputation: 2770

If you see the signature of the method makeText of the Toast class you can see that the first parameter required is the Context.

A fragment is not a subclass of Context so using the this keyword you are passing the Fragment object.

You have to use getActivity() or getContext() method.

Toast.makeText(getActivity(), "count is " + count, Toast.LENGTH_SHORT).show();

If you want to know the difference read this post What is the difference between this getcontext and getactivity

Upvotes: 0

Faisal Shaikh
Faisal Shaikh

Reputation: 4138

You can use getActivity(), which returns the activity associated with a fragment. The activity is a context (since Activity extends Context).

So your code will be like this:

Toast.makeText(getActivity(), "count is " + count, Toast.LENGTH_SHORT).show();

Upvotes: 2

Related Questions