Passing data from one fragment to another - android

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

Related

Passing values from Activity to Fragment

I'm using Navigation drawer after login in my app. In Navigation drawer I am using a fragment called "profile" for displaying the user information. I want to passing data from loginpage activity to the profile fragment.
Bundle bundle = new Bundle();
Intent home = new Intent(LoginPage.this, HomeActivity.class);
startActivity(home);
bundle.putString("name", gname);
Profile profile = new Profile();
profile.setArguments(bundle);
And this is my Profile Fragment:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
name = this.getArguments().getString("name");
ntext.setText(name);
return inflater.inflate(R.layout.activity_profile, container, false);
}
But I am getting Null Pointer Exception. I can't understand what is the problem! If there are another way to pass Data from activity to fragment, please tell me!
You need to create a function in your Profile fragment called newInstance that creates the fragment and set the arguments through there, then returns the fragment with the arguments. Like this
public static Profile newInstance(String name){
Profile profile = new Profile();
Bundle bundle = new Bundle();
bundle.putString("name", name);
profile.setArguments(bundle);
return profile;
}
Then create the fragment in your activity like this
Profile profile = Profile.newInstance(gname);
And get the arguments how you have been doing in the onCreate in the fragment.
You also should be creating the Fragment in the activity you are using it in. So if it's in your home activity you will want to pass the data from the login activity, then build the fragment in the onCreate for the home activity.
Intent home = new Intent(this, HomeActivity.class);
intent.putExtra("name", gname);
startActivity(home);
in the HomeActivity
Bundle extras = getIntent().getExtras();
String gname = extras.getString("name");
Profile profile = Profile.newInstance(gname);
In Kotlin, you can access an activity variable from a fragment like this
(activity as ActivityClassName).variableName
I don't have much experience in Java, but I believe this is that code translated into Java
((ActivityClassName) getActivity()).variableName

Receive data from class to fragment by Intent

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

calling tabactivity from intent

I have a activity and a fragment activity . I want to fetch email id stored in my activity to fragment activity . Can anyone of you tell me how to pass data from activity to fragments . I used bundle but it is not working
Use this code in your activity:
Bundle args = new Bundle();
Fragment frag=new Frag1();
args.putInt("key", value);
frag.setArguments(args);
And now in your fragment class, get the bundle as:
Bundle args = getArguments();
if(args.containsKey("key"))
{
args.getInt("key");
}

How to send data from one Fragment to another Fragment?

Hi I know there are answers of this question. I have tried all of them but it is not working in my app.
I am developing an app that has 3 Fragment activity. First fragment shows a website, second fragment has listview and third Fragment has another listview. Now I want to send URL from third fragment to first fragment when user clicks on listitem..This is what I have done.
I am sending string url from this Fragment to first fragment.
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position,
long id) {
FragmentC fragment = new FragmentC();
final Bundle bundle = new Bundle();
bundle.putString("position", "http://www.facebook.com"); fragment.setArguments(bundle);}
});
This is first fragment where I need the url and Want to show in the webview.
String url="http://www.hotelsearcher.net/";
Bundle args = getArguments();
if (args != null){
url = args.getString("position");
}
WebView webView= (WebView) V.findViewById(R.id.webView1);
WebSettings webViewSettings = webView.getSettings();
webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webViewSettings.setJavaScriptEnabled(true);
webViewSettings.setPluginState(PluginState.ON);
webView.loadUrl(url);
When I click on list item I don't see anything . It does not redirect me to the first fragment.Please help me..
Use Bundle to send String:
//Put the value
YourNewFragment ldf = new YourNewFragment ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);
//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();
In onCreateView of the new Fragment:
//Retrieve the value
String value = getArguments().getString("YourKey");
1.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.
2.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.
You have to attach your bundle to your fragment.
fragment.setArguments(bundle);
and after that change or replace the new fragment.
You have to be sure that the String is in the new Fragment. Debugging!!
You can send data by two ways
First when you want to start that fragment while sending data
SecondFragment ldf = new SecondFragment ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);
//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();
Second, when you want to send data without open your fragment
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.add(R.id.fragContainer1, new ModelListFragment(), FRAG_MODEL_LIST);
ft.add(R.id.fragContainer2, new TrimListFragment(), FRAG_TRIM_LIST);
ft.commit();
Fragment fragment = mFragmentManager.findFragmentByTag(MainActivity.FRAG_MODEL_LIST);
Log.d("MY", "found fragment: " + (fragment != null));

How to use setArguments() and getArguments() methods in Fragments?

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

Categories

Resources