I need the MainActivity-object as context in a Fragment-object.
Passing MainActivity as 'this' to a custom constructor of a Fragment-class works only when starting up the app. When rotating it calls the standard, null-argument-constructor via super.onCreate(savedInstanceState);
Creating a new instance of MainActivity in Fragment does not work either. E.g:
MainActivity ma = new MainActivity();
AdapterTasks at = new AdapterTasks(ma,title, subt, imgid);
-->System services not available to Activities before onCreate()
How can I get a reference from the MainActivity object to a Fragment-object??
If using Java, you can simply call getActivity()
If you're using Kotlin, you can also use requireActivity() which returns a non-null where getActivity() returns nullable, causing you to have lots of null checks in your code.
Within a Fragment, simply call this.getContext().
Or when you need to access something in the parent MainActivity:
MainActivity activity = (MainActivity) this.getActivity();
Both only works while the Fragment is attached to an Activity. Generally, this.getContext() prevents one to add too much code into the Activity, which rather should be added into the Fragment. One can do quite anything in a Fragment, while letting the Activity inflate it.
You don't need to pass the MainActivity.
On your fragment, use this:
activity = (MainActivity) getActivity();
Related
I have been looking for the answer everywhere but can't find the right one. I have tried onAttach methods etc, nothing works.
My goal is to change int value from the fragment inside activity which the fragment is called from or call a function which is inside the activity from the fragment.
As example 1:
I declare inside a Fragment: private int sample = 1;
Inside fragment I press the button and changes sample value to 2.
Example 2 with function:
I have a function inside a Fragment: public void sample(){}
Inside fragment I call the function sample()
How do I achieve this???
Maybe a duplicate of this one: Get current activity from fragment
You can get a Reference to the Activity by calling: getActivity() inside the fragment.
MyActivity myActivity = (MyActivity) getActivity();
Also if you want a reference to the Parent Fragment you just need to call: getParentFragment() inside the fragment:
MyParentFragment myParentFragment = (MyParentFragment) getParentFragment();
declare sample int variable globally and then assign value 2 to sample variable on button click . it will store value 2 and you can access any where in the same fragment .
Here in the doc I see that when I call getActivity() from my fragment class, I get the activity object that the fragment is currently associated with.
Suppose if fragment is associated with MainActivity then getActivity() doesn't give an object of the MainActivity class.
I'm unable to understand the difference between Activity activity; and Activity activity = getActivity();
Can anyone please explain me what this "Return the Activity this fragment is currently associated with" actually mean ?
Sorry for asking simple question.
Thanks.
Edit :
Went through this also, got a better understanding.
Association is simple.
Like in real life.
You are a student (Fragment).
You are getting knowledge in Chicago university (MainActivity).
As you are student you will be associated(attached) to university.
And if someone ask you :
-What is your university?(call getActivity() from Fragment)
You will answer :
-I from Chicago university(return object which refered to MainActivity)
If you change the university - you will respond differently.
That's all :)
The simplest answer would be:
"Return the Activity this fragment is currently associated with"
is activity to which this fragment was added.
Then to make things clear.
Activity activity;
This creates reference to activity object, and at start this one is empty (equal to null), until you write some activity object to it.
Activity activity = getActivity();
Here we do 2 things, firstly we create reference to activity object and then we write to this object value of function getActivity(), that if called from fragment will return associated activity.
And lastly why this is not MainActivity? Well it actually may or may not be. :)
And to check if this is actually MainActivity try this :)
Activity activity = getActivity(); // let get our activity
if (activity == null) {
/* this mean we are not attached to activity, possibly, fragment was not shown yet */
}
if (activity instanceof MainActivity) { // we check if activity is actually Main activity.
MainActivity mainActivity = (MainActivity) activity; // and if it is we can do something with it after we cast it.
}
Then at the end i will add one link that might also help: fragment
I am new to Android and learning to create fragments in Android by following this
example: Fragment Navigation Drawer
The code between Navigating between Menu Items and Add Navigation Header consists a method getActivity().
As the author didn't mentioned where to paste this code, I pasted in my MainActivity.java file
Is code between Navigating between Menu Items and Add Navigation Header pasted at correct location by me?
In method selectDrawerItem(MenuItem menuItem) there is a comment // Create a new fragment and specify the planet to show based on position
Does author expects me to add something over here.
The project files layout created by me on AndroidStudio is as follow:AndroidStudio Snapshot
You can use:
this Or `MainActivity.this`
Instead of:
getActivity()
An Activity has no getActivity() method.
Fragments have.
Because getActivity() says: "return the Activity which contains me".
And while Framents are contained in Activities, Activities themselves aren't.
It has been clearly pointed out that you cannot use the getActivity() method in an activity. Well, other alternatives apart from the this keyword could be;
Get current activity context : using the getContext()
This method can be called on a View like text view like so textView.getContext(); This will give the context of the activity in which the view is currently hosted in. i.e something like so View.getContext();
Get App-level context : getApplicationContext() this method returns the activity that houses the entire life cycle of the application.
In Fragment it is best to use onAttach() method to get the instance of an Activity attached to it.
here is a sample code:
#Override
public void onAttach (Activity activity) {
super.onAttach(activity);
}
I have an Activity Med.java having the following code:
this.deleteDatabase(db.getDatabaseName());
And another activity OrderDetails.java. But in this activity I have to add the class name also:
OrderDetails.this.deleteDatabase(db.getDatabaseName());
And another activity extending Fragment:
getActivity().deleteDatabase(db.getDatabaseName());
The first two are working fine. But i want to know why in the second activity I have to add the class name. And the third fragment code, it is not working at all. Please help
its using context.deleteDatabase(DATABASE_NAME);
inside a fragment might be when you are calling getActivity() then getActivity() can be null at that time. refer this getActivity() returns null in Fragment function
I am new at developing Android App.I am try to use a dynamic fragment which is used 2 activity like (show detail activity and edit details activity).How can I understand the fragment is used by which activity in onActivityCreated() method on MyFragment class. How can I handle this issue please help me thanks in advance
Try this in your Fragment onActivityCreated() method
FragmentActivity activity = getActivity();
if(activity instanceof show detail activity){
// Your ShowDetailsActivity
}else if(activity instanceof edit details activity){
// Your EditDetailsActivity
}
Jagadesh's solution will work, but fragments should operate independent of the activity.
You might want to consider adding a static method like "getInstance" that will accept parameters and return an appropriate instance of the fragment if some functionality shoudl be custom for the calling activity.
If you want to call the activity back, then you might think about having the activities register a callback or listener that the fragment can invoke.