Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
194 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...