I want to receive data from class to fragment by Intent ,I try to do ,I write
Intent n = this.{getIntent()};
{the wrong here} ,but this code is not working ,so what i do ?
Activity Send Intent data to fragment
Bundle b = new Bundle();
b.putString("data", "abc");
// set Fragmentclass Arguments
Fragment frag = new Fragment();
frag.setArguments(b);
Fragment receive data with intent
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String data = getArguments().getString("data");
return inflater.inflate(R.layout.fragment, container, false);
}
For fragments, you can visit Send data from activity to fragment in android
Try this,
you can send data from activity using,
Bundle bundle = new Bundle();
bundle.putString("key", "value");
Fragmentclass fc= new Fragmentclass();
fc.setArguments(bundle);
and receive from this way in your fragment's onCreateView method,
String strtext = getArguments().getString("key");
that's it
Related
This question already has answers here:
Send data from activity to fragment in Android
(22 answers)
Closed 5 years ago.
I have passed some key and value data from one activity to another activity fragment so I have not get key and value to the last point in the fragment.
I have passing data using bundle.
In your activity create bundle to set to the fragment
Yourfragment fragment = new Yourfragment();
Bundle args = new Bundle();
args.putString(ARG_DATA, data);
fragment.setArguments(args);
Then load the fragment getSupportFragmentManager().beginTransaction().replace(R.id.your_container,fragment).commit();
Then in your fragment oncreate get the data like this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mData = getArguments().getString(ARG_DATA);
}
}
From activity to activity you can pass data by using Intent and when you get data in second activity in which you are creating fragments on creating fragment pass that data to fragment by making constructor in fragment or by using bundle. For further assistance and if you dont know how to do this do let me know.
Pass data from activity to activity:
Intent intent = new Intent(this, Second.class);
intent.putExtra("data", sessionId);
startActivity(intent);
get data in Second activity:
String s = getIntent().getStringExtra("data");
Pass data from activity to fragment:
Bundle bundle = new Bundle();
bundle.putString("data", "From Activity");
// set Fragmentclass Arguments
FragmentOne fragment = new FragmentOne ();
fragment.setArguments(bundle);
get data from activity to fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("data");
return inflater.inflate(R.layout.fragment, container, false);
}
Happy coding!!
You can pass data between Activity and Fragments and Fragment to fragment using below:
https://developer.android.com/training/basics/fragments/communicating.html
But to pass it between activity, you may use bundle data, (very few variables) or use Application Class to store it in memory, make sure you do not bloat up your memory.
New Android architecture components also do provide good options, it all depends upon your use:
https://developer.android.com/topic/libraries/architecture/index.html
This question already has answers here:
Send data from activity to fragment in Android
(22 answers)
Closed 6 years ago.
I have a query regarding fragment.
Scenario is: After I login, I am on an actiivity which have 3 fragments. For fragments I have used ViewPager. Now I have to use login username in one of my fragment. I have bought username from login page using putExtra. My query is how take that username to the fragments ??
From your BaseActivity send data with intent :
Bundle bundle = new Bundle();
bundle.putString("username", "From your BaseActivity");
// set Fragmentclass Arguments
Fragmentclass fragmentclass = new Fragmentclass();
fragmentclass .setArguments(bundle);
And in your Fragment onCreatView method :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String username= getArguments().getString("username");
return inflater.inflate(R.layout.yourFragment, container, false);
}
You can also use SharedPreferences.
Store the username or what so ever you want to save in SharedPreferences and use it anywhere in your app.
For your reference SharedPreferences Tutorials
From your activity you can send data with intent:
Bundle bundle = new Bundle();
bundle.putString("username", "abcd");
// set Fragmentclass Arguments
FragmentClass frag_one = new Fragmentclass();
frag_one.setArguments(bundle);
and add below code in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("username");
return inflater.inflate(R.layout.fragment_layout, container, false);
}
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