Passing an Object from an Activity to a Fragment

Passing an Object from an Activity to a Fragment

Create a static method in the Fragment and then get it using getArguments().

Example:

public class CommentsFragment extends Fragment {
private static final String DESCRIBABLE_KEY = "describable_key";
private Describable mDescribable;

public static CommentsFragment newInstance(Describable describable) {
CommentsFragment fragment = new CommentsFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(DESCRIBABLE_KEY, describable);
fragment.setArguments(bundle);

return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {

mDescribable = (Describable) getArguments().getSerializable(
DESCRIBABLE_KEY);

// The rest of your code
}

You can afterwards call it from the Activity doing something like:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment fragment = CommentsFragment.newInstance(mDescribable);
ft.replace(R.id.comments_fragment, fragment);
ft.commit();

Send object from Activity to Fragment using Bundle

Both MyProfile and Employee don't implement Parcelable

The hard way: Make your classes implement Parcelable as per the documentation.

The easy way: Add this lib. That will auto generate that for you. Will just need to do

bundle.putParcelable("myProfile", Parcels.wrap(myProfile));
bundle.putParcelable("employee", Parcels.wrap(employee());

MyProfile myProfile = Parcels.unwrap(getArguments().getParcelable("myProfile"));
Employee employee = Parcels.unwrap(getArguments().getParcelable("employee"));

and add the @Parcel annotation on your classes:

@Parcel
public class MyProfile{//rest of the normal code}

@Parcel
public class Employee{//rest of the normal code}

How can pass array list object from an activity to fragment in android

Try this code in your activity, It is a code snippet from my working application.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourArrayList.add("test");
yourArrayList.add("test2")
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayList", yourArrayList);
yourFragment yourFragment = new yourFragment();
yourFragment.setArguments(bundle);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container, yourFragment);
fragmentTransaction.commit();
}

In your fragment you can access the value like this

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

ArrayList<String> values = getArguments().getStringArrayList("arrayList");

}

How to pass objects from activity to fragments?

You should implement Parcelize as below

  @Parcelize
@JsonClass(generateAdapter = true)
data class FullForecast(@Json(name = "list")
val forecastList: List<WeatherForecast>) : Parcelable {
}

@Parcelize
@JsonClass(generateAdapter = true)
data class WeatherForecast(@Json(name = "main")
val weatherDetail: WeatherDetail,

@Json(name = "weather")
val weatherIcon: List<WeatherIcon>,

@Json(name = "dt_txt")
val date: String) : Parcelable {
}

@Parcelize
@JsonClass(generateAdapter = true)
data class Place(@Json(name = "main")
val weatherDetail: WeatherDetail,

@Json(name = "weather")
val weatherIcon: List<WeatherIcon>,

@Json(name = "sys")
val countryDetail: CountryDetail,

@Json(name = "dt_txt")
var forecastDate: String = "",

val name: String,

var placeIdentifier: String = "",

var lastUpdated: String = "") : Parcelable {
}

@Parcelize
@JsonClass(generateAdapter = true)
data class CountryDetail(val country: String) : Parcelable {
}

@Parcelize
@JsonClass(generateAdapter = true)
data class WeatherDetail(@Json(name = "temp")
val temperature: Double,
val temp_min: Double,
val temp_max: Double) : Parcelable {
}

@Parcelize
@JsonClass(generateAdapter = true)
data class WeatherIcon(val icon: String) : Parcelable {
}

If you face error:

enter image description here

This is a known bug in the IDE itself and you can ignore it, there’s nothing wrong with the code and it works as expected. You can keep track of the issue here.

How to pass custom objects from an activity to a fragment?

You can do something like this:

Your activity:

public class YourActivity extends AppCompatActivity {

...
public Drawable drawableToGet; //Here is the drawable you want to get
...

}

In your Fragment:

public Drawable getDrawableFromActivity(){
Activity activity = getActivity();
if(activity instanceof YourActivity){
return ((YourActivity) activity).drawableToGet;
} else {
//Fragment isn't attached to YourActivity
return null;
}
}

Passing Object from Fragment to Activity

You could have an interface:

public interface MyInterface {
void doSomethingWithData(Object data);
}

then in the activity class:

public class MyActivity extends Activity implements MyInterface {
...
public void doSomethingWithData(Object data) {
// save your data in database
}
...
}

and in fragments:

public class MyFragment extends Fragment {
...
private MyInterface listener;
...
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof MyInterface) {
listener = (MyInterface) context;
}
}

@Override
public void onDetach() {
listener = null;
super.onDetach();
}
...
// Somewhere in code .. where you want to send data to the activity
listener.doSomethingWithData(data);
...
}

Parcelable object passing from android activity to fragment

Try this

First, change some small things.

MainActivity.java

// 1. Parse the object to the fragment as a bundle;
ContentMainFragment contentMainFragment = new ContentMainFragment();

Bundle bundle = new Bundle();
bundle.putParcelable("SampleObject", currentObject);
contentMainFragment.setArguments(bundle);

// 2. Commit the fragment.
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, contentMainFragment).commit();

ContentMainFragment.java

// 1. Get the object in onCreate();
if (getArguments() != null) {
link = getArguments().getParcelable("SampleObject").getLink();
}

Second, it doesn't seem there is something wrong with your approach, then double check if you are parsing a valid object (currentObject) in the Activity.



Related Topics



Leave a reply



Submit