How do I get the instance of the currently visible activity in Android? I've read that I can get the ComponentName of the activity by using ActivityManager to get a list of tasks and messing with that, but that's a recipe for disaster.
Is there a way to get an instance of the topmost activity, or if the activity isn't mine and I can't access it, just null?
TO get instance of currently visible activity, get its context as:
Context mContext = getApplicationContext();
or
mContext = this;
now use it for this activity related tasks.
OR to get instance of another activity; keep a static ActivityClass instance somewhere else and use getter setter to get set this instance like:
public void setActivity(MyActivity activity) {
myActivity = activity;
}
public MyActivity getMyActivity() {
return myActivity;
}
Related
I'm running an AsyncTask to retrieve some info via HTTP.
I'm calling this method from my main activity (do_get_from_url() is triggered by a button click):
private void do_get_from_url() {
new getFromURL(this).execute();
}
The class that this calls is in the same .java file and starts as follows:
class getFromURL extends AsyncTask<Void, Void, String> {
private MainActivity activity;
getFromURL(MainActivity activity){
this.activity = activity;
}
...other code here...
String linkURL = activity.link_url.getText().toString();
String getFromURLrequestURL = activity.getString(R.string.short_url_request_url_base);
...other code here...
}
It seems that I need to use activity in order to access both the string resources and the UI element link_url from the main activity BUT the line this.activity = activity displays a warning in Android Studio that it is leaking a context.
Is there any way to avoid this?
Root cause: You are passing an activity as a context to a background thread. So the thread will keep a reference to the activity. As long as the thread running, the activity cannot be destroyed (by calling finish() method or users press back key to finish the activity). The term leak simply mean when an object or instance no longer used but the system cannot reclaim memory where they live on.
Solution: In Android you can use an API called WeakReference, Simply it will keep a weak reference to your object (in this case your activity), so when the activity get destroyed, it will not keep the reference anymore.
getFromURL.java
class getFromURL extends AsyncTask<Void, Void, String> {
private WeakReference<MainActivity> mainActivityWeakReference;
getFromURL(MainActivity activity){
mainActivityWeakReference = new WeakReference<>(activity);
}
...other code here...
MainActivity activity = mainActivityWeakReference.get();
// Always check this to make sure the activity haven't got destroyed yet.
if (activity != null) {
String linkURL = activity.link_url.getText().toString();
String getFromURLrequestURL = activity.getString(R.string.short_url_request_url_base);
}
...other code here...
}
Yes, there is. Correct way is to use a WeakRefrence like this
WeakReference<MainActivity> parent;
GetFromURL(MainActivity activity){
parent = new WeakReference(activity);
}
...other code here...
String linkURL = parent.get().link_url.getText().toString();
String getFromURLrequestURL = parent.get().getString(R.string.short_url_request_url_base);
...other code here...
When i am applying this Geocoder in my Activity and using context as this ,then i m redirected to another activity I'm my android application.So i want to know that writing this keyword in context signifies what?
The keyword this represents the instance of the current class.
You can access the properties and functions of the current class with this keyword.
For Simple Example,
Suppose, you activity name is MainActivity and you want to print Toast in Main Activity then just write:-
Toast.makeText(this, "Hello...", Toast.LENGTH_SHORT).show();
Here, just need to write this and automatically it takes instance of current Activity or class and display Toast message in Main activity.
this as Context
The Activity class extends the Context class in android. Therefore this keyword can be used in the Activity class to reference both an Activity object and a Context object as an object.
And also other Multiple Usage this keyword
It can be used to refer current class instance.
It used to invoke current class method (implicitly)
It can be passed as an argument in the method call.
It can be passed as argument in the constructor call.
It also used to return the current class instance from the method.
You can also refer this keyword in android for more understanding:-
this always signifies the current class object.. when you are passing this in activity its passing the object of activity which it self is a Context
Lets say you have an activity and you add a click listner on button (i am juts writing a sudo)
public class MyActvity extends AppcompatActivity{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
context=this;//here this will signigy the activity
navigationView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
this //here this will be the object of clickListener
MyActvity.this//Now this is signifying the context
}
});
}
}
I hope it helped
I want to know how can I send the context of an activity from ClassA.java to MainAddingItems.java.
I can pass the MainActivity.class as the argument but I am not able to pass the context.
Here is some of the code of ClassA calling the constructor of MainAddingItems
new MainAddingItems(MainActivity.class,"MainActivity Clicked",R.id.activity_main_linearLayout,"Profile Acitvity")
It will work ..make sure that you declerad it as public and static like below
Public static Context context ;
In your main activity
You can use any where that context in whole project
You can do this. If your constructor is:
MainAddingItems(Context context) {...}
Then from Activity1 you can just do:
Context context = Activity1.this; // Or getApplicationContext() or View.getContext() or whatever context you want
MainAddingItems(context);
Make your MainAddingItem class's constructor as this,
class MainAddingItem {
Context context;
MainAddingItem (Context context, rest of the parameters){
this.context = context;
}
}
Use the above constructor and pass the activity's context in the constructor's parameter.
new MainAddingItem (this, rest of the parameters);
Actually you are passing the context here . In android context is the current state of application . As an example if you are in a activity, then the context is the activity class itself , same for service and any other component of android
Let me give another example ,
Just try to show a toast message in onCreate method of any activity , considering your activity name is SimpleActivity you may write something like this
Toast.makeText(this "Understating context",Toast.LENGTH_LONG).show();
Or you may write the following
Toast.makeText(SimpleActivity.this "Understating context",Toast.LENGTH_LONG).show();
The first parameter of makeText method is context , and it works if you simply pass the class .
This is how you will pass activity as an argument
public SimpleClass{
AppCompatActivity mActivity;
public SimpleClass(AppCompatActivity mActivity){
this.mActivity = mActivity;
}
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SimpleClass newSimpleClass = new SimpleClass(MainActivity.this);
}
}
Just make Context as static like in MainActivity.
Public static Context contextToUse;
You can use like below :
MainActivity.contextToUse
Please let me know ,if it is helpful to you
I have a Main Activity and Child Activity.
MainActivity will intent the ChildActivity and call moveTaskToBack(true) at last to hide itself, but not finish().
On ChildActivity, i want to access the getContext(),getApplicationContext() method from MainActivity, so how can i do that?
Thanks you.
One way you can access using static variable, like this
In parent class declare
Public static String parentContext;
assign context in onCreate(...) method
parentContext = parentActivity.this;
or
parentContext = getApplicationContext();
Now in your ChildActivity
Context childContext = parentActivity.parentContext;
I am trying to integrate facebook-connect to my android application. All the examples i am seeing over the internet are creating the connection from an Android activity. I am doing something a bit different, the user can configure its connection to facebook from a custom preference. I was successfull when doing it for twitter and foursquare. However, the method Facebook.authorize requires an Activity as parameter, and since i am inside a preference, i am not able to find any reference to an activity object.
So my question here is, how to get a reference for an activity inside a preference?
Thank you all
T
I was able to get the Activity reference by casting the Context object to an Activity.
Activity activity = (Activity) context;
or with a custom activtity you can also do this
SettingsActivity activity = (SettingsActivity) context;
It's an old question, though I use following function with the com.android.support:preference preferences fragment:
public static Activity getPrefActivity(Preference pref)
{
Context c = pref.getContext();
if (c instanceof ContextThemeWrapper)
{
if (((ContextThemeWrapper) c).getBaseContext() instanceof Activity)
return (Activity) ((ContextThemeWrapper) c).getBaseContext();
}
else if (c instanceof Activity)
return (Activity) c;
return null;
}
Assuming you have an activity called MyActivity, can you just use MyActivity.class?