Reputation: 419
I want to pass certain values from an activity to a fragment in android. Here is some code:-
MainActivity:-
PlaceDialogFragment dialogFragment = new PlaceDialogFragment(place,dm);
Fragment:-
public PlaceDialogFragment(Place place, DisplayMetrics dm){
super();
this.mPlace = place;
this.mMetrics = dm;
}
Using a constructor in the fragment gives me an error:-
Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead
If i replace the constructor with:-
public static final DialogFragment newInstance(Place place, DisplayMetrics dm)
{
DialogFragment fragment = new DialogFragment();
Bundle bundle = new Bundle(2);
bundle.putParcelable("Place", place);
bundle.putFloat("Metrics", dm.density);
fragment.setArguments(bundle);
return fragment ;
}
I get an error in the MainActivity.Java :-
The constructor PlaceDialogFragment(Place, DisplayMetrics) is undefined
How do i resolve this?
Upvotes: 0
Views: 1896
Reputation: 2879
You can do this in this manner:
From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Upvotes: 1
Reputation: 6409
Change your Activity to use the new method.
PlaceDialogFragment dialogFragment = PlaceDialogFragment.newInstance(place, dm);
Upvotes: 1