Skip to content

Instantly share code, notes, and snippets.

@rhexgomez
Last active October 22, 2016 06:23
Show Gist options
  • Save rhexgomez/9f3bb92f7000443bcb9c5ad17c498c40 to your computer and use it in GitHub Desktop.
Save rhexgomez/9f3bb92f7000443bcb9c5ad17c498c40 to your computer and use it in GitHub Desktop.
The proper way of getting the Activity or Fragment Manager from the Context.
/*
* Copyright 2016 Elmar Rhex Gomez.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public class ContextHelper {
/**
* The method that unwraps the the Context inorder to
* obtained the Fragment Manager.
*
* @param context the Context to unwrap.
* @return the Fragment Manager. Otherwise it returns null if not found.
*/
public static FragmentManager getFragmentManager(Context context) {
Activity activity = getActivity(context);
if (activity instanceof FragmentActivity) {
return ((FragmentActivity) activity).getSupportFragmentManager();
}
return null;
}
/**
* The method that unwraps the the Context inorder to
* obtained the Activity.
*
* @param context the Context to unwrap.
* @return the Activity. Otherwise it returns null if not found.
*/
public static Activity getActivity(Context context) {
if (context == null) {
throw new NullPointerException("Context must not be null");
}
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
throw new IllegalArgumentException("The Context is not an Activity context!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment