Passing Data Between a Fragment and Its Container Activity

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 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.
}

How to get data from fragment to another activity? (Not container activity)

if you're routing from fragment to another activity, you can put you data into the intent using the putExtra and then receive in the activity using getExtra.

Inside the fragment,

Intent profileActivityIntent = new Intent(context,ProfileActivity.class);
profileActivityIntent.putExtra("dataKey",data);
startActivity(profileActivityIntent);

And then inside the ProfileActivity's onCreate method,

//assuming that data is a string
String dataFromFragment = getIntent().getStringExtra("dataKey");
Log.i("Data from fragment",dataFromFragment);

You are in no need of using the interface method. (If you have to route from one fragment to activity).

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

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


Related Topics



Leave a reply



Submit