0

I'm new to android and java.

I'm rearranging some of the classes in my app into separate class files. I had a onLocationListener class in my main activity class file. I moved the class to a separate java class file. Then, however the following code will not compile . . .

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

The getApplicationContext won't compile when this code is in a separate file. I tried this. and mainactivityname. but nothing seems to work. So I suppose this problem can be formed into a the following question:

How do you state the application context from code that exists in separate java class files outside the main activity file? thanks, Gary

nyyrikki
  • 1,436
  • 1
  • 21
  • 32
Dean Blakely
  • 3,535
  • 11
  • 51
  • 83

1 Answers1

2

getApplicationContext() is a method of class Context, so you can only call it from a class or object that in some way extends Context. You factored your code out of Activity, which is such a class. Your solution, then, is for the Context class that contains your new class or object to pass its context in so that your new class can use it.

Your code inside your main Activity would look something like this:

MyOwnClass ownObject = new MyOwnClass();
// you have to implement setApplicationContext
ownObject.setApplicationContext( this.getApplicationContext() );

It's probably a good idea to get the application context right away, since it'll be stable for the lifetime of your app, unlike the Activity context which could go away on something as simple as an orientation change.

Sparky
  • 8,437
  • 1
  • 29
  • 41