Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the method getApplicationContext() is undefined

Tags:

android

public void onProviderDisabled(String provider) {
    Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT);


}

So this is what I have, and it shows an error and tells me The method getApplicationContext() is undefined for the type MyLocationListener

what should I do to avoid this error

like image 316
john parker Avatar asked May 21 '13 20:05

john parker


People also ask

When would you call getApplicationContext () and why?

This method is generally used for the application level and can be used to refer to all the activities. For example, if we want to access a variable throughout the android app, one has to use it via getApplicationContext().

What is getApplicationContext in Android Studio?

getApplicationContext() : Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.


3 Answers

Since you aren't in an Activity you need to pass a Context to the class. Wherever you instantiate this class pass your Activities context

MyClass myClass = new MyClass(this);

Then create a constructor in that class that accepts Context as a param and use that

public class MyClass {
    Context c;
    public MyClass(Context context) {
         c = context;
     }
}

then when you need to use it

public void onProviderDisabled(String provider) {
    Toast.makeText(c, "Gps Disabled", Toast.LENGTH_SHORT);
}
like image 99
codeMagic Avatar answered Sep 28 '22 21:09

codeMagic


this worked for me

public class MyClass extends Activity

like image 37
Abhay Kumar Avatar answered Sep 28 '22 20:09

Abhay Kumar


if you are using ContentProvider try this

getContext()
like image 26
Sujith Manjavana Avatar answered Sep 28 '22 22:09

Sujith Manjavana