Bundle getInt only return default value - java

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

Related

Pass data from an Activity to a fragment [duplicate]

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

SavedInstanceStateNull between Fragments is null

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();
}

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
}

pass bundle from recycleview adapter to activity

I want to pass a bundle on click of button to new activity.
This is the code for bundle in the class adapter which extends recycleview adapter
private void passBundle (Vendor mItemSelected){
mBundle = new Bundle();
mBundle.putString("VENDOR_ID", mItemSelected.getVENDORID());
mBundle.putString("CAT_ID", "" + mItemSelected.getVEN_TYPE());
mBundle.putString("VENDOR_NAME", "" + mItemSelected.getVENDORNAME());
mBundle.putString("CAT_ID", "" + mItemSelected.getVEN_TYPE());
mBundle.putString("CAT_ID", "" + mItemSelected.getVEN_TYPE());
mBundle.putString("VENDOR_AREA", "" + mItemSelected.getVENDORADDRESS());
Intent in = new Intent(context,Chat_Activity.class);
in.putExtra("Bundle", mBundle);
Context.startActivity(in);
}
and this is the code where i retrieve the bundle data in another activity.
Bundle bundle = new Bundle();
chatVenID = bundle.getString("VENDOR_ID", "");
catID = bundle.getString("CAT_ID", "");
vendorName = bundle.getString("VENDOR_NAME", "");
vendorArea = bundle.getString("VENDOR_AREA","");
Bundle bundle = new Bundle();
In this code, you are creating a new object of Bundle, so you wont' get any values. Change it to
getIntent().getBundleExtra("Bundle")
You can invoke
Bundle bundle = getIntent().getBundleExtra("Bundle");
chatVenID = bundle.getString("VENDOR_ID", "");
in onCreate(Bundle savedInstanceState) method;
new Bunlde() will create a new bundle object, can't get pass value from prev activity.

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.

Categories