dealing with application context - java

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

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.

Related

Android 25 Java : Using methods that require Context in a different Class - Require assistance

I created a simple little directory listing method in the default MainActivity.class
I was able to get it to function the way I wanted it to, however, when I moved the method to a different class and called it in MainActivity, I wound up getting a lot of Context Errors all over the place. After searching the web I am stumped and require assistance.
The code where it errors out is for the Context for FileArray:
(public class Utilities extends Activity)
arrayAdapter = new FileArrayAdapter(getApplicationContext(),R.layout.custom_explorer,dir);
Method Name:
public void listDirectories(ListView listView, File directory)
It errors out on the getApplicationContext, this method worked just fine in MainActivity.
I have not implemented Fragments to MainActivity yet, wanted to get the working functionality first then spread out for OOP; then call by Fragment.
Hope someone can help, any further info I am happy to share.
Thank you for the timely response: ρяσѕρєя K & Nilabja.
Ya I guess it just needed another person to suggest feeding Context as a param. I did that once but it did not work so I passed it off, attempted once again from Nilabja suggestion. Yip that was the solution.
utilities.ListDirectory(mainList, root, getApplicationContext());
public void listDIR(ListView listView, File directory, Context setContext)

Complications while converting an Android application to a library

I had an Android application(MyApp, say) that used ApplicationContext extensively. The ApplicationContext was made available via a class that extended Application.
class MyApp extends Application {
static Context mContext = null;
public void onCreate() {
mContext = getApplicationContext();
}
public static Context getContext() {
return mContext;
}
}
I would like to convert this application to a library and use it in another application ( AnotherApp, say). Now I see that AnotherApp already has a similar class that extends Application and gives its context everywhere within itself. When I move MyApp as a library into AnotherApp, my code will not be able to get ApplicationContext anymore - as only one class can be declared in Manifest (android:name=".AnotherApp")
What is the best way to make application context available within library? I do not mind making extensive code changes, but would like to know options I have - other than passing context to every api in my library.
A library should never use the getApplicationCOntext it is meant for the main program.
you can pass the context using a function or save it into a public static variable in your class in the beginning.
Note about code design
This completely depends on how you want to use the library, will the functions be used in the main app ? Will the activity be directly called ? and a bunch of other code design things like that.
If you want two activities sometimes the best way it to make them into separate applications and make one call the other using an Intent. Like how google maps and other inbuilt services are used.
If you want to use your library's function in the main application, you should not be creating an activity at all. Rather you should make an abstract class that the user can inherit from and use your class through.
I have done similar stuffs in my Application.
Its true you will not able to get context in your library
You will have context of only AnotherApp
If you want to use Context in your library in that case you need to have some method which can pass your AnotherApp's context to your library.
For example
class MyApp extends Application {
static Context mContext = null;
public void onCreate() {
mContext = getApplicationContext();
objecofYourLibClass = new MyApp();
objecofYourLibClass.yourMethod(mContext);
}
}
Now you will able to use context in your Library.

Forward context in Android

I am writing client REST application for Android. Because in my main Activity there is a lot of methods I decided to move rest operations to new class 'RestClient'.
Over there I need application context to execute: Volley.newRequestQueue(CONTEXT HERE); and to create Toasts.
What is the best way to do that?
I believe that making static Context context in Activity and then access it inside class is not the best way.
The safest way is to always pass the Context to any method that needs it, e.g.
public void showToast(final Context context, ...)
so you can call it from an Activity as follows
showToast(this, ...);

Static Context from Activity.onStart()

I am trying to generate a notification from a class, Utilities.java, outside of the subclass of Context. I've thought about providing a SingletonContext class and have looked at posts ike this. I'd like to be able to return != null Context object since the notification can be generated at any given time because it is generated from a messageReceived() callback.
What are there downsides to doing something like this:
public static Context c;
public class MainActivity extends Activity{
#Override
public void onStart()
super.onStart()
c = this.getApplicationContext();
}
//other method somewhere outside this class
public Context getContext(){
return MainActivity.c
}
I don't think it would be any different than putting this on the onCreate(), however, it guarantees that the context is up to date when the activity starts.
The Context keeps a reference to this activity in memory, which you might not want. Perhaps use
this.getApplicationContext();
instead. This will still let you do file IO and most other things a context requires. Without a specific reference to this activity.
Maybe you should overwrite the onResume Method.
If you open a new activity, and switch back, the onStart method will not getting invoked.
Android Lifecycle: doc
BTW: I read about problems with ApplicationContext using a dialog or toast, so if you use the context to create on of these you should use your Activity as context.

Generic classes in my application

I've created a few minor apps for Android while learning. Being a PHP developer, it's a challenge to get used to it.
I'm especially wondering how I could define a couple of "general" functions in a separate class. Eg I have a function that checks if network connection is available, and if not, shows a dialog saying that the user should enable it. Currently, that function exists in several of my activities. Of course that seems strange - I suppose it would be more logical to define it once and include it in the activites where needed.
I tried putting it in a new class, and included that class in the original activity. But that failed since eg getBaseContext() is not accepted anymore.
I'm wondering how to go ahead. What should I be Google-ing for ? What is this mechanism called?
You need to create class with static methods. Like this
public class HelperUtils {
public static void checkNetworkConnection(Context ctx) {...}
}
Then you can call it from any place like this:
HelperUtils.checkNetworkConnection(this.getContext());
Assuming current class has Context.
You should read books on general OOP concepts where different type of methods are explained.
You can for example create a class - let's call it NetworkUtils. In this class you can create static method boolean isNetworkConnectionAvailable() and return true if is available and false otherwise. In this class you can create another static method void showNoConnectionDialog(Activity activity) - and in this method you create dialog starting with
public static void showNoConnectionDialog(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//setting message, listener etc. and finally
builder.create().show();
}
In your activity, where you want to check and handle network connection you should call:
if (!NetworkUtils.isConnectionAvailable(getApplicationContext())) {
NetworkUtils.showNoConnectionDialog(YourActivityClassName.this)
}
I guess this should work.

Categories

Resources