Pass data from fragment to activity - android

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 .

Related

Android: Pass instance of MainActivity to Fragment

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();

Changing variable's value of fragment from the activity

I have an activity like this:
There are 2 buttons A and B on toolbar and a frame for fragment to take over. Say I have a string variable named button_type in fragment.
I want to have a system so that when I click button A in activity, the button_type in fragment sets to A and when I click button B in activity, the button_type in fragment sets to B.
How to do this?
Please note that I may click the buttons (A,B) when the fragment is already active (its not like after I click one button, the fragment comes.)
Thanks in advance.
Edit:
Currently I am trying this:
In MainActivity I get similar string button_type and set it as A or B according as button click and use the method:
public String getData(){return button_type;}
And in fragment I use: button_type= activity.getData(); in onViewCreated.
But it only seems to have the initial set value of A and B (which is A) and does not change when another button is clicked.
I think the best way if you use an interface for managing text in the fragment. the fragment will implement the interface. When the button click call the function in the fragment which is implemented by fragment.
Another way you can create an object of the fragment using findFragmentByTag() or findFragmentById() and then call the function in the fragment which handles the text.
Create an interface with methods onClickA(String buttonType) and onClickB(String buttonType).
Then create an object that implements this interface (or make fragment implement this interface by itself). I'll call this object listener.
call setButtonType(String buttonType) in listener methods implementation.
Then pass your listener to activity (you can get an instance of parent activity in fragment with getActivity() and cast it to your activity class) and in onClickListener of button A (in activity) call listener.onClickA(yourString) and do the same thing for button B.

Activity to RecyclerView Adapter Communication(Recyclerview in Fragment)

I have a Activity which contains a fragment with recyclerview.
The recyclerview has few editable fields and need to put validations on clicking a button on activity.
Please let me know the solution or any techniques to overcome this problem statement
use this (click here ) functionality for data sharing between Fragment to fragment , Fragment to Activity and Activity to Activity
1) in your onCreate declare the BUSand register it
Bus bus = new Bus();
bus.register(this);
2) send data or any action using
bus.post(<your data or any Item>);
3) don't forgot to unregister in your onestroy
bus.unregister(this)
You can get that fragment instance either by 'ID' or by tag (you would need to give a tag while adding this fragment).
Now you can call any public method of that fragment using its instance.
For Example (Using tag), if you want to call a public method 'show()' of FragmentA. Then while adding it to the activity give it a tag like this:
Fragment fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
.add(R.id.fragment_container,fragmentA,"YOUR_TARGET_FRAGMENT_TAG").commit();
And to get its instance (on a button click or as required):
FragmentA fragmentA = getFragmentManager().findFragmentByTag("YOUR_TARGET_FRAGMENT_TAG");
fragmentA.show();
Declare in your fragment the RecyclerView as public
Declare in your activity the fragment as variable
in your activity on click listener get the recyclerview with
fragment.recyclerview

How to pass data from Activity to fragment inside fragment

I have an Activity. It adds Fragment A dynamically. Fragment A contains static added (by xml) child Fragment B. How can I pass data from Activity to Fragment B when i add Fragment A to Activity?
I know next approach:
Implement interface getter in Activity and call getter method from Fragment B
I'd like to know, are there another ways to do it?
I tried set arguments from Activity to Fragment A, find Fragment B by child fragment manager and set arguments from Fragment A to Fragment B.
But Fragment B created earlier than Fragment A, so i had exceptions..
Well there are more than one ways to accomplish that. one of the way is
Create a function public void setData(Data data) in your Fragment B
Transfer your data from Activity to Fragment A. Since your Fragment B is added by fragment tag in xml. create ref to your Fragment B object in Fragment A. Now you have the reference to Fragment B in A.
Now Simply call the function (created in Fragment B) in Fragment A and pass the data which you have received by the Activity
Other way..
In Fragment B you can call getActivity() and type cast it in to your Activity class type and call its method which can return the desired data
This sample by google should resolve all your Issues:
https://developer.android.com/training/basics/fragments/communicating.html
You can try EventBus to pass data from Activity to your Fragment B. In your activity call this EventBus.getDefault().post(new MessageEvent());
And then you just need to register EventBus in onCreateView of Fragment B
EventBus.getDefault().register(this);
And then
#Subscribe
public void onEvent(MessageEvent event){
// DO SOMETHING
}

Use a dynamic Activity name while calling it's method from a fragment

Ok, so I've a Fragment inside which I use getActivity().getClass().getSimpleName() to get the name of the activity that contains it.
Now, I've a method called sampleMethod() inside that activity, and to call it from the fragment I use ((MyActivity) getActivity()).sampleMethod(); This works fine as well.
My question is that how can I use the activity name in the statement ((MyActivity) getActivity()).sampleMethod(); dynamically. Obviously, I do get the name from getActivity().getClass().getSimpleName().
So what I want is something like
`((getActivity().getClass().getSimpleName()) getActivity()).sampleMethod();
Syntactically, the above is incorrect. What's the correct way?
All the Activities that include this fragment should implement an interface, let's say
interface Sample {
public void sampleMethod();
}
then in your fragment
((Sample)getActivity()).sampleMethod();

Categories

Resources