Pass parameter from activity to fragment - android

I have an activity that calls to a web service and I want to pass these result to a fragment. Obviously the web service is invoked by an AsyncTask, so the fragment is loaded before getting result.
How can I pass this paramteter from activity's AsyncTask to fragment when is received?

You can implement a method inside your Fragment and call it when needed. For bidirectional communication between an Activity and a Fragment see http://developer.android.com/training/basics/fragments/communicating.html

Set bundle in your fragment.
Bundle args = new Bundle();
args.putInt("id",value);
Fragment newFragment = new Fragment();
newFragment.setArguments(args);
In your fragment get the bundle as
Bundle b = getArguments();
String s = b.getInt("id");

You could move the AsyncTask into the fragment.
But if you wish to keep your current set up, you should save the Fragment reference when you initialize it, and create a public function in the fragment that takes the new data as a parameter.
So the activity code could look like this:
MyFragment fragment = new MyFragment();
getFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit();
and then you could call:
fragment.updateData(myNewData);
Just make sure to do the appropriate null-checks, just to be safe.

Related

Sending data to Fragment of Fragment from Activity (Activity->Fragment->Fragment) on menuItemclick

I am trying to send a data from MainActivity (on MenuItem click) to a Fragment of its Child Fragment.
I have shown an image to understand better.
I want an event to be fired in DayFragment from the MainActivity when MainActivity menuclicked.
I cannot send when the fragment is being created as you know.
Any ideas (or) code to understand the idea would be helpful.
Guys, Negative vote would neither help you nor me.
I will explain in little detail.
I am going to show a datepicker dialog fragment on menu item click on MainActivity. I need to pass the date from MainActivity -> calendarfragment - > dayfragment.
I want the date in dayfragment to other process. Thats it.
Create a public method inside Fragment which the Activity will call upon item selection.
From that public method, using the instance of ChildFragment, call another public method inside ChildFragment to make the magic happen!
You can use Fragment.setTarget(Fragment fragment, int requestCode); , just in case
Use a Bundle. Here's an example:
Fragment fragment = new Fragment(); // replace your custom fragment class
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager(). beginTransaction();
bundle.putString("key","value"); // use as per your need
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(viewID,fragment);
fragmentTransaction.commit();
Bundle has put methods for lots of data types.
Then in your Fragment, retrieve the data (e.g. in onCreate() method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);
}

How to transfer data from one activity to a fragment with Firebase?

Hey I was wondering how I could transfer data from one activity to a fragment using fire base. I have edit text in the activity class and a list view in the Fragment.
I would like to display the information throughout the app database so that other users can see and edit the information too.
I dont know if the IDE matters but passing information to a fragment is usually done with fragment arguments. You need to create a static "newInstance" method in your fragment that you can call from the activity and pass whatever info to the fragment through it. Something like this:
public static mListFragment newInstance(String fromActivity) {
mListFragment fragment = new mListFragment ();
Bundle args = new Bundle();
args.putString("STIRNG_FROM_ACTIVITY", fromActivity);
fragment.setArguments(args);
return fragment;
}
You can then call the method from the activity like this:
FragmentManager fm = getFragmentManager().beginTransaction();
mListFragment fragment = new mListFragment();
fragment = mListFragment.newInstance("info_to_send");
fragmentTransaction.add(R.id.fragments_frame, fragment);
From here you can even persist the info across device screen orientation changes..
Just use firebaseRef to setValue() and set the value from the edittext.
Add ValueListener on the fragment to get the same value from dataSnapshot.
:D
https://github.com/firebase/quickstart-java/tree/master/database/src/main/java/com/google/firebase/quickstart

how to create same fragment with different arguments in viewpager

I want to create same fragment multiple times in view pager with different arguments how can i do it?
Now i have a static single argument constructor in a fragment which i call to initialize the fragment
Is there a simple way to do this.
You could use setArguments() method, for each of your Fragment. Do something like this:
Fragment myFragment = new Fragment();
Bundle data = new Bundle();
data.putString("data_1","Hello");
myFragment.setArguments(data);
Then in your Fragment, do this:
Bundle data = getArguments();
String data_1 = data.getString("data_1");

Find out in which activity fragment was added

So basically I'm using same type of fragment in two different activities and I want to create and initialize some variable in the fragment only if it was added from specific activity. My question is how can I programmatically find out in which activity the fragment was added.
there're two main ways of achieving it:
the less modular approach, you simply check using instanceof
if(getActivity() instanceof MyActivity)
and the more modular approach, you pass some arguments to the fragment on the moment you'll add it to the transaction:
// this during the transaction to pass extra parameters to the fragment
Fragment f = new MyFragment();
Bundle b = new Bundle();
b.putBoolean("doExtraCode", true);
f.setArguments(b);
then inside the fragment:
// check if should execute extras
Bundle b = getArguments();
boolean doExtraCode = b == null? false: b.getBoolean("doExtraCode", false);

Set arguments of fragment from activity

I want to pass arguments from my activity to a fragment, embedded into the activity. Fragment is embedded statically in xml layout.
I tried to call setArgument() like this:
setContentView(R.layout.detail_activity);
DetailFragment detailFragment = (DetailFragment) getFragmentManager().findFragmentById(R.id.detailFragment);
detailFragment.setArguments(getIntent().getExtras());
but it is already too late, because setArguments has to be called immediately after fragment's creation. The only was I see it to getArguments() and the change the bundle. Any better way?
AFAIK, you can't use setArguments() like that when you embed the fragment within XML. If it's critical, you'd be better off dynamically adding the fragment instead. However if you truly want the fragment to be embedded via XML, there are different ways you can pass along that data.
Have the Activity implement the fragment's event listener. Have the fragment then request the required parameters from the Activity at creation or whenever needed. Communication with Fragment
Create custom attributes that can be embedded in xml along with the fragment. Then during fragment's inflation process, parse the custom attributes to obtain their data. Custom fragment attributes
Create public setters in the fragment and have the activity use them directly. If it's critical to set them prior to the fragment's onCreate() method, then do it from the activity's onAttachFragment() method.
You have two options here
If you just need information in the activity's intent, then placing information from the intent into the fragment arguments just adds an unneeded step. You might just a well keep things simple and from your fragment call
Bundle data = getActivity().getIntent().getExtras();
If you need to add information that is not in the activity's intent then in you fragment create a no parameter constructor like:
public DetailFragment() {
this.setArguments(new Bundle());
}
then in your activity you can add whatever arguments you need with code like:
DetailFragment frg = (DetailFragment) getFragmentManager().findFragmentById(R.id.detailFragment);
frg.getArguments().putBundle("key", data);
the point here is to use the existing bundle object rather than trying to call setArguments() after the fragment has been attached to the activity.
Another way to pass data to Fragment is as following:
//In DetailFragment (for Instance) define a public static method to get the instance of the fragment
public static final DetailFragment getInstance(Bundle data) {
DetailFragment fragment = new DetailFragment();
fragment.setArguments(data);
return fragment;
}
And when attaching DetailFragment from inside Activity
Bundle data = new Bundle();
//Add data to this bundle and pass it in getInstance() of DetailFragment
fragmentTransaction.replace(R.id.frament_layout, DetailFragment.getInstance(data));

Categories

Resources