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.
Related
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);
}
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"))
I want to pass image uri from my array images[] at 0 position to other fragment.
This is my fragment from which i want to pass in onclick method at postion==0.
public class OrganicAcidFragment extends Fragment {
String[] product_name={"Formic Acid","Acetic Acid","Propionic Acid",};
String[] product_cn={"CH2O2","CH3COOH","C3H602"};
int[] images={R.drawable.formicacid,R.drawable.aceticacidjpg,R.drawable.propionicacid};
ListView list;
String quantity;
String price;
FragmentManager fm;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.i_fragment_organic_acid, container, false);
fm=getFragmentManager();
MyAdapter adapter=new MyAdapter(getActivity(),product_name,images,product_cn,quantity,price);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position==0){
PurchaseFragment ldf = new PurchaseFragment ();
Bundle args = new Bundle();
args.putString("product_name", product_name[0]);
args.putString("product_cn", product_cn[0]);
ldf.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.content_frame, ldf).commit();
}
if(position==1){
fm.beginTransaction().replace(R.id.content_frame,new OrganicBaseFragment()).addToBackStack("chemicalorganicfragment").commit();
}
if(position==2){
fm.beginTransaction().replace(R.id.content_frame,new OrganicBaseFragment()).addToBackStack("chemicalorganicfragment").commit();
}
}
});
return rootview;
}
}
In this fragment i want to get that data:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.i_fragment_purchase, container, false);
String product_names = getArguments().getString("product_name");
String product_cns = getArguments().getString("product_cn");
imagee=(ImageView)rootview.findViewById(R.id.productimage);
cancel= (Button) rootview.findViewById(R.id.cancel);
address= (EditText) rootview.findViewById(R.id.address);
name.setText(product_names);
cn.setText("("+product_cns+")");
return rootview;
}
Both fragments are in same activity.
How can i do it?
I think best and easiest way to send data between running activities and fragments is LocalBroadcast.
Intent intent = new Intent("some_name");
intent.putExtra("some_data_key", "some_data_value");
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
This is how to send local broadcast.
For listen local broadcast you must register that broadcast in onCreate() (If listener is Activity) or onCreateView() (If listener is fragment) or whenever you want to receive that broadcast:
LocalBroadcastManager.getInstance(this/*here is context*/).registerReceiver(someReceiver,
new IntentFilter("some_name"));
This is broadcast receiver to receive data:
BroadcastReceiver someReceiver= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String data= intent.getStringExtra("some_data_key");
//Here do whatever you want with data
//It isn't must be a string. If you want to send a object you must make object class implement Parcelable properly.
}
};
In the end, don't forget to unregister this broadcast receiver. Do it in onDestroy() or whereever you want.
LocalBroadcastManager.getInstance(this).unregisterReceiver(someReceiver);
You can use bundle to send data from one fragment to another.
//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 another fragment:
//Retrieve the value
String value = getArguments().getString("YourKey");
I have a fragment which shows a list of buttons, each have their own id. When the user clicks the button, I am trying to replace the current fragment with another. Right after I replace the fragment, I a am adding arguments to the bundle. From what I can tell from debug mode, that part is working 100%. However, when we get to the new fragment, the "savedInstanceState" state will always be null.
I have read several posts on this however, I am confused because I am attempting to set the bundle and replace the fragment the same way I did when going from the activity to the first fragment and it is still not working.
MyActivity.java (this is working and all values are being set):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyFirstFragment fragment = new MyFirstFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
Intent i = getIntent();
value = i.getExtras().getString("key");
Bundle bundle = new Bundle();
bundle.putString("key",value);
fragment.setArguments(bundle);
}
MyFirstFragment.java (also working):
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
final String value = getArguments().getString("key");
myButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String gid = Integer.toString(v.getId());
MySecondFragment secondfragment = new MySecondFragment();
Bundle secondFragmentBundle = new Bundle();
secondFragmentBundle.putString("key",value);
secondFragmentBundle.putString("id",id);
secondfragment.setArguments(secondFragmentBundle);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,secondfragment);
fragmentTransaction.commit();
}
});
MySecondFragment (getting null for savedInstanceState and all bundle agruments!):
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_second, container, false);
value = getArguments().getString("key");
id = getArguments().getString("id");
}
You cannot set arguments on a Fragment after it is attached to an Activity.
Your issue is caused by confusion about Fragment creation. What you provided in your question is not the correct way to send arguments to another Fragment type.
The de-facto standard way of passing arguments to a Fragment when it is created it to use a static factory method, generally called newInstance(). You should set the arguments this way, and should do so before committing the FragmentTransaction - however, you technically could do it right after committing the transaction with no ill effects. This is because when a Fragment is committed, it isn't immediately attached/created, rather, it is queued on the main thread.
Here is how you would do it:
Write a method in your Fragment class called new instance. Be sure to leave a public default (no arguments) constructor for the system to handle things in the background.
public MyFirstFragment extends Fragment {
public MyFirstFragment(){
//constructor - don't use this to create a new fragment directly
}
public static MyFirstFragment newInstance(String argument1, String argument2) {
// This is where you set the Fragment arguments:
MyFirstFragment instance = new MyFirstFragment();
Bundle arguments = new Bundle();
// add whatever arguments you need to the bundle
arguments.putString("ARGUMENT_1_KEY", argument1);
arguments.putString("ARGUMENT_2_KEY", argument2);
//Set the arguments on the new fragment instance
instance.setArguments(arguments);
return instance;
}
// recover the values in onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
// an easy way to check if this is a new instance is to null-check the saved state Bundle
if (savedInstanceState == null) {
String argument1 = getArguments().getString("ARGUMENT_1_KEY");
String argument2 = getArguments().getString("ARGUMENT_2_KEY");
} else {
// restore whatever you need from savedInstanceState bundle
}
}
Key point - the arguments are passed into the newInstance() method (these can be whatever you want, as long as the type is allowed). The newInstance() method enforces argument types and also prevents setting them after the fragment is already attached to an activity.
After this, in your Activity.onCreate() method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String argument1 = "some information";
String argument2 = "other information";
MyFirstFragment fragment = MyFirstFragment.newInstance(argument1, argument2);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
}
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");