Calling functions provided by the Activity class from anywhere - android

How do I call the functions provided by Activity class from a class that does not extend Activity? Theoretically, yes, if I don't extend Activity I cannot directly use the functions provided by it. But is there a workaround provided for this? If not, are there replacements or alternative ways for these functions?
For example,
If my class extends Activity, I can call setContentView() to instantiate my layout xml file. But if my class extends some other class and doesn't extend Activity, then I can use the LayoutInflater to do the task. But what about other functions like registerReceiver() ? How do I get the functionality of 'registerReceiver()' from any other class , obviously I wouldn't want every such class to extend Activity. Static access by "Activity.function_name" is also not possible as these functions are not static.
Certain services can be accessed from anywhere. For example 'println()' or Log.e(),System functions can be called from anywhere, whenever needed. Is there a similar way for other critical functions?
Conclusion:
Pass Context to destination class. For accessing some functions however, type-casting the passed Context to Activity is required.
Both Changdeo's and BT's answers are correct.
Thanks.

Although I have not found any documentation explicitly stating why, in every case where I have ever needed to do this, simply passing the Activity's Context is sufficient.
For a Context called contextActivity passed into any function, the following will allow access to these member functions you require:
((Activity) contextActivity).<anyMemberFunction>
Or if you need these functions in multiple cases it might be simplest just to do the following:
Activity myActivity = (Activity) contextActivity;
From there you can access these Activity member functions whenever you like by using:
myActivity.<desiredFunction>;
As I mentioned, I have never found any case where this hasn't worked, but also no solid documentation saying this will always work. This is the trick I have seen consistently used though. If anyone has more to add, please do.

For Ex
Class XYZActivity extends Activity
{
......
......
MyClass myClass = new MyClass(this);
// OR you can pass just context
// MyClass myClass = new MyClass(getContext());
}
Class MyClass
{
Context context;
Myclass(Context context)
{
this.context = context;
context.registe....//Or any function
}
}

Related

Android getApplicationContext() outside Activity and Application

How I can get application context outside activity and without extending application class.
class A{
public static B b = new B(App context here);
}
Objetc b must be as a field
No you can't get context without extending Application or Activity by the given example. All that you can do is to have a static method in a class (extends Application) that would return context and then pass that method as a parameter to your B().
BTW, I did not get your intention of doing this. Can you detail out what exactly you wants to do.
Thank you
It is not possible.
If it were, it would mean that any Java class would be able to access an android.content.Context instance, even when is not related to anything in Android, for example, a Java EE application.
What you can do, is, have a static reference to a Context (an Application or an Activity) in a centralized place inside your app, but I wouldn't recommend it because it would cause multiple memory leaks.

How can I get a packagemanager object if i am not extending the activity class in Android/ Java?

i am trying to set up a helper class that does not extend the Activity class. How ever i need to get a packagemanager object with getPackageManager(). How can i do this?
Why I am needing this? Well i am trying to setup this Helper class and I tried doing it with my Helper class that extended Activity. However I always got a nullpointerexceptions since my helper object was null.
Any tips?
Usually the best way to do what you're trying to do it pass the Context to the constructor of your new class. That way you can then use that to call methods which belong to the Activity.
An example is below, it should help you work out your problem:
private Context context;
// ...
public HelperClass(Context c){
context = c;
}
// ...
context.getPackageManager();
You can then call it by just adding your Context when you initialize the new class:
new HelperClass(this);
Although in certain situations, such as from a Fragment, you may have to provide getActivity();.
new HelperClass(getActivity());
Try edit your class as shown above and let us know if you see any improvements.
As mentioned in the comments, unless you're planning on using your context to edits views etc. you'd be better off with context = c.getApplicationContext(); in your constructor.

How to handle Android Java objects which "extends Activity"?

Let's say I have two classes:
Class Show is my normal Android activity.
Class Work is a Java class which does a lot of work:
public class Work extends Activity {...}
As you can see, Work extends Activity. Thats because it needs some methods that are only in Activity (I don't mean methods which regard the UI).
In my Activity Show I make an Objekt of class Work
protected void onCreate(){
Work mWork = new Work();
mWork.doSomething();
}
My question:
How shall I handle my object Work regarding its lifecycle? Is it like a normal Java object and I don't have to care about its lifecycle, or is it like a normal activity and i have to call finish()? I am confused because it's kind of both.
Based on our discussion in the comments, the answer here would be to pass the Context of your current activity to the target class, and use the accessible methods through that context instance to do whatever task it is you want, as the Activity class basically extends ApplicationContext.
For example (in a class not extending Activity) I can add:
myLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
and use myLocationManager as I please. Also, this way the object created locally would be set for garbage collection upon destruction of your main Activity.
Thought it'd be worth having an answer others could refer to rather than scrounging through the comments.
you should read this to understand activity lifecycle.

Why are we using Context in creating object for other class in Android?

In some places we were giving like "DatabaseUtil db=new DatabaseUtil(DailyPlanView.this);" where DatabaseUtil is the class with the constructor argument is context. But if we create the object for the DatabaseUtil class in the DailyPlanVIew class we are using the above code. My doubt is what is the use of the context and instead of passing the context object as argument why we are passing "this".
Whenever you are dealing with Context, its important to understand its used in everything. From using a database to obtaining system services. This is required by the way android works with Context. Specifically when you are passing this you are basically passing the class that encapsulates this statement.
class MyActivity extends Activity
{
onCreate(Bundle bundle)
{
View v = new View(this);
}
}
passing this refers to the object that encapsulates it. This is a Object oriented concept... Where this is reffering to MyActivity. One thing to keep in mind when passing context is ensure that you are passing the correct kind. Some Context objects have a longer lifespan than others and if not managed properly can lead to Context leaking. Specifically in this example, this works because Activity extends Context.
The differences occur in the View class.
getApplicationContext()
getBaseContext()
this, which in the Context of an activity has the life span of an Activity (Example above)
One thing to add about Context is that it is basically a reference to the current Application and it's specific data.
Some more information about context can be found in this thread:
What is 'Context' on Android?

Needing Context in non-Activity classes

I have some classes within my application that need to call Android functions that require the Context as a parameter.
I don't have it as the class is not a subclass of the Activity class.
What is the correct way to tackle this problem?
Pass it as a parameter on each call?
Pass it at class instantiation and keep it?
It depends on the role of the class. But anyway pass ApplicationContext but not Activity one. If you pass Activity context gc can't remove it from the memory when after you don't need activity anymore. But application context is used while application was not finished by OS.Refer Avoid Memory Leaks
Pass it as a parameter. Or better yet, get the application context to avoid memory leaks.
public class Example {
protected Context context;
public Example(Context context){
this.context = context.getApplicationContext();
}
}
I'm pretty much always going with a constructor parameter approach. I pass it in the instantiation and keep a private reference in the instantiated class.
You have to think about one important thing. If the class you pass the Context will exist longer than the Activity instantiating it then you should use the application context. If that class is doing UI stuff you will need an activity context.
Make sure that the class you are passing an activity context to won't last longer than the Activity or you'll leak the entire activity.
If you don't do UI stuff then go with the application context.
I pass it as a parameter, i think its de best form to do it
Pass it at class instantiation and keep it.
One typical example is when you create a db helper. See this link
I've answered this question here also.
You can do that using ContextWrapper, as described here.
For example:
public class MyContextWrapper extends ContextWrapper {
public MyContextWrapper(Context base) {
super(base);
}
}
and use that class as it were Context
The best way is to follow Bean approach:
public class Example {
protected Context getContext() {
...
}
...
}
Then it depends on possibilities to access context. If class is fully independent then constructor parameter and private field seems best approach.
But that bean property way shields you from further code changes.

Categories

Resources