Danh Danh
Danh Danh

Reputation: 3

Passing argument from fragment to activity using SafeArgs

Using navigation graph, when i navigate from fragment to activity and also passing argument using safeargs, in activity, I cannot get argument. How can I get argument passing from fragment???

In fragment, I can get argument by getArgument() function, but not in activity.

In fragment I switch to another activity by:

findNavController().navigate(AFragmentDirections.actionAFragmentToBActivity(1)

and in B activity get argument in onCreate by :

val args = BActivityArgs.fromBundle(savedInstanceState!!)

but my app crash immediately.

Upvotes: 0

Views: 3748

Answers (4)

Tristan Elliott
Tristan Elliott

Reputation: 922

  • As stated in the official documentation HERE :

The Navigation component is designed for apps that have one main activity with multiple fragment destinations. The main activity is associated with a navigation graph and contains a NavHostFragment that is responsible for swapping destinations as needed. In an app with multiple activity destinations, each activity has its own navigation graph

  • A solution might be: rethink if the activity could be converted to a Fragment and then the newly created Fragment could be handled by the same Navigation Component. Thus allowing you to use the normal SafeArgs syntax to pass and retrieve data.

  • If you are still having problems with the SafeArgs plugin, I would highly recommend this medium article by the official Android team, HERE

Upvotes: 0

logancodemaker
logancodemaker

Reputation: 670

BActivityArgs.fromBundle(getIntent().getExtras()).getAField();

Work perfectly

Upvotes: 1

user7987898
user7987898

Reputation:

The accepted answer is not an answer to your question. As you point out: you cannot use getArguments() in your Activity, you can only do that in a fragment. However, in an activity you can get the data like this (java syntax):

String aField = BActivityArgs.fromBundle(getIntent().getExtras()).getAField()

So, just replace getArguments() with getIntent().getExtras() if you have an Activity on the receiving end.

Upvotes: 6

Shyak Das
Shyak Das

Reputation: 134

Check it out the Android Doc :-

https://developer.android.com/guide/navigation/navigation-pass-data#java

Send Data

@Override
public void onClick(View view) {
EditText amountTv = (EditText) getView().findViewById(R.id.editTextAmount);
int amount = Integer.parseInt(amountTv.getText().toString());
ConfirmationAction action =
       SpecifyAmountFragmentDirections.confirmationAction()
action.setAmount(amount)
Navigation.findNavController(view).navigate(action);
}

Get Data :-

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
TextView tv = view.findViewById(R.id.textViewAmount);
int amount = ConfirmationFragmentArgs.fromBundle(getArguments()).getAmount();
tv.setText(amount + "")
}

Upvotes: 0

Related Questions