Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to cast with getActivity()?

I'm writing an app that has a parent Activity and several child Fragments. I am trying to get the Fragment to communicate back to the parent Activity. I know there are several ways to do this, including making an interface and implementing that in the parent Activity. However, I am interested in this method:

ParentActivity activity = (ParentActivity) getActivity();
activity.someMethod();

This approach takes less code and is less complex. However, is this cast safe to do in production code? Or is an interface safer?

like image 922
crocboy Avatar asked Jul 19 '14 19:07

crocboy


3 Answers

You can use this -

private ParentActivity callback;

@Override
public void onAttach(Activity activity)
{
    //callback = (ParentActivity ) activity;
    // make sure there is no cast exception
    callback = (ParentActivty.class.isAssignableFrom(activity
            .getClass())) ? (ParentActivity) activity : null;

    super.onAttach(activity);
}

@Override
public void onDetach()
{
    callback = null;
    super.onDetach();
}

now when you do any method call , call it like this -

if(callback!=null)
{
callback.someMethod();
}

this method is safe .

like image 77
Ratul Ghosh Avatar answered Oct 20 '22 21:10

Ratul Ghosh


It is safe (i.e. you won't get a ClassCastException), as long as you make sure that only ParentActivity ever creates/adds your Fragment.

These classes are now effectively coupled, which is, in general, not a good thing.

like image 5
matiash Avatar answered Oct 20 '22 19:10

matiash


By casting to a specific Activity class (ParentActivity), you are losing the ability to re-use the fragment with different activities. It's safe to cast, as long as you only use the fragment with that one activity.

Using an interface allows the fragment to be used with multiple activities - you just need to implement the interface in the activities that use the fragment.

Another option is to use an Event Bus - like GreenRobot's EventBus or Square's Otto

like image 1
GreyBeardedGeek Avatar answered Oct 20 '22 20:10

GreyBeardedGeek