Passing Data Between Fragments to Activity

Send data from activity to fragment in Android

From Activity you send data with intent as:

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}

Passing Data Between Fragments to Activity

Pass data from each fragment to activity, when activity gets all data then process it.
You can pass data using interfaces.

Fragment:

public class Fragment2 extends Fragment {

public interface onSomeEventListener {
public void someEvent(String s);
}

onSomeEventListener someEventListener;

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
someEventListener = (onSomeEventListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement onSomeEventListener");
}
}

final String LOG_TAG = "myLogs";

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment2, null);

Button button = (Button) v.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
someEventListener.someEvent("Test text to Fragment1");
}
});

return v;
}
}

Activity:

public class MainActivity extends Activity implements onSomeEventListener{

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Fragment frag2 = new Fragment2();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment2, frag2);
ft.commit();
}

@Override
public void someEvent(String s) {
Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1);
((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s);
}
}

Passing data between a fragment and its container activity

In your fragment you can call getActivity().

This will give you access to the activity that created the fragment. From there you can obviously call any sort of accessor methods that are in the activity.

e.g. for a method called getResult() on your Activity:

((MyActivity) getActivity()).getResult();

How to share data between fragments and activities in android

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.

Android passing data between Activities and Fragments

If you need to access the same data you shouldn't pass them through bundles. Passing data with bundles may slow down your application (Parcing data reduce performance).
Instead you can try a combination of Singleton and ViewModels.
For Examble.

class LoginViewModel(
private val userController : Controller
): ViewModel() {
fun login(){
userController.downloadUsers()
}
//some code...
fun getUser(name: String): User{
return userController.findUser(name)
}
}
class DetailsScreenViewModel(
private val userController : Controller
): ViewModel() {
//some code...
fun getUser(name: String): User{
return userController.findUser(name)
}
}

/**
* Singleton class
*/
class Controller(){
private var users = mutableListOf<User>()

/**
* Download users from a server.
*/
fun downloadUsers(){
users.add(User("Super User"))
users.add(User("Good User"))
}

/**
* Find a user.
*/
fun findUser(name: String): User{
return users.find { it.name == name } ?: throw NoUserFound()
}
}
class NoUserFound(): Exception()

data class User(var name: String)

How to pass values between Fragments

Step 1: To send data from a fragment to an activity

Intent intent = new Intent(getActivity().getBaseContext(),
TargetActivity.class);
intent.putExtra("message", message);
getActivity().startActivity(intent);

Step 2: To receive this data in an Activity:

Intent intent = getIntent();
String message = intent.getStringExtra("message");

Step 3: To send data from an activity to another activity, follow the normal approach

Intent intent = new Intent(MainActivity.this,
TargetActivity.class);
intent.putExtra("message", message);
startActivity(intent);

Step 4: To receive this data in an activity

  Intent intent = getIntent();
String message = intent.getStringExtra("message");

Step 5.: From an Activity you can send data to a Fragment with the intent as:

Bundle bundle = new Bundle();
bundle.putString("message", "From Activity");

// Set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

And to receive a fragment in the Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("message");

return inflater.inflate(R.layout.fragment, container, false);
}

How to send data from fragment to activity

The fragment will be attached to the activity which you launch from.

Thus, you can create a callback method in your activity which can be called from fragment using the activity context object.

Please see the below code snippet :

public class YourFragment extends Fragment{

OnCallbackReceived mCallback;

// Implement this interface in your Activity.

public interface OnCallbackReceived {
public void Update();
}

In your fragment :

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);

try {
mCallback = (OnCallbackReceived) activity;
} catch (ClassCastException e) {

}
}

// You can Call the event from fragment as mentioned below
// mCallback is the activity context.
mCallback.Update();

Activity :

public class MainActivity extends Activity
implements YourFragment.OnCallbackReceived {

// Implemented method.
public override void Update() {
// Write your logic here.
}

passing data through navigation between fragments android studio

You can pass a bundle object as the second argument in .navigate() and access it in your fragment with getArguments().

final Bundle bundle = new Bundle();
bundle.putString("test", "Hello World!");
Navigation.findNavController(view).navigate(R.id.action_qrSession_to_addSession, bundle);
public class MyFragment extends Fragment {

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// the string you passed in .navigate()
final String text = getArguments().getString("test");
}
}


Related Topics



Leave a reply



Submit