Pass data from an Activity to a fragment [duplicate] - java

This question already has answers here:
Send data from activity to fragment in Android
(22 answers)
Closed 1 year ago.
I am a little bit lost in this, so I already passed data from my LoginActivity to my DashboardActivity. And it works now (thank god). But now, I would love to pass that data to a fragment.
I have this on my DashboardActivity:
Intent get = getIntent();
String userId = get.getStringExtra(LoginActivity.EXTRA_ID);
Bundle bundle = new Bundle();
bundle.putString("userId", userId);
Fragment fragment = new Fragment();
fragment.setArguments(bundle);
I have this on my Fragment:
Bundle bundle = getArguments();
String userId = bundle.getString("userId");
int uid = Integer.parseInt(userId);
Is it like this?

Getting data in Fragment and Activity are not done in the same way.
To send extra to a fragment, You can do it this way.
In your Activity Class
Bundle bundle = new Bundle();
bundle.putString("userId", "value you want to send");
FragmentClass frag = new FragmentClass();
frag.setArguments(bundle);
Then in Fragement onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("userId");
return inflater.inflate(R.layout.fragment, container, false);
}
The issue with your code is you're getting the argument with a wrong id.
Right way
String userId = getArguments().getString("userId");

From activity to fragment you should use bundle as below
Bundle bundle = new Bundle();
bundle.putString(LoginActivity.EXTRA_ID, "Extra value");
Fragment fragment = new Fragment();
fragment.setArguments(bundle);
Then in your Fragment, get the data for example in onCreate() method
Bundle bundle = this.getArguments();
if (bundle != null) {
String extraId = bundle.getString(key, defaultValue);
}

Related

Pass data between fragments with Bundle

I read a lot of discussion about that, and someone suggests to use Bundle to pass data between two fragments in the same activity...I tried some come, but it didn't worked.
I have 2 fragments in my GroupDetailActivity. The paymentFragment, which download data from a database and show them in a listView, and the fragment FragmentReport, which displays a report of the payments.
So, after the paymentFragment get the data, I need to pass some of them to the second fragment. That's my code:
PaymentFragment:
final Bundle bundle = new Bundle();
final FragmentReport fragment = new FragmentReport();
// This is inside the onCreateView, where I get the the data from the db and show them in a listview
bundle.putInt("num_of_pay", cont);
Log.v("cont", String.valueOf(cont)); // it display the correct number of person
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, fragment);
Then, in my FragmentReport, inside the OnCreateView:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.report_fragment,container,false);
numberOfPaymentTV = rootView.findViewById(R.id.n_payment_tv);
Bundle args = this.getArguments();
if (args != null){
numberOfPaymentTV.setText(args.getInt("num_of_pay"));
Log.v("totalPayment", String.valueOf(args.getInt("num_of_pay"))); // I don't get any log, maybe this fragment doesn't receive the data
}
return rootView;
}
}
I don't get any error, but the textView doesn't show the "cont" value.
Maybe I could use sharedPreferences? Is it possibile achieve that with Bundle?
You can get args in onCreate() function.
private Bundle bundle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
((TextView) view.findViewById(R.id.textView))
.setText(String.valueOf(bundle.getInt("KEY")));
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.bundle = getArguments();
}
You should use the String.valueOf(int) when setting an int as text in a TextView:
numberOfPaymentTV.setText(String.valueOf(getArguments().getInt("num_of_pay"))

how to pass a value using intents and bundle

I am trying to pass a value from my Activity to my Fragment but the Bundle is always null.
Activity
CallLogsFragment callLogfrag = new CallLogsFragment();
Intent intent = new Intent(this, DeviceUsageActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key", callgroup);
callLogfrag.setArguments(bundle);
this.startActivity(intent);
Fragment which is meant to retrieve value from Activity
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt("key", 0);
}
View view = inflater.inflate(R.layout.fragment_call_logs, container, false);
load(view);
setupList(view);
return view;
}
try this one
// send value from activity to fragment
CallLogsFragment callLogfrag = new CallLogsFragment();
Bundle bundle = new Bundle();
bundle.putInt("key", "4");
callLogfrag.setArguments(bundle);
// call fragment from activity
getSupportFragmentManager().beginTransaction().replace(R.id.containar, callLogfrag).commit();
// get value in fragment
if (getArguments() != null) {
int status = getArguments().getInt("key");
If I am clear with your question!! You are trying to send data from one activity to the fragment in Another activity.
Then you need to first send data in Intent that starts second activity. Then get the data from intent and set your data to fragment as argument and add the fragment to the parent activity.
//here you go, from first activity
Intent intent = new Intent(this, DeviceUsageActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key", callgroup);
intent.putExtra("yourdata",bundle);
//start your activity - parent activity of your fragment
this.startActivity(intent);
//then get your data in DeviceUsageActivity in onCreate()
Bundle yourdata = null;
if(getIntent().getExtras() != null) {
yourdata = getIntent().getBundleExtra("yourdata");
}
//Then sent data to fragment
CallLogsFragment callLogfrag = new CallLogsFragment();
callLogfrag.setArguments(yourdata);
// add fragment to parent activity
getSupportFragmentManager().beginTransaction().replace(R.id.containar, callLogfrag).commit();
//rest you know - get bundle argument in fragmet
From Activity to store data
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("key","value");
startActivity(i);
To retrieve data back to fragment,use Context as getActivity if needed only in fragments
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//The key argument here must match that used in the other activity
}

Communication between one fragment to another [duplicate]

This question already has answers here:
How to pass data between fragments
(13 answers)
Closed 6 years ago.
I am new to fragments. I added two edit texts in first fragment and I want to send that edittext data to second fragment.
I am using a bundle, but its printing null in second fragment.
Can anyone tell me how to send data to other fragment?
First fragment
nextt.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View _view) {
int viewId = _view.getId();
FragmentTransaction ft;
switch (viewId) {
case R.id.Button1:
FragmentManager fm = getFragmentManager();
ft = fm.beginTransaction();
SecondFrag secondFrag = new SecondFrag();
Bundle bundle = new Bundle();
bundle.putInt("deviceInst",viewId);
secondFrag.setArguments(bundle);
ft.replace(R.id.total_frame_content, secondFrag);
ft.addToBackStack(null);
ft.commit();
break;
}
}
});
In second fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_new, container, false);
String value = getArguments().getString("deviceInst");
System.out.println("TTTT"+ value);
In your first fragment you pass an int as an argument.
bundle.putInt("deviceInst",viewId);
And then, in your second fragment you try to get that argument by using
getArguments().getString("deviceInst")
which will fail, so to get the argument you pass you need to use getArguments().getInt("deviceInst")
For encapsulating the needed data, a good tip is to have a static newInstance() method in your fragments that requires data.
Here's a post about it.
https://plus.google.com/+AndroidDevelopers/posts/bCD7Zvd945d
You need to change like
int value = getArguments().getInt("deviceInst");
instead of
String value = getArguments().getString("deviceInst");
You will need to make the following changes in your code.
bundle.putString("deviceInst",editText.getText().toString());
Then in your second fragment you can get that argument by using
getArguments().getString("deviceInst")
Here editText is the instance of the edit text in the first fragment.
As you have passed int in the bundle, you need to use getInt() in your receiver fragment.
For example:
SecondFrag secondFrag = new SecondFrag();
Bundle bundle = new Bundle();
bundle.putInt("deviceInst",viewId);
secondFrag.setArguments(bundle);
getFragmentManager().beginTransaction().add(R.id.total_frame_content, secondFrag).commit();
In receiver fragment
String value = getArguments().getInt("deviceInst");

Passing data through bundle

I want to send data which i do this way :
public static final String Itemmm = "tryIT";
String item3 = (String)arrayAdapter.getItem(position).toString();
ClassicsA class = new Classics();
Bundle bundle2 = new Bundle();
bundle2.putString(ClassicsB.Itemmm, item3);
class.setArguments(bundle2);
And to receive data I do this:
Bundle bundle2 = this.getArguments();
if(bundle2!=null){
String i = bundle2.getString(ClassicsB.Itemmm, "");
testButton.setText(i);
}
However the data is never being sent, when I check the value of testButton it's empty. Can you see what i am doing wrong? When I add item3 between the brackets it just takes the item3 as a string.
BTW this is communication between 2 fragments.
To Send the data, use the following lines of code:
Bundle bundle = new Bundle();
bundle.putString("KEY", "VALUE");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
And in order to recieve a data use this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("KEY");
return inflater.inflate(R.layout.fragment, container, false);
}
Hope this helps.

Bundle getInt only return default value

I have a problem that is this code only return default value is -1. I tried to debug, it has value so i don't know why it alway return -1.
private static final String KEY_CATEGORY_ID = "category";
Bundle bundle = getArguments();
mCategoryId = bundle.getInt(KEY_CATEGORY_ID, -1);
This is my debug value:
bundle Bundle (id=830037735464)
Bundle[{category=2}]
In your activity setArguments in this way
mFragment = new MyFragment();
Bundle extras = this.getIntent().getExtras();
extras.putInt("category", 10);
mFragment.setArguments(extras);
mFragmentTransaction = getSupportFragmentManager().beginTransaction();
mFragmentTransaction.add(R.id.profile_fragment, mFragment);
mFragmentTransaction.commit();
In fragment get it in this way
Bundle bundle = getArguments();
catgory = bundle.getInt("category");

Categories