Ali Azimi
Ali Azimi

Reputation: 404

How to share data between fragments and activities in android

I am new to android.
Can anyone please tell me if it is possible to share data between activities and fragments using java interfaces. I have studied OOP but I am still stuck in interfaces and abstracts classes. I think if I implement a class on many activities, I will be able to share data like passing data from one activity and getting it from another.
Am I right about it? Please help me

Upvotes: 1

Views: 2074

Answers (3)

Jaime
Jaime

Reputation: 388

Android has standards for setting and getting data in activities and fragments

To send data between activities

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("YOUR_INT", 1);
b.putString("YOUR_STRING", "Hello");
intent.putExtras(b);
startActivity(intent);

To send data to a fragment from an activity

// Declare a static method on your fragment 'New Instance'
public static MyFragment newInstance(int yourInt, String yourString) {
    MyFragment myFragment = new MyFragment();

    Bundle args = new Bundle();
    args.putInt("YOUR_INT_KEY", yourInt);
    args.putString("YOUR_STRING_KEY", yourString);
    myFragment.setArguments(args);

    return myFragment;
}

// Get the data inside your fragment
getArguments().getInt("YOUR_INT_KEY", 0); //Default value is zero if no int was found


// Instantiate your fragment wherever
MyFragment f = MyFragment.newInstance(1, "Hello");

Upvotes: 1

James Palfrey
James Palfrey

Reputation: 803

For between activities you can putExtra values such as below:

Intent intent = new Intent (this, newActivity.class);
intent.putExtra("someKey", someValue);
intent.putExtra(bundle);
startActivity(intent);

To get it inside your activity:

getIntent().getExtra("someKey");

For moving values between fragments i'd suggest using bundles:

//Where mainlayout is the top level id of your xml layout and R.id.viewProfile is the id of the action within your navigation xml.
       NavController navController = Navigation.findNavController(getActivity(), R.id.mainlayout);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("uid",snapshot.getKey());
                                    navController.navigate(R.id.viewProfile,bundle);

to retrieve this value within your fragment:

String game = getArguments().getString("game");

Hopefully that helps.

Upvotes: 1

zedlabs
zedlabs

Reputation: 523

use intents and them use the putExtra() and getExtra() to pass and recieve information, alternatively you can pass them as NavArgs() when using the jetpack navigation library.

intents in java

navigation

Upvotes: 1

Related Questions