getActivity() with in FragmentActivity: android
Solution 1
A FragmentActivity
is an instance of Activity
(in Java style: FragmentActivity extends Activity
).
So there is no point calling getActivity
because a FragmentActivity
is already an Acivity
, so just calling/using this
will work. Also there is no method called getActivity
in the FragmentActivity
class. In other words your B class is extending an Activity
instance.
So inside your A (or B) class you could use this code snippet to get the activity instance:
Activity test = (Activity) this;
But if your B class extends Fragment
then the getActivity
call would have worked.
Solution 2
FragmentActivity
is an alternate to Activity
in support package. Since your class B
extends FragmentActivity
and later your class A
extends class B
, therefore your class A
is also referring Activity
(a.k.a FragmentActivity
).
In short, you dont need to call any method. simply use this
keyword to refer to your activity instance.
![Shikha Shah](https://i.stack.imgur.com/uDKZ9.jpg?s=256&g=1)
Shikha Shah
Currently working as a SDET @ Citrix Systems. Past Experience : Worked as an Intern @ Citrix Systems, Worked as an iOS and Android developer @AventuSoft LLC.
Updated on May 11, 2020Comments
-
Shikha Shah about 4 years
I am using this class A which extends another abstract class (and this abstract class extends FragmentActivity) and in one of my function with in A class I want to get getActivity() for my current activity A. But whenever I use getActivity , It gives me error that getActivity() method is not defined type for my class. Please help me !! How can I achieve this??
Code for my class A
public class A extends B { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.voicing); //doing another initializations and stuff// } }
code for class B
public abstract class B extends FragmentActivity { FragmentAdapter mAdapter; ViewPager mPager; PageIndicator mIndicator; }
-
Shikha Shah almost 12 yearsThanks a Lot!!!! It worked!!!..Sometime straight things seems complicated...Thanks a lot again!!!
-
Shikha Shah almost 12 yearsHey I am confuse here..I dont know for whom I should accept as answer...as I can accept only one answer..:)
-
wallerjake over 10 yearsExcellent post. It's so simple for some reason getActivity() wasn't working when I thought it should.