java-尝试获取Activity的DefaultSharedPreferences时出现NullPointerException

我必须为实习开发一个应用程序,并且正在使用AndroidStudio.

现在,我只是在尝试事情,并且正在开发Spank计数器应用程序(是的,我知道).

我知道那里已经有一个回应:
What is a NullPointerException, and how do I fix it?
和许多其他类似我的问题.
事实是我误解了错误,但是在我的代码中找不到它.

(我没有放入xml文件,因为我认为这不是有用的,如果您想看到它,请打个招呼.)

对不起,如果很难阅读这篇文章.这是我第一次在论坛上提问.
在此先感谢那些勇于阅读并帮助我的人.

所以这里是错误:

                                                                          --------- beginning of crash
06-02 18:05:31.515 2680-2680/com.example.florian.fessee E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.florian.fessee, PID: 2680
                                                                          java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.florian.fessee/com.example.florian.fessee.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                              at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:135)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                                                                              at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
                                                                              at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
                                                                              at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
                                                                              at com.example.florian.fessee.MainActivity.<init>(MainActivity.java:23)
                                                                              at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                              at java.lang.Class.newInstance(Class.java:1606)
                                                                              at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                              at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at android.os.Looper.loop(Looper.java:135) 
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                                              at java.lang.reflect.Method.invoke(Native Method) 
                                                                              at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
06-02 18:11:28.569 3101-3101/com.example.florian.fessee D/AndroidRuntime: Shutting down VM
06-02 18:11:28.570 3101-3101/com.example.florian.fessee E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.florian.fessee, PID: 3101
                                                                          java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.florian.fessee/com.example.florian.fessee.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                              at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:135)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                                                                              at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
                                                                              at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
                                                                              at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
                                                                              at com.example.florian.fessee.MainActivity.<init>(MainActivity.java:23)
                                                                              at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                              at java.lang.Class.newInstance(Class.java:1606)
                                                                              at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                              at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at android.os.Looper.loop(Looper.java:135) 
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                                              at java.lang.reflect.Method.invoke(Native Method) 
                                                                              at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
06-02 18:16:53.409 3339-3339/com.example.florian.fessee D/AndroidRuntime: Shutting down VM
06-02 18:16:53.435 3339-3339/com.example.florian.fessee E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.florian.fessee, PID: 3339
                                                                          java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.florian.fessee/com.example.florian.fessee.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                              at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:135)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                                                                              at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
                                                                              at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
                                                                              at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
                                                                              at com.example.florian.fessee.MainActivity.<init>(MainActivity.java:23)
                                                                              at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                              at java.lang.Class.newInstance(Class.java:1606)
                                                                              at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                              at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at android.os.Looper.loop(Looper.java:135) 
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                                              at java.lang.reflect.Method.invoke(Native Method) 
                                                                              at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
06-02 18:19:42.932 3515-3515/com.example.florian.fessee D/AndroidRuntime: Shutting down VM
06-02 18:19:42.935 3515-3515/com.example.florian.fessee E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.florian.fessee, PID: 3515
                                                                          java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.florian.fessee/com.example.florian.fessee.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                              at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:135)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                                                                              at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
                                                                              at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
                                                                              at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
                                                                              at com.example.florian.fessee.MainActivity.<init>(MainActivity.java:23)
                                                                              at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                              at java.lang.Class.newInstance(Class.java:1606)
                                                                              at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                              at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at android.os.Looper.loop(Looper.java:135) 
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                                              at java.lang.reflect.Method.invoke(Native Method) 
                                                                              at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

这是我的代码:

package com.example.florian.fessee;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private int compt = 0;
    private Button b1 = null;
    private Button b5 = null;
    private Button b01 = null;
    private Button b05 = null;
    private Button braz = null;
    private TextView t = null;
    private String COMPT = "comptfess";

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = preferences.edit();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        b1 = (Button) findViewById(R.id.button1);
        b5 = (Button) findViewById(R.id.button5);
        b01 = (Button) findViewById(R.id.button01);
        b05 = (Button) findViewById(R.id.button05);
        braz = (Button) findViewById(R.id.buttonraz);

        t = (TextView) findViewById(R.id.textView);

        compt = preferences.getInt(COMPT, 0);

        b1.setOnClickListener(b1Listener);
        b5.setOnClickListener(b5Listener);
        b01.setOnClickListener(b01Listener);
        b05.setOnClickListener(b05Listener);
        braz.setOnClickListener(brazListener);

        if (compt == 1) {
            t.setText("Je dois 1 fessée à Sophie.");
        }
        else if (compt!=0){
            t.setText("Je dois " + compt + "fessées à Sophie.");
        }

    }

    private View.OnClickListener b1Listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            compt +=1;

            editor.putInt(COMPT,compt);
            editor.commit();

            if (compt == 1) {
                t.setText("Je dois 1 fessée à Sophie.");
            }
            else if (compt!=0){
                t.setText("Je dois " + compt + "fessées à Sophie.");
            }
        }
    };

    private View.OnClickListener b5Listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            compt +=5;

            editor.putInt(COMPT,compt);
            editor.commit();

            if (compt == 1) {
                t.setText("Je dois 1 fessée à Sophie.");
            }
            else if (compt!=0){
                t.setText("Je dois " + compt + "fessées à Sophie.");
            }
        }
    };

    private View.OnClickListener b01Listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(compt!=0){
                compt -=1;

                editor.putInt(COMPT,compt);
                editor.commit();

                if (compt==0){
                    t.setText("Je ne dois plus de fessées å Sophie");
                }

                else if (compt == 1) {
                    t.setText("Je dois 1 fessée à Sophie.");
                }
                else{
                    t.setText("Je dois " + compt + "fessées à Sophie.");
                }

            }
            else {
                Toast.makeText(MainActivity.this, "Un nombre de fessées doit être positif.", Toast.LENGTH_SHORT).show();
            }
        }
    };

    private View.OnClickListener b05Listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(compt>4){
                compt -=5;

                editor.putInt(COMPT,compt);
                editor.commit();

                if (compt==0){
                    t.setText("Je ne dois plus de fessées å Sophie.");
                }

                else if (compt == 1) {
                    t.setText("Je dois 1 fessée à Sophie.");
                }
                else{
                    t.setText("Je dois " + compt + "fessées à Sophie.");
                }

            }
            else {
                Toast.makeText(MainActivity.this, "Un nombre de fessées doit être positif.", Toast.LENGTH_SHORT).show();
            }
        }
    };

    private View.OnClickListener brazListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            compt = 0;
            editor.putInt(COMPT,compt);
            editor.commit();
            t.setText("Je ne dois plus de fessées à Sophie.");
        }
    };
}

解决方法:

这是你的问题:

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = preferences.edit();

在创建活动之前,您无法初始化SharedPreferences.像这样分开声明和实例化:

...

SharedPreferences preferences;
SharedPreferences.Editor editor;

...

@Override
public void onCreate(Bundle savedInstanceState){

    ...

    preferences = PreferenceManager.getDefaultSharedPreferences(this);
    editor = preferences.edit();

    ...

}
上一篇:在Java的另一个类中实例化/初始化的对象的引用变量


下一篇:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法’void android.widget.ImageView.setImageResource(int)’