I am trying to send data from Fragment A to Fragment B of NAVIGATION Drawer on Button click.I tried with bundle and intent but both of them are not working.
In Fragment A I have editText and button when I click the data is passed to another fragment.
In Fragment B there is textView where editText data is going to show but I am not getting a way to communicate between fragment in Navigation Drawer
When lauching Fragment from first fragment
Bundle bundle = new Bundle();
bundle.putString("key", YOUR_EDITVIEW_TEXT);
Fragment fragment = new SECONDFragment();
if (arguments != null) {
fragment.setArguments(arguments);
}
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.container, fragment);
ft.addToBackStack("");
ft.commit();
And in SecondFragment
private String mData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mData = getArguments().getString("key");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.YourLayout, container, false);
TextView text = (TextView) rootView.findViewById(R.id.yourTextView);
text.setText(mData);
return rootView;
}
Let your Activity to do the communication.
Take a public static variable in your MainActivity from where you're controlling the Fragment replaces of the navigation drawer. When you click the button in FragmentA store the value in the EditText to the public static variable of your MainActivity. Then when FragmentB is loaded check if the public static value is null or not. If not null place the value of that variable to your desired position.
This is not an elegant way for passing values between fragments, but in your case it'll work just fine.
If you're looking for how to pass values from one fragment to another, try something like this.
// To pass some value from FragmentA
FragmentB mFragmentB = new FragmentB();
Bundle args = new Bundle();
args.putString("VALUE", value);
mFragmentB.setArguments(args);
And from your FragmentB use the code to get the values passed.
Bundle args = getArguments();
int value = args.getString("VALUE");
1- create Application Class
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
private static MyApplication mInstance;
public static synchronized MyApplication getInstance() {
return mInstance;
}
String mytext;
public String getMytext() {
return mytext;
}
public void setMytext(String mytext) {
this.mytext = mytext;
}
}
2- app name tag in manifast
<application
android:name=".MyApplication"
.......
3- from first Fragment
MyApplication.getInstance().setMytext("your text here");
4- from other Fragment
String text=MyApplication.getInstance().getMytext();
//Put the value
YourNewFragment ldf = new YourNewFragment ();
Bundle args = new Bundle();
args.putString("KEY", "VALUE");
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("KEY");
Related
i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea? my case is diffrent because i wanna do it in fragment
myActivity :
if(email.matches(users.user1)&&password.matches(users.pass1)){
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
Intent i = new Intent(LoginActivity.this,ProfileFragment.class);
i.putExtra("pn", users.pn1);
i.putExtra("name", users.name1);
i.putExtra("family", users.family1);
i.putExtra("rank", users.rank1);
startActivity(intent);
finish();
}
myfragment
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile2, container, false);
final TextView pn =getActivity().findViewById(R.id.pn);
final TextView name =getActivity().findViewById(R.id.name);
final TextView family =getActivity().findViewById(R.id.family);
final TextView user =getActivity().findViewById(R.id.user);
final TextView rank =getActivity().findViewById(R.id.rank);
String pnget = getActivity().getIntent().getStringExtra("pn");
String nameget = getActivity().getIntent().getStringExtra("name");
String familyget = getActivity().getIntent().getStringExtra("family");
String userget = getActivity().getIntent().getStringExtra("user");
String rankget = getActivity().getIntent().getStringExtra("rank");
pn.setText(pnget);
name.setText(nameget);
family.setText(familyget);
user.setText(userget);
rank.setText(rankget);
}
Hi . i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea?
You start an intent call intent. But the intent have data is i, and it have't started yet.
You can use setArgument and getArgument to send and receive data from activity to fragment or from fragment to fragment:
In YourReceiveFragment:
public static Fragment newInstance(String data1, String data2, ...) {
Fragment f = new YourReceiveFragment();
Bundle bundle = new Bundle();
bundle.putString(DATA_RECEIVE1, data1);
bundle.putString(DATA_RECEIVE2, data2);
f.setArguments(bundle);
return f;
}
In your activity: Just call it:
Fragment f = YourReceiveFragment.newInstance(yourString1, yourString2);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.main_container, f).commit();
Then in YourReceiveFragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null){
String dataReceive1 = getArguments().getString(DATA_RECEIVE1);
String dataReceive2 = getArguments().getString(DATA_RECEIVE2);
}
}
In case you want to send data from an activity to a fragment in another activity, use interface or an easier way is just pass the data to the activity which contains fragment and from that, send data to fragment.
You can't create a Fragment with startActivity. You need to create the fragment with bundle like this:
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString("name", users.name1);
args.putString("family", users.family1);
fragment.setArguments(args);
// then tell the FragmentManager to attach the fragment
// to the activity
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.your_placeholder, fragment);
ft.commit();
Then in your onCreateView get them with:
String name = getArguments().getString("name", "");
String family = getArguments().getString("family", "");
Please remember that you need to move the return code to the last of onCreateView method and change your code to something like this:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile2, container, false);
TextView pn =view.findViewById(R.id.pn);
...
return view;
}
You can send data with the bundle, that is recommended
To Pass Data from Activity
fragment = new YourFragment();
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
Bundle bundle = new Bundle();
bundle.putString("key", "value");
fragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
}
To receive data from Fragment
String var = getArguments().getString("value");
I want to pass data from my Activity to a Fragment. I have no idea how to do it. I've seen many solutions but no one of them did really work.
I just want to pass a simple String to the Fragment.
I have tried it this way:
public class PhotoActivty extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
if (null == savedInstanceState) {
Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
BasicFragment fragInfo = new BasicFragment();
fragInfo.setArguments(bundle);
android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.photo_frame, fragInfo);
transaction.commit();
}
}
}
What is the error there? I call it this way:
String myValue = this.getArguments().getString("message");
In the onCreateView in the Fragment
I usually use a static factory pattern:
public class MyFragment extends Fragment {
public static MyFragment newInstance(int index) {
MyFragment f = new MyFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
}
When you create the fragment in your Activity:
Fragment MyFragment = MyFragment.newInstance(5);
Alex Lockwood has a good rundown on why this is a preferred design pattern:
http://www.androiddesignpatterns.com/2012/05/using-newinstance-to-instantiate.html
Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
Fragment fragInfo = new BasicFragment();
fragInfo.setArguments(bundle);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.photo_frame, fragInfo);
transaction.commit();
try this inside your if
from activity:
Bundle bundleObject = new Bundle();
bundleObject.putString("data", " Send From Activity");
/*set Fragmentclass Arguments*/
Fragment fragmentobject = new Fragment();
fragmentobject .setArguments(bundleObject );
From Fragment You receive this way:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String stringText = getArguments().getString("data");
return inflater.inflate(R.layout.fragment, container, false);
Not sure if this is the real cause of the problem, but you have to use getSupportFragmentManager() instead of getFragmentManager() inside AppCompatActivity. Also, classes such as Fragment and FragmentTransaction should come from support.v4 package.
Remove if (null == savedInstanceState) in your activity. If savedInstanceStatenull == null then BasicFragment will not replace your FrameLayout for R.id.photo_frame.
This question already has answers here:
How to pass values between Fragments
(18 answers)
Closed 6 years ago.
I have Two Dynamic Fragments associated with one activity, I am trying to pass one Text from First Fragment to Second Fragment using Bundle, but I am getting Null Pointer Exception. Is it the right way to pass String between two fragments? Below is my code :
First Fragment
public class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_main, container, false);
String text = "GetThisStringInSecondFragment";
TextView txtView = null;
txtView = (TextView) view.findViewById(R.id.firstfragmenttext);
txtView.setText(text);
Bundle bundle = new Bundle();
bundle.putString("HI", text);
return view;
}
}
Second Fragment
public class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_secondmain,
container, false);
TextView txtView = null;
txtView = (TextView) view.findViewById(R.id.secondfragmenttext);
Bundle bundle = this.getArguments();
String myInt = bundle.getString("HI");
txtView.setText(myInt);
return view;
}
}
Activity
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnLoad = (Button) findViewById(R.id.btn_load);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FirstFragment hello = new FirstFragment();
fragmentTransaction.add(R.id.fragment_container, hello, "HELLO");
fragmentTransaction.commit();
FragmentManager fragmentManager2 = getFragmentManager();
FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction();
SecondFragment hello2 = new SecondFragment();
fragmentTransaction2.add(R.id.fragment_container, hello2, "HELLO");
fragmentTransaction2.commit();
}
};
btnLoad.setOnClickListener(listener);
}
}
You are doing getArguments in second fragment but where are you sending those arguments from first fragment. You can use Interface here and define it in activity. From activity, you can use setArgument() method for second fragment.
check the following link for more detailed information and steps to do that.
https://developer.android.com/training/basics/fragments/communicating.html
I am Using one String [] to display in ListView of fragmentone and pass String[] to fragmentTwo which has listView. my tried Codes below,
MainActivity:
public class MainActivity extends FragmentActivity implements ListInterface {
private FragmentOne fragmentOne;
private FragmentTwo fragmentTwo;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
fragmentOne = new FragmentOne ();
fragmentTwo = new FragmentTwo ();
FragmentManager fragmentManager = getSupportFragmentManager ();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();
fragmentTransaction.add (R.id.frame_one,fragmentOne);
fragmentTransaction.add (R.id.frame_two , fragmentTwo);
fragmentTransaction.commit ();
}
#Override
public void getValue (String[] s) {
fragmentTwo.setValue (s);
}}
FragmentOne:
public class FragmentOne extends Fragment {
private ListView listView;
private ListInterface listInterface;
String [] listData = {"Dhana","Rahul","Strobs","Uday","Selvi"};
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate (R.layout.fragment_one,container,false);
listView = (ListView)view.findViewById (R.id.lst_view);
ArrayAdapter adapter = new ArrayAdapter (getActivity (),R.layout.fragment_one,listData);
listView.setAdapter (adapter);
return view;
}
#Override
public void onAttach (Context context) {
super.onAttach (context);
if(context instanceof ListInterface){
listInterface =(ListInterface)context;
listInterface.getValue (listData);
}else{
throw new ClassCastException (context.toString ()+"mess ");
}
}}
FragmentTwo:
public class FragmentTwo extends Fragment {
private ListView listView;
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate (R.layout.fragment_two,container,false);
listView = (ListView)view.findViewById (R.id.lst_view_two);
return view;
}
public void setValue (String [] value){
ArrayAdapter adapter = new ArrayAdapter (getActivity (),R.layout.fragment_two,value);
listView.setAdapter (adapter);
}}
ListInterface:
public interface ListInterface {
public void getValue (String [] s);}
i tried my codes it show
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
FragmentTwo.setValue(FragmentTwo.java:27)
MainActivity.getValue(MainActivity.java:31)
FragmentOne.onAttach(FragmentOne.java:37)
You can set the data in this way.
public static BuyerToyFragment newInstance(String yourText) {
FragmentOne fragment = new FragmentOne ();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, yourText);
fragment.setArguments(args);
return fragment;
}
NOw in fragmentOne you need to get data like this.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
String myStringData = getArguments().getString(ARG_PARAM1);
}
}
and in your MainActivity you can set data like this.
// you can add string array as well. i dont remember the tag exactely. i its
//like putStingArray() but you need to check it yourself
fragmentOne = new FragmentOne ().newInstance("Your data goes here");
you need to do the same for fragment 2
I don't really understand the role of your list interface.
I don't really understand neither why you make your setValue and getValue call statically...
1/The easiest way is to store your list in your activity and then access it from the fragment, for exemple in onViewCreated.
Activity:
public String[] getMyList() {
return mMyList;
}
You will also need to do the setter to set the list from another fragment.
Access your list from the fragment:
String[] listFromActivity = ((MainActivity) getActivity()).getMyList();
2/A cleaner way could be to pass your list as an argument to your fragment.
In activity :
FragmentOne frO = new FragmentOne();
Bundle bundle = new Bundle();
bundle.putStringArray(mMyList, "my_list_key");
frO.setArguments(bundle);
In fragment :
String[] listFromActivity = getArguments().getStringArray("my_list_key");
The solution 1 is more easy if you want to update your list, if your list won't change the solution 2 is cleaner.
I have 2 Fragments.
When I click a button in Fragment 1 here what I do:
I set the variable String title = "Lady Gaga".
I will show the Fragment 2.
When the Fragment 2 is shown, I want to display the title text.
How to do it?
you can use bundles to pass data :
Bundle data = new Bundle();
data.putString("title", "my title");
Fragment fragment2 = new Fragment2();
fragment2.setArguments(data);
FragmentTransaction agm_ft = getSupportFragmentManager()
.beginTransaction();
agm_ft.replace(R.id.frag_containor, fragment2,
"agm_frag");
agm_ft.addToBackStack(null);
agm_ft.commit();
and get it back on next fragment:
Bundle getData = getArguments();
title = getData.getString("title");
1) Create a Interface
public interface TitleChangeListener {
public void onUpdateTitle(String title);
}
2) in Fragment 2
Create a public method
public void setTitle(String title){
//Do Somthing
}
3)Let Activity implement Interface TitleChangeListener and override onUpdateTitle
public void onUpdateTitle(String title){
fragment2.setTitle(title);
}
4) In Button onClickListner , 1st Fragment
TitleChangeListener listener=(TitleChangeListener)getActivity();
listener.onUpdateTitle("Lady Gaga");
For getting string from one fragment to another you have to use bundles and set them to as arguments like :
//on button click
String title = "Lady Gaga";
Fragment fr = new Final_Categories_Fragment();
Bundle b = new Bundle();
b.putString("title", title);
fragmentManager.beginTransaction()
.add(R.id.list_frame, fr, "last").commit();
fr.setArguments(b);
//Now on another fragment you have to get this argument
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sub_child_category_listview,
container, false);
...
String title = getArguments().getString("title");
...
return rootView;
}