2

My app works fine on most devices, except in some, where even in the fragment's onActivityCreated, the getActivity method keeps returning null. I need Context class to set-up things.

So anyone can help me?

Example

public class BaseProductFragment extends Fragment {

...

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(layout_id, container,
            false);
    return rootView;
}

public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ImageCacheParams cacheParams = new ImageCacheParams(getActivity(),
            Utils.PRODUCTS_CACHE_DIR);
    ....
}
Top-Master
  • 7,611
  • 5
  • 39
  • 71
Takashi Lee
  • 145
  • 1
  • 2
  • 10

1 Answers1

6

getActivity "might" return null when called from within onActivityCreated...especially during a configuration change like orientation change because the activity gets destroyed...move that initialization to onAttach...

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    //initialize here
}

onActivityCreated is a called when the parent activity's onCreate is called...but remember that it could be "recreated", destroyed during a config change

Leo
  • 14,625
  • 2
  • 37
  • 55