android.content.Context.getPackageName()' on a null object reference
I had the same problem trying to show a Toast in a fragment.
After some debugging I found out that I was removing the fragment before calling:
Toast.makeText(getContext(), "text", Toast.LENGTH_SHORT).show();
Because the fragment had been removed, the context became null, causing the exception.
Simple solution: call the getContext()
before removing the fragment.
android API level 23.
Use
getContext()
instead of
getActivity()
getActivity() gives the parent Activity, a Context object
Here You can use
MyActivity.this
instead of
getActivity() / getApplicationContext()
I have found the mistake what I did. We need to get the activity instance from the override method OnAttach() For example,
public MainActivity activity;
@Override
public void onAttach(Activity activity){
this.activity = activity;
}
Then pass the activity as context as following.
Intent mIntent = new Intent(activity, MusicHome.class);
The answers to this question helped me find my problem, but my source was different, so hopefully this can shed light on someone finding this page searching for answers to the 'random' context crash:
I had specified a SharedPreferences object, and tried to instantiate it at it's class-level declaration, like so:
public class MyFragment extends FragmentActivity {
private SharedPreferences sharedPref =
PreferenceManager.getDefaultSharedPreferences(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
Referencing this
before the onCreate caused the "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference" error for me.
Instantiating the object inside the onCreate() solved my problem, like so:
public class MyFragment extends FragmentActivity {
private SharedPreferences sharedPref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Hope that helps.