How to transfer from one fragment to another in Android - android

I want to transfer some data like "editText1Double" and "sum" to another fragment (SecondFragment) that will use those data. How would I do that?
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_fragment, container, false);
editText1 = (EditText) v.findViewById(R.id.editText1);
editText2 = (EditText) v.findViewById(R.id.editText2);
editText3 = (EditText) v.findViewById(R.id.editText3);
textView = (TextView) v.findViewById(R.id.textView);
calculateButton = (Button) v.findViewById(R.id.calculateButton);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText1Double = Double.parseDouble(editText1.getText().toString());
editText2Double = Double.parseDouble(editText2.getText().toString());
editText3Double = Double.parseDouble(editText3.getText().toString());
sum = editText1Double + editText2Double + editText3Double;
}
});

1) Using Bundle :
FragmentManager fM = getActivity().getSupportFragmentManager();
FragmentTransaction fT = fM.beginTransaction();
Fragment_B fragment = new Fragment_B();//receiving fragment
Bundle bundle = new Bundle();
bundle.putDouble("key", sum);
fragment.setArguments(bundle);
fT.add(R.id.container, fragment);
fT.addToBackStack(null);
fT.commit();
and Receive as
Bundle bundle = getArguments();
Double sum = bundle.getDouble("key");
2)Using Construcor:
FragmentManager fM = getActivity().getSupportFragmentManager();
FragmentTransaction fT = fM.beginTransaction();
Fragment_B fragment = new Fragment_B(sum);//receiving fragment
fT.add(R.id.container, fragment);
fT.addToBackStack(null);
fT.commit();
and Receive as
public class Fragment_B extends Fragment{
private double sum;
public Fragment_B (double sum) {
this.sum= sum;
}
public Fragment_B () {
}}

Pass data by using
fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putDouble("double", 1.1);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, "HomeFragment").addToBackStack(null).commit();
And get data in another Fragment using
Bundle bundle = getArguments();
double d = bundle.getDouble("double")
Hope it works fine for you.

Sending data from fragment_A
FragmentManager fM = getActivity().getSupportFragmentManager();
FragmentTransaction fT = fM.beginTransaction();
Fragment_B fragment = new Fragment_B();//receiving fragment
Bundle bundle = new Bundle();
bundle.putDouble("sum_key", sum);
fragment.setArguments(bundle);
fT.add(R.id.container, fragment);
fT.addToBackStack(null);
fT.commit();
Receiving data at fragment_B
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle bundle = getArguments();
Double sum = bundle.getDouble("sum_key");
}

Related

Share information between fragments

I need to share information between fragments. I know that I can use sharedpreferences but I think that is not optimized.
This is the parent fragment code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_blank, container, false);
....
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.eventos_pager, new BlankFragment2());
ft.commit();
....
return view;
}
This fragment call BlankFragment2 and BlankFragment1 need to sends information to BlankFragment2
I can share information to BlankFragment2 by the BlankFragment2's constructor. It is not allowed.
In Android you pass values to Fragments via bundles.
Using AndroidStudio File > New > Fragment > Fragment (Blank) will generate something like this.
public class MTFragment extends Fragment {
private String mParam1;
public static MTFragment newInstance(String param1) {
MTFragment fragment = new MTFragment();
Bundle args = new Bundle();
args.putString("value", param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString("value");
}
}
}
From your code:
MTFragment mFragment = MTFragment.newInstance("Hello");
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.eventos_pager, mFragment);
ft.commit();

Passing data by using bundle between tablayout

I am using Bundle to passing data from my First TabFragment but it prompts out with the NullPointerException. Error is occur when getArguments() in list_fragments2 in second tab
MainActivity Fragment
list_fragment2 fragment = new list_fragment2();
Bundle b = new Bundle();
b.putString("test","text");
fragment.setArguments(b);
Toast.makeText(this, "" + b, Toast.LENGTH_SHORT).show();
SecondActivity Fragment
public class list_fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View h = inflater.inflate(R.layout.tab2, container, false);
TextView textView = (TextView) h.findViewById(R.id.textView);
Bundle bundle=getArguments();
//your string
if(bundle != null) {
String test = bundle.getString("test");
textView.setText(test);
}
return h;
}
}
Do you actually load your second fragment?
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
list_fragment2 fragment = new list_fragment2();
Bundle b = new Bundle();
b.putString("test","text");
fragment.setArguments(b);
fragmentTransaction.replace(placeholder, fragment);
fragmentTransaction.commit();
I think you can create your instance of list_fragment2 code within list_fragment2. Maybe your codes recreated list_fragment2 many times.
public static list_fragment2 createInstance() {
list_fragment2 fragment = new list_fragment2();
Bundle bundle = new Bundle();
bundle .putString("test","text");
fragment.setArguments(bundle);
return fragment;
}

sending data from activity to fragment

I have a side menu, when the side menu is pressed. It should take the SharedPreferences String and send it to the Fragment. And the Fragment should set the TextView and it will be displayed on the MainActivity.
The sent data to fragment is not showing up in the MainActivity,I am getting the error. Any solutions?
Main Activity code (when option pressed):-
if(num == 0)
{
SharedPreferences sp = getSharedPreferences("Login", Context.MODE_PRIVATE);
username = sp.getString("username", "DEFAULT");
FragmentOne F1 = new FragmentOne();
FragmentManager FM = getFragmentManager();
FragmentTransaction FT = FM.beginTransaction();
FT.add(R.id.relative_main, F1);
F1.setTextV(username);
FT.commit();
}
Fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
textV = (TextView) getActivity().findViewById(R.id.frag_one_textview);
View v = inflater.inflate(R.layout.fragment_one, container, false);
return v;
}
public void setTextV(String username)
{
textV.setText(username);
}
Following issue is in current implementation :
1. If fragment_one is in layout which return in from onCreateView then use v to call findViewById :
View v = inflater.inflate(R.layout.fragment_one, container, false);
textV = (TextView) getActivity().findViewById(R.id.frag_one_textview);
return v;
2. Call setTextV after FT.commit(); :
FragmentTransaction FT = FM.beginTransaction();
FT.add(R.id.relative_main, F1);
FT.commit();
F1.setTextV(username);
Because you are getting value from SharedPreferences to show in TextView so get value from Preferences in onCreateView and show in TextView.
In this particular case, you don't need to send data to the fragment because in a fragment you can access to SharedPreferences.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
textV = (TextView) getActivity().findViewById(R.id.frag_one_textview);
View v = inflater.inflate(R.layout.fragment_one, container, false);
SharedPreferences sp = getActivity().getSharedPreferences("Login", Context.MODE_PRIVATE);
username = sp.getString("username", "DEFAULT");
textV.setText(username);
return v;
}
For other cases, the best way to send information from the Activity to the Fragment is using a Bundle.
if(num == 0)
{
SharedPreferences sp = getSharedPreferences("Login", Context.MODE_PRIVATE);
username = sp.getString("username", "DEFAULT");
FragmentOne F1 = new FragmentOne();
Bundle bundle = new Bundle();
bundle.putString("username", username);
// You can add all the information that you need in the same bundle
F1.setArguments(bundle);
FragmentManager FM = getFragmentManager();
FragmentTransaction FT = FM.beginTransaction();
FT.add(R.id.relative_main, F1);
FT.commit();
}
Fragment:-
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
textV = (TextView) getActivity().findViewById(R.id.frag_one_textview);
View v = inflater.inflate(R.layout.fragment_one, container, false);
textV.setText(getArguments().getString("username", ""));
return v;
}

Crashes fragement when passing arguments to previous fragment

I have three fragments FragA, FragB, FragC. Am passing an argument through bundle "discount" from FragA to FragB. Then from FragB am sending two arguments "discount" and "address" to FragC. Till here all are working properly.
Then i have to go back to FragB from FragC. I used a button 'backButton' for this purpose. But when the button clicks, my app crashes due to NPE. I have send argument to FragB from FragC, but no arguments will get in FragB.
Am attaching the code i have used below..
Fragement A
class FragA extends Fragment
{
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
{
context = getActivity();
View v = inflater.inflate(R.layout.layout_fragfirst, container, false);
nextButton = (Button) v.findViewById(R.id.buttonnext);
nextButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
fr = new FragB();
Bundle bundle=new Bundle();
bundle.putString("discount", discount);
fr.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
}
Fragement B
class FragB extends Fragment
{
Context context;
String discount = "";
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
{
context = getActivity();
View v = inflater.inflate(R.layout.layout_fragsec, container, false);
String addressid = "something";
nextButton = (Button) v.findViewById(R.id.buttonnext);
Bundle b = getArguments();
discount = b.getString("discount");
nextButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
fr = new FragC();
Bundle bundle=new Bundle();
bundle.putString("discount", discount);
bundle.putString("address", addressid);
fr.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
}
Fragement C
class FragC extends Fragment
{
Context context;
String discount = "",addressid="";
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
{
context = getActivity();
View v = inflater.inflate(R.layout.layout_fragthird, container, false);
backButton = (Button) v.findViewById(R.id.buttonnext);
Bundle b = getArguments();
discount = b.getString("discount");
//backButton to go to Fragment B(FragB)
backButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
fr = new FragB();
Bundle bundle=new Bundle();
bundle.putString("discount", discount);
fr.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
}
LogCat
java.lang.NullPointerException
at com.abc.fragments.FragA.onCreateView(FragA.java:114)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:829)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
at android.app.BackStackRecord.run(BackStackRecord.java:635)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Please Suggest me a solution...
the problem might be NullPointerException....
as you are extracting arguments in onCreateView but when you are going back getArguments must be giving you null a there is no argument passed from FragC to FragB... it better you put null check around bundle
Bundle b = getArguments();
if( b != null )
discount = b.getString("discount");
when you press back button you are restoring your pervious fragment... but in you code you are going Frag A >Frag B >Frag C >Frag B ....you are implementing it wrong way... just dont add Frag B to stack of fragment

Use single Fragment for multiple UI tasks?

I am using the Fragment master detail architecture
All Fragment Classes have the same logic
Is it possible to "detach" the Fragment from the layout and use just one Fragment class
So this code:
FragmentTransaction fragManager = getSupportFragmentManager().beginTransaction();
if("001".equalsIgnoreCase(id)){
arguments.putString(Fragment001.ARG_ITEM_ID, id);
Fragment001 fragment = new Fragment001();
fragment.setArguments(arguments); fragManager.replace(R.id.item_detail_container, fragment);
}
else if("002".equalsIgnoreCase(id)){
arguments.putString(Fragment002.ARG_ITEM_ID, id);
Fragment002 fragment = new Fragment002();
fragment.setArguments(arguments);
fragManager.replace(R.id.item_detail_container, fragment);
}
fragManager.commit();
Will turn into Something like:
FragmentTransaction fragManager = getSupportFragmentManager().beginTransaction();
GenericFragment fragment = new GenericFragment();
fragment.setUiId(id)
fragManager.replace(R.id.item_detail_container, fragment);
fragManager.commit();
List item
yes its possible, you can check and select which layout to use in onCreateView...
public static final String ARG_ITEM_ID1 = "fragment001";
public static final String ARG_ITEM_ID2 = "fragment002";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
String id = "fragment001";
if(ARG_ITEM_ID1.equalsIgnoreCase(id)){
rootView = inflater.inflate(R.layout.fragment_1_layout, container, false);
}
else {
rootView = inflater.inflate(R.layout.fragment_2_layout, container, false);
}
return rootView;
}

Categories

Resources