Send data from activity to fragment - android

How can we send data from actvity to fragment? The Fragments are configured to actvity by using FragmentPagerAdapter.
Regards
mini.

You can pass a bundle to the fragment on creation with setArguments.
You can create methods to set the data on the Fragment class.

You can perform this by using Bundle
Send data from the activity (or fragment) :
int a = 5;
Bundle args = new Bundle();
args.putInt("INT_DATA_TAG", a);
Fragment fragment = Fragment.newInstance(args);
//Making fragment transaction
Retrieve data in the fragment
int a;
public static Fragment newInstance(Bundle args) {
a = args.getInt("INT_DATA_TAG"); //use a constant for the tag
return new Fragment();
}

Related

How to pass data from one activity to other activity fragment in android? [duplicate]

This question already has answers here:
Send data from activity to fragment in Android
(22 answers)
Closed 5 years ago.
I have passed some key and value data from one activity to another activity fragment so I have not get key and value to the last point in the fragment.
I have passing data using bundle.
In your activity create bundle to set to the fragment
Yourfragment fragment = new Yourfragment();
Bundle args = new Bundle();
args.putString(ARG_DATA, data);
fragment.setArguments(args);
Then load the fragment getSupportFragmentManager().beginTransaction().replace(R.id.your_container,fragment).commit();
Then in your fragment oncreate get the data like this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mData = getArguments().getString(ARG_DATA);
}
}
From activity to activity you can pass data by using Intent and when you get data in second activity in which you are creating fragments on creating fragment pass that data to fragment by making constructor in fragment or by using bundle. For further assistance and if you dont know how to do this do let me know.
Pass data from activity to activity:
Intent intent = new Intent(this, Second.class);
intent.putExtra("data", sessionId);
startActivity(intent);
get data in Second activity:
String s = getIntent().getStringExtra("data");
Pass data from activity to fragment:
Bundle bundle = new Bundle();
bundle.putString("data", "From Activity");
// set Fragmentclass Arguments
FragmentOne fragment = new FragmentOne ();
fragment.setArguments(bundle);
get data from activity to fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("data");
return inflater.inflate(R.layout.fragment, container, false);
}
Happy coding!!
You can pass data between Activity and Fragments and Fragment to fragment using below:
https://developer.android.com/training/basics/fragments/communicating.html
But to pass it between activity, you may use bundle data, (very few variables) or use Application Class to store it in memory, make sure you do not bloat up your memory.
New Android architecture components also do provide good options, it all depends upon your use:
https://developer.android.com/topic/libraries/architecture/index.html

Check which Activity loads a fragment

Is there a way to check which activity loads a fragment from within the fragment? I have a user profile fragment which is loaded from 2 different activities but only one passes a value in, so when getting values from the bundle when the fragment loads from the activity that doesn't pass a value throws a nullpointerexception. Or is there a better way to pass the value into the fragment so the fragment can get the value only when loaded from this specific activity?
You can simply do this check in your fragment:
if(getActivity() instanceof SomeActivity){
//do something
}
You can also cast the getActivity() call if you are sure which Activity it is (and then call methods from that Activity).
You can define two static methods (also known as Static Factory Methods) which returns instances of your Fragment with the parameters you want to pass with bundle like the following code:
private static final String BUNDLE_VALUE_KEY = "value";
#NonNull
public static YourFragment newInstance() {
return new YourFragment();
}
#NonNull
public static YourFragment newInstance(#NonNull String yourValue) {
final YourFragment instance = new YourFragment();
final Bundle args = new Bundle();
args.putString(BUNDLE_VALUE_KEY,yourValue);
instance.setArguments(args);
return instance;
}
In your Activity which you want to pass the value you can use:
final YourFragment fragment = YourFragment.newInstance(value);
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
In other Activity you can use:
final YourFragment fragment = YourFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
And in onCreate method of your Fragment you can check arguments and init your value like the following code:
final Bundle args = getArguments();
if(args != null){
yourValue = args.getString(BUNDLE_VALUE_KEY,null);
}
So if your Fragment is attached to the Activity which passes data you'll have it. If the Fragment is attached to other Activity you'll have the initial value (in the example it's null)
Or you can check the instance of Activity which Fragment gets attached. (Not best practice)
if(getActivity() instanceof YourActivityWhichPassesData){
yourValue = getArguments().getString(BUNDLE_VALUE_KEY,null);
}

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

How to parsing in a fragment?

I made an application which has an Activity that parses a XML file (XMLPullParser) and shows data in a Listview. It works.
In the same application I have another Activity in which I put different fragments in dependece of the selected item of the Navigation Drawer.
Now, my question is: how can I use the data, obtained in the Parsing activity, and manage them inside a fragment?
You don't have to send the whole parsed data to the fragment.
You can write an own Handler or Manager class to parse the file for you and keep it in the memory (It can be some Singleton stuff). Once you parsed it you just have to pass the ID of the item and the Fragment can get it out from your Handler.
You can pass whatever you like to the Fragment like this:
public static YourFragment newInstance(int index) {
YourFragment f = new YourFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
//To get out
//...
Bundle args = getArguments();
int index = args.getInt("index", 0);
//...

Pass parameter from activity to fragment

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.

Categories

Resources