Getting activity from context in android
From your Activity
, just pass in this
as the Context
for your layout:
ProfileView pv = new ProfileView(this, null, temp, tempPd);
Afterwards you will have a Context
in the layout, but you will know it is actually your Activity
and you can cast it so that you have what you need:
Activity activity = (Activity) context;
This is something that I have used successfully to convert Context
to Activity
when operating within the UI in fragments or custom views. It will unpack ContextWrapper recursively or return null if it fails.
public Activity getActivity(Context context){ if (context == null) { return null; } else if (context instanceof ContextWrapper) { if (context instanceof Activity) { return (Activity) context; } else { return getActivity(((ContextWrapper) context).getBaseContext()); } } return null;}
- No
- You can't
There are two different contexts in Android. One for your application (Let's call it the BIG one) and one for each view (let's call it the activity context).
A linearLayout is a view, so you have to call the activity context. To call it from an activity, simply call "this". So easy isn't it?
When you use
this.getApplicationContext();
You call the BIG context, the one that describes your application and cannot manage your view.
A big problem with Android is that a context cannot call your activity. That's a big deal to avoid this when someone begins with the Android development. You have to find a better way to code your class (or replace "Context context" by "Activity activity" and cast it to "Context" when needed).
Regards.
Just to update my answer. The easiest way to get your Activity context
is to define a static
instance in your Activity
. For example
public class DummyActivity extends Activity{ public static DummyActivity instance = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Do some operations here } @Override public void onResume() { super.onResume(); instance = this; } @Override public void onPause() { super.onPause(); instance = null; }}
And then, in your Task
, Dialog
, View
, you could use that kind of code to get your Activity context
:
if (DummyActivity.instance != null){ // Do your operations with DummyActivity.instance}