android.content.Context.getPackageName()' on a null object reference

匿名 (未验证) 提交于 2019-12-03 01:19:01

问题:

Hi I am working with Fragments which implements an interface.

public class SigninFragment extends Fragment implements SigninInterface 

The interface's method implementation in the fragment class is as follows.

@Override public void afterSubmitClicked(String userId, Bundle bundle) {      Log.d(TAG,"Calling time afterSubmitClicked called"+bundle);      if(!userId.equals("-1")){         //Logged in successfully         //Move to MusicHome          Intent mIntent = new Intent(getActivity(),MusicHome.class);         mIntent.putExtra("SigninFragment.user_details", bundle);         startActivity(mIntent);      }else{         //Logging in failed         //show error dialog     }  }

This method is called after exectuting a AsynchronousTask (which extends AsyncTask) class.

But I am getting crash. And the error message shows

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

Logcat

   02-14 16:37:04.648: E/AndroidRuntime(28177): Process: com.raaga.android, PID: 28177 02-14 16:37:04.648: E/AndroidRuntime(28177): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference 02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.content.ComponentName.(ComponentName.java:77) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.content.Intent.(Intent.java:3996) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at com.raaga.fragments.SigninFragment.afterSubmitClicked(SigninFragment.java:152) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at com.raaga.asynctask.SignInAsyncTask.onPostExecute(SignInAsyncTask.java:92) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at com.raaga.asynctask.SignInAsyncTask.onPostExecute(SignInAsyncTask.java:1) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.os.AsyncTask.finish(AsyncTask.java:632) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.os.AsyncTask.access$600(AsyncTask.java:177) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.os.Handler.dispatchMessage(Handler.java:102) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.os.Looper.loop(Looper.java:135) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.app.ActivityThread.main(ActivityThread.java:5221) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at java.lang.reflect.Method.invoke(Native Method) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at java.lang.reflect.Method.invoke(Method.java:372) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 02-14 16:37:04.648: E/AndroidRuntime(28177):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

I have tried myself and explored in Google. But I didn't get any solution. Could any one help on this ?

回答1:

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);


回答2:

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.



回答3:

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()



回答4:

For me the problem was that I was passing Activity to the constructor, not Context

public Adapter(Activity activity, List items, boolean can) {     mItems = items;     canEdit = can;     mActivity = activity; }

and using this activity to getDefaultSharedPreferences(), so I changed the Activity to Context and I was still calling the Adapter constructor with MainActivity.this



回答5:

You only need to do this:

Intent myIntent = new Intent(MainActivity.this, nextActivity.class);


回答6:

In my case the error occurred inside a Fragment on this line:

Intent intent = new Intent(getActivity(), SecondaryActivity.class);

It happened when I double clicked on an item which triggered the code above so two SecondaryActivity.class activities were launched at the same time, one on top of the other. I closed the top SecondaryActivity.class activity by pressing back button which triggered a call to getActivity() in the SecondaryActivity.class which came to foreground. The call to getActivity() returned null. It's some kind of weird Android bug so it usually should not happen.



回答7:

My class is not extends to Activiti. I solved the problem this way.

class MyOnBindViewHolder : LogicViewAdapterModel.LogicAdapter {           ...  holder.title.setOnClickListener({v->                 v.context.startActivity(Intent(context,  HomeActivity::class.java))             })           ...     }


回答8:

You solve the issue with a try/ catch. This crash happens when user close the app before the start intent.

try {     Intent mIntent = new Intent(getActivity(),MusicHome.class);     mIntent.putExtra("SigninFragment.user_details", bundle);     startActivity(mIntent); } catch (Exception e) {     e.printStackTrace(); }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!