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
Related
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();
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
How can I have an activity B, which pops up and partially obscures a "parent" activity A, continuously send update info to A?
The normal mechanism, of course, would be to send an Intent back to A. But this can only happen once, when calling finish().
I suppose another way would be to have a handler in A and let B post to the handler. Getting the handler from A to B could be done through a "global" Application member.
Is there a better way?
EDIT: Using DialogFragment appears to be a good solution. However there is a position issue with DialogFragment. Please see my new post: https://stackoverflow.com/questions/30471032/position-dialogfragmet-relative-to-view
As far as I know, an Activity always covers another Activity. At any point, Android could reclaim memory and destroy Activity A.
This means that you should manage your data differently. Either through your Application instance, if there is not much to share.
But you probably should consider another storage mechanism. What kind of data do you want to pass to your Activity A ? And what do you mean by "partially obscures"?
EDIT
I would suggest that your DialogFragment keeps a reference to your Activity. Take a look at the developer page. You can try to implement something like this:
In you Activity, when you would like to show your dialog:
void showDialog() {
DialogFragment newFragment = MyAlertDialogFragment.newInstance(
R.string.alert_dialog_two_buttons_title);
newFragment.setActivity(this);
newFragment.show(getFragmentManager(), "dialog");
}
In your DialogFragment class, simply implement a setter method:
public static class MyAlertDialogFragment extends DialogFragment {
Activity activity;
//rest of the code here
public void setActivity(Activity a){
this.activity = a;
}
private void notifyActivity(){
int level = aMethod();
activity.somethingHappened(level);
}
}
Now, everytime you would like to call a method of your Activity, use the reference you passed previously.
I would also make an Interface, and make your Activity implement it. Like this, you are not dependent on one specific Activity, but it could be any UI component. Hope it helps.
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.
I have been asked an interview question: Can a fragment exist without activity? I searched for answers but didn't get a proper answer and explanation. Can someone help?
Yes, you can do this anywhere:
new YourFragment();
As fragments must have a parameter-less constructor.
However its lifecycle doesn't kick in until it is attached. So onAttach, onCreate, onCreateView, etc. are only called when it is attached. So most fragments do nothing until they are attached.
It can exist as an object in memory (by creating it with new), but it needs to be attached to an Activity in order to appear on the screen, assuming it has any UI (fragments don't have to have UI).
A Fragment can exist independently, but in order to display it, you need the help of an Activity. The Activity will act like a container for the Fragment(s).
A fragment is not required to be a part of the Activity layout; you may also use a fragment without its own UI as an invisible worker for the Activity but it needs to be attached to an Activity in order to appear on the screen.
As soon as you create an instance of the Fragment class, it exists, but in order for it to appear on the UI, you must attach that fragment to an activity because a fragment's lifecycle runs parallel to an activity's lifecycle. Without any call to Activity's onCreate(), there will be no call for onAttach(), onCreate(), onCreateView() and onActivityCreated() of fragment and so it can't be started.
I read above top rated answer , i am not disagreeing but android already provides to make independent fragment without activity DialogFragment , which extends fragment . if you want show in full screen first extends DialogFragment then
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_FRAME, android.R.style.Theme_Holo_Light);
}
Android app must have an Activity or FragmentActivity that handles the fragment.
Fragment can't be initiated without Activity or FragmentActivity.