0

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?

Albert
  • 63
  • 1
  • 7

5 Answers5

2

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();
Faisal Shaikh
  • 3,900
  • 5
  • 40
  • 77
0

use getActivity()

Toast.makeText(getActivity(), "count is " + count, Toast.LENGTH_SHORT).show();
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
KamDroid
  • 102
  • 4
  • 7
0

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

Community
  • 1
  • 1
appersiano
  • 2,670
  • 22
  • 42
0

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();
Nanda Gopal
  • 2,519
  • 1
  • 17
  • 25
0

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();`
  }    
}
Nagendra
  • 193
  • 4
  • 14