how to pass data from one fragment to a replaced fragmnet - android

Having Fragment A and B, B is kinda of extended A. The UI data update from B need to store back in A and A's UI makes decision whether to save to database.
So A is put on the backstack first, then at some time it needs B and B is put on the backstack and in the holder with 'replace()'.
Passing data to B could be don by argument.
How to pass data back from B fragment to the A fragment (if A is 'replaced()' by B on the holder and currently not showing or 'existing')?
Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment bFrgmt = new B();
bFrgmt.setArguments(args);
getFragmentManager()
.beginTransaction()
.replace(R.id.holder, bFrgmt, TAG_B_FRAGMENT)
.addToBackStack(TAG_B_FRAGMENT).commit();

From Developers website:
Often you will want one Fragment to communicate with another, for
example to change the content based on a user event. All
Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
First send data from fragment to activity, then receive this data in activity, then from Activity you can send data to Fragment with intent and to receive in fragment onCreateView method.
You can communicate among fragments with the help of its Activity. You can communicate among activity and fragment using this approach.

Related

Send Data from Activity A to Fragment One of a Tabbed Activity B

i need an approach how to handle this topic:
i have create a Mainactivity (A) and a Tabbed Activity (B) that contains 3 Tabs (Fragment One, Fragment Two and Fragment Tree)
how to send a string from the Mainactivity to the Fragment One without starting the Tabbed Activity.
when i use bundle
let say: in MainActivity
Bundle bundle=new Bundle();
bundle.putString("key", editText.getText().toString());
BlankFragmentTab1 fragment = new BlankFragmentTab1();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.frag,fragment).commit();
and inside Fragment One i get the String with getarguments.getString("key")
i get a nullpointerexception.
the approach works only by the communication between the Fragments and its container Activity.
thank you very much for your help
LieForBananas is correct.
You can not interact with your FragmentOne without calling its host activity.
However you can use SharedPreferences instead of Bundle for retrieving data.

Passing data between fragments for signup

I am singing up a user in 2 fragments in android. First fragment will have personal information and second fragment will contain educational information. I am using fragments inside a viewpager. I want to store the whole data in student object. How do I pass student object from first fragment to second fragment?
in your first fragment
Bundle bundle=new Bundle();
bundle.putSerializable("tag", user);
FragmentTwo frag =new FragmentTwo ();
frag.setArguments(bundle);
in your second fragment
User user = (User) getArguments().getSerializable("tag");
As per Android Developer website All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
For more details you can look up http://developer.android.com/training/basics/fragments/communicating.html

Pass data to previous fragment

I have two Fragments A and B. I am going from fragment A to Fragment B using Following method.
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new B()).addToBackStack(TAG).commit();
Now I want to send data to from fragment B to Fragment A i.e Previous Fragment.
Can you please give me an idea about how to send data to previous Fragment.
Thanks
Check the documentation about Fragments and its communication.
Do you want to pass info from one fragment to another? One fragment shouldn't know about other fragments. Make the fragment B communicate with its activity through an interface and make the activity pass the data to fragment A
You can communicate between fragments through Activity where you are replacing fragments.
Pass data to activity and then call method of that fragment where you want to update data.
2.Other way you can take a variable in Activity and save the data to this variable and when another fragment (Fragment A) is loaded(Resumed) then show data from Activity variable by getting
((HomeActivity)getActivity).variableName;
You create a subclass of Fragment called MyFragment that A, B are instances of it. Then create a static factory method take a MyFragment as param like:
public static MyFragment newInstance(MyFragment a){
MyFragment b = new MyFragment();
MyFragment b.a = a;
return b;
}
b.a is a field of MyFragment. Then you can use reference a to send data.

Refreshing a fragment view from MainActivity

So I currently have an app that has 4 tabs (fragments). They are fragments A,B,C,D, in that order.
Fragment A is the first view opened (along with B because viewPager loads the view before and after the current view).
When I click a button in Fragment A, it sends Data back to MainActivity and then sends that data out to Fragments B and C.
However, this is where the issue comes into play. Since Fragment B was already called, the View isn't updated once I click the button and send the data over, but Fragment C is because the view wasn't called before.
Is there any way that I can remedy this?
You can do it a few ways right.
Just set the data to the fragment and have it update its views
Have all the fragments like B and C register themselves to recieve data from the MainActivity and when MainActivity gets it's data set you tell all the registered receivers of the new data
Recreate the fragment
Use an event bus and tell all subsribers of the new data and MainActivity, Fragment B would get notified of new data. Fragment C would get its data when created by MainActivity
I think this list is pretty endless tbh
The key here is the fragments need to fetch the data from the actvitiy aswell as be updated by the activity. In which case you need to break your UI update behaviour out of onCreateView and into its own updateUI() function. updateUI(MyData) can then be called from onCreateView and also called in a setMyData() on the fragment. Just make sure you check the isAdded flag in setMyData.
This pretty much says it all:
http://developer.android.com/training/basics/fragments/communicating.html
I used a simple fragment communicator that allows the activity to call the fragment, and the same for a fragment to talk to the activity.
You can change the views with the new data based on calling the method from within the activity. The way I do it is set the fragments in the activity then pass them into the page adapter this way I can call the methods within the fragment and implement the fragmentcommunicator interface on the fragments.
You can honestly even avoid the interface if you want, but if you are going to include the same method in all the fragments to talk to them it is easiest.
If you show code, I can show you a quick example.

Fragments, Parameters, and ActionBar 'Up' Navigation

So I am trying to get some experience with Fragments, but I'm finding some roadblocks.
My current situation is as follows.
I have an activity that displays a List whose content is determined by Extra Intent parameters sent from the 'calling' activity.
This List activity uses ListFragment declared in the XML like so:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:background="#color/black">
<fragment class="com.pixlworks.NLC.DirectoryBrowse$ListingFragment"
android:id="#+id/listing"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Currently I get the parameter that indicates the type of content directly in the Fragment by accessing the Extra data of the Activity Intent (or saved Bundle if available):
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null)
mListingType = savedInstanceState.getString(Utils.DIRECTORY_TYPE_STORE_KEY);
else
mListingType = getActivity().getIntent().getStringExtra(Utils.DIRECTORY_TYPE_STORE_KEY);
// get content by type, create and set the adapter
}
Now part of my problem is that I am not sure this is the right way to 'pass' that parameter from the Activity to the Fragment.
On top of that, I am getting issues with this setup when using the Action Bar's UP Navigation. When I click on an item in this List Activity it goes to another activity showing the details of the selected item. From this detail activity:
If I use the back button, the List Activity is brought back from the stack as usual and everything works fine.
If I use the ActionBar's UP (despite following steps here), it would seem that a new instance is created instead of using the one in the stack and this new instance obviously is not getting the Extra parameter in the Intent. Since I am expecting the value to exist in the saved Bundle or in the Intent, my app crashes in this situation.
So to boil things down, I am not sure which of these to follow and how to make them work properly with 'UP' navigation:
A) Hold the 'type' parameter in a field in the Activity and save it in the Activity's Bundle onSaveInstanceState. In which case I am not sure how to then pass the value to the Fragment. In this case I would just need to make sure that UP calls the existing instance of the Activity List
B) Continue with my current setup of saving the value in the Fragment instead of the Activity, but again, how to handle the UP navigation correctly?
I know it is kind of multiple things I am asking here at the same time, but they are all connected, so I hope that I can get some help on this.
Thanks for any help in advance!
The UP navigation makes more sense to be used within the same activity level. That is the intention of the codes that you followed in the developers page. Because you started a new activity, if you want to return to previous activity like the back button you will need to call finish() to destroy the details activity first.
As for passing data from activity to fragment, when you create a new instance of fragment, you can pass the data to it as bundle, for example:
// in fragment class
public static MyFragment newInstance(Bundle arg) {
MyFragment f = new MyFragment();
f.setArguments(arg);
return f;
}
When you create a new fragment, you can call:
// in activity
Bundle arg = new Bundle();
int info = ...;
arg.putInt("INFO",info);
...
MyFragment mFragment = MyFragment.newInstance(arg);
Finally, to get the data in fragment:
int info = getArguments().getInt("INFO");
...
Instead of directly calling MyFragment mFragment = new MyFragment() to instantiate the fragment, you should use a static method to instantiate it. This is to prevent some crashes which might happen if you rotate the screen and the framework complains that it couldn't find a public empty constructor.
UPDATE
To answer your questions:
1) Say you start from activity A -> activity B. Then in activity B you press the up button. By logic of use, the up button will not bring you back to activity A, because its intention is to navigate one level up,but still inside, activity B. To return to activity A, you need to call finish() to destroy activity B first.
2) If your fragment is created in xml, you still can set arguments. In your xml, you set an id for the fragment android:id="#+id/fragment_id", then
// in activity
FragmentManager fm = getSupportFragmentManager(); // or getFragmentManager() if you don't have backward compatibility
MyFragment mFragment = fm.findFragmentById(R.id.fragment_id);
Bundle arg = new Bundle();
// put data blah blah
mFragment.setArguments(arg);
Just make sure you set the arguments before you use the fragment.
Simply said, intent is used when you pass data between calling activities; bundle is used when you want to pass data from activity to fragment.

Categories

Resources