Error in getApplicationContext () Android

1

I am trying to load a Toast Messagge. Inside a class that "paints" a ViewPager . The problem is that I am having an error when it comes to picking up the context. What could I be doing wrong?

public class ScreenSlidePageFragment extends Fragment {
    public void onCreate(Bundle savedInstanceState){...}
    public void onCreateView(Bundle savedInstanceState) {

        Button btnTick = (Button) rootView.findViewById(R.id.buttonInvertirTick);
    btnTick.setOnClickListener(new View.OnClickListener() {
        public void onClick (View v) {
            Context context = getApplicationContext();
            CharSequence text = "Hello toast!";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    });

    }
}

I have not copied all the code since the post would be somewhat longer and the error is as follows Can not resolve'getApplicationContext () '

    
asked by Eduardo 24.05.2017 в 14:34
source

2 answers

4

Replace getApplicationContext() with getActivity() .

If you are going to work with more elements that need the Context I advise you that in your Fragment initialices:

Activity activity = getActivity();
Toast toast = Toast.makeText(activity, text, duration);

EDITION

  

getActivity ()   Return the Activity this fragment is currently associated with.

As the documentation says, the getActivity() method brings the activity (The context) to which it is associated with your Fragment

  

getApplicationContext ()   Return the context of the single, global Application object of the current process.

I leave you more info of the official documentation.

    
answered by 24.05.2017 / 14:36
source
0

As a complement to this question you must remember that if you are in a Fragment usa getActivity() to get the context , (since a Fragment is always contained in an Activity).

   Context context = getActivity();

In the case of being in an Activity you can use this to refer to Activity or use getApplicationContext() to get the context of the application.

  Context context = getApplicationContext();

Your corrected code would be:

  public void onClick (View v) {
            Context context = getActivity(); //*** Aquí el cambio.
            CharSequence text = "Hello toast!";
            int duration = Toast.LENGTH_SHORT;    
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    
answered by 24.05.2017 в 16:54