I would like to pass an object from an activity to a fragment. I know how to pass the data but do not know which type of bundle i should use?
UPdate
In other words, I have an object of type mqttAndroidClient and that object i want to pass from my activity to a fragment through a bundle. Which bundle type I should use?
For relatively simple object data types, you shouldn't need a bundle at all. When you override onCreate() in the fragment that uses the argument, simply add a line of code that fetches the data from the intent.
For example, if you're passing an integer, the line would be:
intvar = (int)getActivity().getIntent().getInt(SOME_IDENTIFIER);
where SOME_IDENTIFIER is a constant that's common to both the activity and the fragment. (It would look something like "com.yourpackage.yourapp.some_identifier."
you should use something like this :
make your custom class that contains your desired data to be passed and extend from Serializable or Parcelable and put your object as extra to your Bundle object and set Bundle as an argument to your Fragment.
in your Activity
...
Fragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("data", "yourData");
fragment.setArguments(bundle);
...
in your Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String data = getArguments().getString("data");
...
}
Related
This question already has answers here:
Send data from activity to fragment in Android
(22 answers)
Closed 5 years ago.
I have passed some key and value data from one activity to another activity fragment so I have not get key and value to the last point in the fragment.
I have passing data using bundle.
In your activity create bundle to set to the fragment
Yourfragment fragment = new Yourfragment();
Bundle args = new Bundle();
args.putString(ARG_DATA, data);
fragment.setArguments(args);
Then load the fragment getSupportFragmentManager().beginTransaction().replace(R.id.your_container,fragment).commit();
Then in your fragment oncreate get the data like this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mData = getArguments().getString(ARG_DATA);
}
}
From activity to activity you can pass data by using Intent and when you get data in second activity in which you are creating fragments on creating fragment pass that data to fragment by making constructor in fragment or by using bundle. For further assistance and if you dont know how to do this do let me know.
Pass data from activity to activity:
Intent intent = new Intent(this, Second.class);
intent.putExtra("data", sessionId);
startActivity(intent);
get data in Second activity:
String s = getIntent().getStringExtra("data");
Pass data from activity to fragment:
Bundle bundle = new Bundle();
bundle.putString("data", "From Activity");
// set Fragmentclass Arguments
FragmentOne fragment = new FragmentOne ();
fragment.setArguments(bundle);
get data from activity to fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("data");
return inflater.inflate(R.layout.fragment, container, false);
}
Happy coding!!
You can pass data between Activity and Fragments and Fragment to fragment using below:
https://developer.android.com/training/basics/fragments/communicating.html
But to pass it between activity, you may use bundle data, (very few variables) or use Application Class to store it in memory, make sure you do not bloat up your memory.
New Android architecture components also do provide good options, it all depends upon your use:
https://developer.android.com/topic/libraries/architecture/index.html
I am trying to pass string from Adapter to fragment in Bundle bu ti'm getting null in my Fragment
Here is my code to add string to Bundle
Bundle bundle=new Bundle();
bundle.putString("id",expense_id);
AddExpenseFragment fragment=new AddExpenseFragment();
fragment.setArguments(bundle);
UiActivity.startAddExpense(context);
this is my code to retrieve to Bundle value in Fragment
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view=inflater.inflate(R.layout.activity_fragment_add_expense,container,false);
String id=this.getArguments().getString("id");
return view;
}
and i'm passing bundle value from My recyclerView Adapter class
The problem is simple here. You are creating a fragment and setting data to it which is fine,
AddExpenseFragment fragment=new AddExpenseFragment();
fragment.setArguments(bundle);
But the problem is in your
UiActivity.startAddExpense(context);
you must be replacing with a new instance of the AddExpenseFragment as you are no where passing the newly created fragment instance (with the arguments set to it) to the startAddExpense() method.
The solution is simple, just pass the newly created fragment object to the startAddExpense() like this,
UiActivity.startAddExpense(context, fragment);
and then inside the method replace or add this new fragment and do not instantiate any new fragment object.
Try this:
Bundle bundle = this.getArguments();
String id=bundle.getString("id");
From your code, it's hard to find problems.just give your some suggestions.
Firstly, check whether your variable expense_id is null or not.
Secondly, check whether the AddExpenseFragment you created and really showed are the same.
I have seen Bundles restored in several of the Android callback methods, but in many cases there is manual creation and setting of Bundles as on the developers website, in this case from an external message on Fragment creation:
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
In this other question, for example, bundle data is restored in the onCreateView() method.
public class Frag2 extends Fragment {
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle=getArguments();
//here is your list array
String[] myStrings=bundle.getStringArray("elist");
}
}
I am a bit confused about the Bundle data supplied with each callback method VS "other bundles":
Bundle bundle=getArguments();
and the correct way and place to retrieve these different types of bundled data.
Thanks in advance!
The two ways described above are exactly the correct way to
initialize a new instance of the Fragment and pass the initial parameters.
retrieve the initial parameters in the Fragment.
In other words, you're on the right track! It should work, and you should be pleased with yourself :)
EDIT:
The Bundle can be retrieved in either onCreateView() or
onCreate(). I'd prefer onCreate(), as it represents the creation
of the Fragment instance and is the right place for initialization.
There is always one and only one Bundle instance retrieved by the call to getArguments(), and this Bundle instance contains all of your ints, Strings, whatever.
I was just wondering how I could send parameters or arguments to a Fragment before it is created. Because I want to pass an array of strings to the fragment so that it could put all of them in the layout when it is created. For example I am making a Leaderboard fragment, and my activitiy would pass in all of the scores etc. that the fragment would use to display. I understand that I can use the Bundle and the .setArgs but will that work for my case?
Thank you
** EDIT **
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View singleplayerView = inflater.inflate(R.layout.singleplayer_tab, container, false);
String[] scores = (String[]) getArguments().get("scores");
TextView tview = (TextView) singleplayerView.findViewById(R.id.player_name0);
tview.setText(scores[0]);
setupRank(singleplayerView);
return singleplayerView;
}
public static SingleplayerTab newInstance(String[] scores) {
SingleplayerTab spt = new SingleplayerTab();
Bundle args = new Bundle();
args.putStringArray("scores", scores);
spt.setArguments(args);
return spt;
}
CODE THAT CALLS IT
String[] scores = {"hello"};
Fragment singlePlayerFragment = SingleplayerTab.newInstance(scores);
I understand that I can use the Bundle and the .setArgs but will that work for my case?
A Bundle can hold an String[] or an ArrayList<String>.
Moreover, this is the way you should do it, rather than a custom constructor. Android automatically recreates your fragments on a configuration change (e.g., screen rotation), and it will use your public zero-argument constructor for that. Hence, unless you use the arguments Bundle, or something else, you will lose your string array on a configuration change.
The recommended approach for this is to use a factory method, such as this one from an EditorFragment:
static EditorFragment newInstance(int position) {
EditorFragment frag=new EditorFragment();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
In this case, I want to pass int position into the fragment. I isolate packaging this into the Bundle into the factory method (newInstance()). When I need to create an instance of this fragment, I call EditorFragment.newInstance() instead of new EditorFragment, so I can supply the position. My fragment can get the position by reading the KEY_POSITION value out of the getArguments() Bundle. I use this approach in (among other places) this sample project, showing loading 10 of these editors into a ViewPager.
I currently have this Custom ArrayList:
ArrayList<PlaceDetails> place_list = new ArrayList<PlaceDetails>();
which will be populated during the onCreateView() portion.
I am unsure as of how do I pass this ArrayList in a bundle from this fragment class to another fragment class. Below is the snippet of my codes:
public void Map(View view){
if(hasConnection() == true){
Bundle b = new Bundle();
// how should I be passing the ArrayList in this bundle?
FragmentTransaction ft = getSherlockActivity().getSupportFragmentManager().beginTransaction();
TOnlineMapViewFragment mapfrag = TOnlineMapViewFragment.newInstance(b);
ft.replace(R.id.container, mapfrag).addToBackStack(null).commit();
}
}
So I've created the bundle and I wanted to pass it to the next fragment with the newInstance() method. How should I do this?
Consider implementing Parcelable interface in your classes. Then you would be able to store PlaceDetails in Bundle and pass it to setArguments() method.
I've found a tutorial: http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/
I haven't testes it but it looks good.
Are you really sure a bundle is really needed?
TOnlineMapViewFragment mapfrag = TOnlineMapViewFragment.newInstance(b);
mapfrag.setPlaceList(place_list)
Should be trivial to create setPlaceList(ArrayList<PlaceDetails> place_list) ...