I want to receive data from an Activity to a Fragment.
In an Activity is easy:
Bundle b = getIntent().getExtras();
String flag = b.getString("flag");
Ok, for me, doesn't work
String flag = getIntent().getExtras().getString("flag");
Neither
String flag = getActivity().getIntent().getExtras().getString("flag");
Or.
Bundle b = getIntent().getExtras();
The error: "Unreachable code"
Any idea?
You can view that on Fragment documentation.
Create a newInstance funcion in your fragment to initialize the fragment and add data with setArguments, passing a Bundle.
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
Then get the arguments using:
Bundle args = getArguments();
int index = args.getInt("index", 0);
Related
I'm trying to send a Parcelable array from MainActivity to one of its fragment using bundle. My code is
Bundle bundle = new Bundle();
MyFragment fragment = new MyFragment();
bundle.putParcelableArray(key, MyParcelableArray);
fragment.setArguments(bundle);
When debugged, I found that MyParcelableArray is not null but bundle mParcelledData is null. Thus, it is throwing a null pointer error.
Why is this happening?
I'm retrieving code in the fragments onCreateView as below.
Bundle bundle = getArguments();
Parcelable[] parcelables = bundle.getParcelableArray(MainActivity.key);
getting null pointer in the above line.
While opening a fragment use below code
Bundle bundle= new Bundle();
bundle.putSerializable("data", MyParcelableArray);
ListFrag newFragment = new ListFrag ();
newFragment.setArguments(bundle);
While obtaining that bundle data in fragment use below code
Bundle b = getArguments();
ArrayList<collection> yourArrayList = (ArrayList<collection>) b.getSerializable("data");
I have a fragment with an ExpandableList which content is provided by a HashMap<String,List<String>>. This HashMap<String,List<String>> is filled in Fragment's Activity and i need to pass it to the fragment.
To do it, i was planning to do a Fragment transaction but i found the problem:
In the method "newInstance" of the fragment, when setting arguments to the Bundle, there is no method to put a HashMap.
Ex:
Bundle args = new Bundle();
args.putInt(ARG_PARAM1,index); //method .putHashmap doesn't exist.
So, how can i pass my hashmap in bundle to the Fragment? Please provide an solution for this one.Thanks in advance
To pass HashMap do this
MyFragment fr = new MyFragment(); // Replace with your Fragment class
Bundle bundle = new Bundle();
bundle.putSerializable("hashmap",mMap);
fr.setArguments(bundle);
To retrieve do this
HashMap<String,List<String>> mMap = new HashMap<String,List<String>>();
Bundle b = this.getArguments();
if(b.getSerializable("hashmap") != null)
mMap = (HashMap<String,List<String>>)b.getSerializable("hashmap");
Try using:
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, hereGoesYourHashMap);
as according to the docs:
https://developer.android.com/reference/java/util/HashMap.html
HashMap is Serializable
How can I get a value(String) from activity and then use it in Fragment?
errors are occurred
fragment.java
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
View rootView = inflater.inflate(R.layout.fragment_user_info,
container, false);
return rootView;
}
activity.java
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
UserInfoFragment fragobj = new UserInfoFragment();
fragobj.setArguments(bundle);
The error is a NullPointerException, correct?
This is because you read the arguments (in the fragment's constructor):
String strtext = getArguments().getString("edttext");
before you assign them (in activity after the fragment's constructor has already been called):
fragobj.setArguments(bundle);
Keep the constructor simple. Best solution is to create a static factory method newInstance(String edttext) according to this guide https://stackoverflow.com/a/9245510/2444099 like so:
public static UserInfoFragment newInstance(String edttext) {
UserInfoFragment myFragment = new UserInfoFragment();
Bundle args = new Bundle();
args.putInt("edttext", edttext);
myFragment.setArguments(args);
return myFragment;
}
Then use this factory method instead of constructor whenever you need to obtain a new fragment instance.
This is what's happening in your current code:
You create the Fragment
In the onCreateView() method, you get the arguments
You set the arguments in your Activity.
In other words, you're calling the arguments before you've set them. As per the Fragment Documentation, you should be using a static method to instantiate your Fragments. It would look something like the following.
In your Fragment class, add this code
/**
* Create a new instance of UserInfoFragment, initialized to
* show the text in str.
*/
public static MyFragment newInstance(String str) {
MyFragment f = new MyFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putString("edttext", str);
f.setArguments(args);
return f;
}
And now, in your Activity, do the following:
//Bundle bundle = new Bundle();
//bundle.putString("edttext", "From Activity");
//UserInfoFragment fragobj = new UserInfoFragment();
//fragobj.setArguments(bundle);
UserInfoFragment fragobj = UserInfoFragment.newInstance("From Activity");
Notice how now, you don't even need to create a Bundle and set it in your Activity class, it is handled by the static newInstance() method.
I have an Activity with two fragments and I need to pass a string from FragmentA to FragmentB.
To pass the data, I have this in my FragmentA:
Intent intent = new Intent(getActivity(), FragmentB.class);
intent.putExtra("name", "Mark");
startActivity(intent);
And to get the data, I did this in FragmentB
Intent intent = getActivity().getIntent();
Bundle b = intent.getExtras();
if(b!=null)
{
String name =(String) b.get("name");
nameTextView.setText(name);
}
But this is not working. Is there a specific way to pass a string from one fragment to another fragment?
If fragments are hosted by same activity-
You cannot cast an intent to Fragment. Fragment acts as a part of Activity, it is not an activity by itself. So to share a string between fragments you can declare a static String in Activity. Access that string from Fragment A to set the value and Get the string value in fragment B.
Both fragments are hosted by different Activities-
Then you can use putExtra to pass a string from Fragment A of Activity A to Activity B. Store that string in Activity B and use it in Fragment B.
to pass data between Fragments you can use setArguments(Bundle b). For instance:
public class FragmentA extends Fragment {
public static FragmentA newInstance(String name) {
Bundle bundle = new Bundle();
bundle.putString("name", name);
FragmentA f = new FragmentA();
f.setArguments(bundle);
return f;
}
}
You can do something like below,
Fragment fr=new friendfragment();
FragmentManager fm=getFragmentManager();
android.app.FragmentTransaction ft=fm.beginTransaction();
Bundle args = new Bundle();
args.putString("CID", "your value");
fr.setArguments(args);
ft.replace(R.id.content_frame, fr);
ft.commit();
To receive the data do the following,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("CID");
return inflater.inflate(R.layout.fragment, container, false);
}
Code in FragmentActivity 1 fragment A:
fb is the instance of the bean I created and ID is the parameter
Intent intent = new Intent(getContext(), FragmentActivity2.class);
intent.putExtra("id", fb.ID);
startActivity(intent);
Code in FragmentActivity 2 fragment Any:
fragmentA= (FragmentActivity2) getActivity();
String cust_id = fragmentA.getIntent().getExtras().getString("id");
I have 2 fragments: (1)Frag1 (2)Frag2.
Frag1
bundl = new Bundle();
bundl.putStringArrayList("elist", eList);
Frag2 dv = new Frag2();
dv.setArguments(bundl);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.the_fragg,dv);
ft.show(getFragmentManager().findFragmentById(R.id.the_fragg));
ft.addToBackStack(null);
ft.commit();
How do I get this data in Frag2?
Just call getArguments() in your Frag2's onCreateView() method:
public class Frag2 extends Fragment {
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle=getArguments();
//here is your list array
String[] myStrings=bundle.getStringArray("elist");
}
}
EDIT:
Best practice is read and save arguments in onCreate method. It's worse to do it in onCreateView because onCreateView will be called each time when fragment creates view (for example each time when fragment pops from backstack)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = getArguments();
}
Eg: Add data:-
Bundle bundle = new Bundle();
bundle.putString("latitude", latitude);
bundle.putString("longitude", longitude);
bundle.putString("board_id", board_id);
MapFragment mapFragment = new MapFragment();
mapFragment.setArguments(bundle);
Eg: Get data :-
String latitude = getArguments().getString("latitude")
You have a method called getArguments() that belongs to Fragment class.
in Frag1:
Bundle b = new Bundle();
b.putStringArray("arrayname that use to retrive in frag2",StringArrayObject);
Frag2.setArguments(b);
in Frag2:
Bundle b = getArguments();
String[] stringArray = b.getStringArray("arrayname that passed in frag1");
It's that simple.
Instantiating the Fragment the correct way!
getArguments() setArguments() methods seem very useful when it comes
to instantiating a Fragment using a static method.
ie Myfragment.createInstance(String msg)
How to do it?
Fragment code
public MyFragment extends Fragment {
private String displayMsg;
private TextView text;
public static MyFragment createInstance(String displayMsg)
{
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.setString("KEY",displayMsg);
fragment.setArguments(args); //set
return fragment;
}
#Override
public void onCreate(Bundle bundle)
{
displayMsg = getArguments().getString("KEY"): // get
}
#Override
public View onCreateView(LayoutInlater inflater, ViewGroup parent, Bundle bundle){
View view = inflater.inflate(R.id.placeholder,parent,false);
text = (TextView)view.findViewById(R.id.myTextView);
text.setText(displayMsg) // show msg
returm view;
}
}
Let's say you want to pass a String while creating an Instance. This
is how you will do it.
MyFragment.createInstance("This String will be shown in textView");
Read More
1) Why Myfragment.getInstance(String msg) is preferred over new MyFragment(String msg)?
2) Sample code on Fragments
for those like me who are looking to send objects other than primitives,
since you can't create a parameterized constructor in your fragment, just add a setter accessor in your fragment, this always works for me.
If you are using navigation components and navigation graph create a bundle like this
val bundle = bundleOf(KEY to VALUE) // or whatever you would like to create the bundle
then when navigating to the other fragment use this:
findNavController().navigate(
R.id.action_navigate_from_frag1_to_frag2,
bundle
)
and when you land the destination fragment u can access that bundle using
Bundle b = getArguments()// in Java
or
val b = arguments// in kotlin