program story

null 객체 참조에 대한 android.content.Context.getPackageName () '

inputbox 2020. 11. 28. 09:15
반응형

null 객체 참조에 대한 android.content.Context.getPackageName () '


안녕하세요 저는 인터페이스를 구현하는 Fragments로 작업하고 있습니다.

public class SigninFragment extends Fragment implements SigninInterface 

프래그먼트 클래스에서 인터페이스의 메소드 구현은 다음과 같습니다.

@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
    }

}

이 메서드는 AsyncTask를 확장하는 AsynchronousTask 클래스를 추출한 후 호출됩니다.

하지만 충돌이 발생합니다. 그리고 오류 메시지는

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.<init>(ComponentName.java:77)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.content.Intent.<init>(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)

나는 나 자신을 시도하고 Google에서 탐구했습니다. 그러나 나는 어떤 해결책도 얻지 못했습니다. 아무도 이것에 대해 도울 수 있습니까?


나는 내가 한 실수를 발견했습니다. 재정의 메서드 OnAttach ()에서 활동 인스턴스를 가져와야합니다. 예를 들면 다음과 같습니다.

public MainActivity activity;

@Override
public void onAttach(Activity activity){
    this.activity = activity;
}

그런 다음 활동을 다음과 같이 컨텍스트로 전달하십시오.

Intent mIntent = new Intent(activity, MusicHome.class);

이 질문에 대한 답변은 내 문제를 찾는 데 도움이되었지만 소스가 달랐으므로 '무작위'컨텍스트 충돌에 대한 답변을 검색하는이 페이지를 찾는 사람에게 빛을 비출 수 있기를 바랍니다.

SharedPreferences 개체를 지정하고 다음과 같이 클래스 수준 선언에서 인스턴스화하려고했습니다.

public class MyFragment extends FragmentActivity {
    private SharedPreferences sharedPref =
        PreferenceManager.getDefaultSharedPreferences(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //...

thisonCreate 이전에 참조 하면 "java.lang.NullPointerException : 널 오브젝트 참조에서 가상 메소드 'java.lang.String android.content.Context.getPackageName ()'호출 시도"오류가 발생했습니다.

onCreate () 내부에서 객체를 인스턴스화하면 다음과 같이 문제가 해결되었습니다.

public class MyFragment extends FragmentActivity {
    private SharedPreferences sharedPref ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

도움이되기를 바랍니다.


안드로이드 API 레벨 23.

사용하다

getContext ()

대신에

getActivity ()

getActivity ()는 부모 Activity, Context 객체를 제공합니다.

여기에서 사용할 수 있습니다

MyActivity.this

대신에

getActivity () / getApplicationContext ()


이 작업 만 수행하면됩니다.

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

나에게 문제는 내가 Context가 아닌 생성자에게 Activity를 전달한다는 것입니다.

public Adapter(Activity activity, List<MediaItem> 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


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. You can block the clicks after the user clicked once.


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.


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))
            })
          ...
    }

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

참고URL : https://stackoverflow.com/questions/28515049/android-content-context-getpackagename-on-a-null-object-reference

반응형