Pass data from activity to fragment with kotlin - android

I have an activity and 2 fragments on it, this activity got value from intent and I want to pass this value to a fragment, but when I do this with
supportFragmentManager.beginTransaction().replace(R.id.nav_host_fragment,fragment).commit()
it overrides fragments on each other,(I have a fragment and bottomnavbar)
I think there should be a better way, for example passing data without replacing, but when I do this there is no value given to fragment.
Activity Code: `
val bundle = Bundle()
val fragment = ResultFragment()
bundle.putString("BMI", bmi)
fragment.arguments = bundle
supportFragmentManager.beginTransaction().replace(R.id.nav_host_fragment,fragment).commit()
Fragment code:
val data = arguments
val value = data?.getString("BMI")
I tried using different ways to navigate between fragments, but did not work.

while getting data in fragment use requireArguments()
if (arguments != null) {
if (requireArguments().getString("BMI")) {
// your code
}

Related

Pass to fragment using Navigation from Activity

I have an activity with two fragments. Either fragment is located on container in activity. Also activity has toolbar with settings button. I should pass on settings fragment using Navigation by click on settings button, but i have problems with it, because findNavController(R.id.home_nav).navigate(R.id.action_second_fragment_to_settings_fragment)
works if we pass to settings screen and second fragment is active, but from first active will be crash.
What do i need to do for solving this problem? I used just actions in Navigation component for passing between fragment. May be there is useful solution for this task
if your navController in MainActivity, with this code you can access to navController and send data to fragment.
load new fragment :
val bundle = Bundle()
bundle.putString("id", id)
(activity as MainActivity).navController.navigate(R.id.orderDetailFragment, bundle)
for get data in onViewCreated in fragment :
arguments?.let {
if (it.getSerializable("id") != null) {
val id = it.getString("id")
}
}
i hope it's useful

kotlin- Bundle pass null to other fragments

I have simple app that has 1 activity and two fragments one of them display RecyclerView with OnClickListener to replace the fragment
now I need to send data from that arraylist RecyclerView with the click to other fragment and I don't know where I must type the Bundle and how
Your main culprit is ft1.replace(R.id.MainFram,SubMark()) instead you must use ft1.replace(R.id.MainFram,subMark) subMark variable. You are calling new instance of Fragment instead of fragment with bundle. Use these piece of code
val bundle = Bundle()
bundle.putString("data", "nasser")
val subMark = SubMark()
subMark.arguments = bundle
var ft1 : FragmentTransaction = supportFragmentManager.beginTransaction()
ft1.replace(R.id.MainFram,subMark) ft1.commit()
And access data with
String name = getArguments().getString("key");

Check which Activity loads a fragment

Is there a way to check which activity loads a fragment from within the fragment? I have a user profile fragment which is loaded from 2 different activities but only one passes a value in, so when getting values from the bundle when the fragment loads from the activity that doesn't pass a value throws a nullpointerexception. Or is there a better way to pass the value into the fragment so the fragment can get the value only when loaded from this specific activity?
You can simply do this check in your fragment:
if(getActivity() instanceof SomeActivity){
//do something
}
You can also cast the getActivity() call if you are sure which Activity it is (and then call methods from that Activity).
You can define two static methods (also known as Static Factory Methods) which returns instances of your Fragment with the parameters you want to pass with bundle like the following code:
private static final String BUNDLE_VALUE_KEY = "value";
#NonNull
public static YourFragment newInstance() {
return new YourFragment();
}
#NonNull
public static YourFragment newInstance(#NonNull String yourValue) {
final YourFragment instance = new YourFragment();
final Bundle args = new Bundle();
args.putString(BUNDLE_VALUE_KEY,yourValue);
instance.setArguments(args);
return instance;
}
In your Activity which you want to pass the value you can use:
final YourFragment fragment = YourFragment.newInstance(value);
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
In other Activity you can use:
final YourFragment fragment = YourFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
And in onCreate method of your Fragment you can check arguments and init your value like the following code:
final Bundle args = getArguments();
if(args != null){
yourValue = args.getString(BUNDLE_VALUE_KEY,null);
}
So if your Fragment is attached to the Activity which passes data you'll have it. If the Fragment is attached to other Activity you'll have the initial value (in the example it's null)
Or you can check the instance of Activity which Fragment gets attached. (Not best practice)
if(getActivity() instanceof YourActivityWhichPassesData){
yourValue = getArguments().getString(BUNDLE_VALUE_KEY,null);
}

Find out in which activity fragment was added

So basically I'm using same type of fragment in two different activities and I want to create and initialize some variable in the fragment only if it was added from specific activity. My question is how can I programmatically find out in which activity the fragment was added.
there're two main ways of achieving it:
the less modular approach, you simply check using instanceof
if(getActivity() instanceof MyActivity)
and the more modular approach, you pass some arguments to the fragment on the moment you'll add it to the transaction:
// this during the transaction to pass extra parameters to the fragment
Fragment f = new MyFragment();
Bundle b = new Bundle();
b.putBoolean("doExtraCode", true);
f.setArguments(b);
then inside the fragment:
// check if should execute extras
Bundle b = getArguments();
boolean doExtraCode = b == null? false: b.getBoolean("doExtraCode", false);

Android: Passing a non-primitive ArrayList type from one fragment to another in a bundle

I currently have this Custom ArrayList:
ArrayList<PlaceDetails> place_list = new ArrayList<PlaceDetails>();
which will be populated during the onCreateView() portion.
I am unsure as of how do I pass this ArrayList in a bundle from this fragment class to another fragment class. Below is the snippet of my codes:
public void Map(View view){
if(hasConnection() == true){
Bundle b = new Bundle();
// how should I be passing the ArrayList in this bundle?
FragmentTransaction ft = getSherlockActivity().getSupportFragmentManager().beginTransaction();
TOnlineMapViewFragment mapfrag = TOnlineMapViewFragment.newInstance(b);
ft.replace(R.id.container, mapfrag).addToBackStack(null).commit();
}
}
So I've created the bundle and I wanted to pass it to the next fragment with the newInstance() method. How should I do this?
Consider implementing Parcelable interface in your classes. Then you would be able to store PlaceDetails in Bundle and pass it to setArguments() method.
I've found a tutorial: http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/
I haven't testes it but it looks good.
Are you really sure a bundle is really needed?
TOnlineMapViewFragment mapfrag = TOnlineMapViewFragment.newInstance(b);
mapfrag.setPlaceList(place_list)
Should be trivial to create setPlaceList(ArrayList<PlaceDetails> place_list) ...

Categories

Resources