Skip to content Skip to sidebar Skip to footer

How To Send Data From Activity To Fragment?(android)

I want to make use of some TextViews(cityField, updatedField) I have in my activity inside my fragment. I know it would have been easier to make use of them in the activity instead

Solution 1:

You should create a SharedViewModel and let the Activity set values of variables like cityField and updateField while the FragmentObserve the changes done to them, basically the Activity will Set and Fragment will Get

for more information about ViewModels check this: https://developer.android.com/topic/libraries/architecture/viewmodel

Solution 2:

You can access these instances from your fragment like this:

String cityFieldFragment = (activity as YourActivity).cityField;

String updatedFieldFragment = (activity as YourActivity).updatedField;

If I understood this right, the fragment lives in your activity, so you are able to access the data from it, just make sure that the instances are public.

Solution 3:

if the fragment is not already created you can make use of the constructor of the fragment and pass arguments to it. If the fragment is already created, create a method inside the fragment and invoke it in the activity.

Solution 4:

Let's say you want to pass it from an activity to another activity that contains fragments. First, you need to pass the data like so :

Intent intent = newIntent();
                    intent.setClass(FirstActivity.this, SecondActivity.class);
                    intent.putExtra("name", username);
                    intent.putExtra("pass", password);
                    startActivity(intent);

In this case, the fragment is inside the SecondActivity.java but to receive the data, we need code inside the Fragment.java instead of the SecondActivity.java.

Bundleextras= getActivity().getIntent().getExtras();
        if (extras != null) {
            getUsername = extras.getString("name");
            getPassword = extras.getString("pass");
        }

I haven't tried to pass the data directly to the fragment, but you can try with the same code. All you need to do is changing the intent instead of intent.setClass(FirstActivity.this, SecondActivity.class); to intent.setClass(FirstActivity.this, Fragment.class);.

Solution 5:

Have you tried with SharedPreferences?

in you MainActivity

// create sharedPrefences file with the name "info"SharedPreferencessp=this.getSharedPreferences("info",0);
// here the name and default value
sp.getString("name", "default value");
// create editor
SharedPreferences.Editoreditor= sp.edit();
// enter a new value
editor.putString("name", "new value");
// save changes
editor.apply();

in your Fragment

SharedPreferencessp= getActivity().getSharedPreferences("info",0);
Stringstr= sp.getString("name", "default value"); //will get you the new value you entered

Post a Comment for "How To Send Data From Activity To Fragment?(android)"