When you choose Fragment over Activity?

  • Activities are designed to represent a single screen of my application, while
  • Fragments are designed to be reusable UI layouts with logic embedded inside of them

Google advises you to always use Fragments. In the simplest case, Fragments are used like containers of activities. Android 4 (ICS) supports both Smartphones and Tablets. This means the same application will be running on a smartphone and a tablet and they are likely to be very different.


Historically each screen in an Android app was implemented as a separate Activity. This creates a challenge in passing information between screens because the Android Intent mechanism does not allow passing a reference type (i.e. object) directly between Activities. By making each screen a separate Fragment, this data passing headache is completely avoided. Fragments always exist within the context of a given Activity and can always access that Activity. By storing the information of interest within the Activity, the Fragment for each screen can simply access the object reference through the Activity.

How fragment get context in Android?

You can use getActivity() , which returns the activity associated with a fragment. The activity is a context (since
Activity extends Context ). You can also override the onAttach() method of fragment:

public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    DBHelper = new DatabaseHelper(activity);
}
}