有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

尝试获取活动的DefaultSharedReferences时发生java NullPointerException

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

现在我只是在尝试一些东西,我正在开发一个“屁股计数器”应用程序(是的,我知道)

我知道已经有了回应: 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 安卓.content.Context.getPackageName()' on a null object reference
                                                                              at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                                              at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                              at 安卓.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                              at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                              at 安卓.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at 安卓.os.Looper.loop(Looper.java:135)
                                                                              at 安卓.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.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                              at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String 安卓.content.Context.getPackageName()' on a null object reference
                                                                              at 安卓.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
                                                                              at 安卓.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
                                                                              at 安卓.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 安卓.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                                              at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                                                                              at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                              at 安卓.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                              at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                              at 安卓.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at 安卓.os.Looper.loop(Looper.java:135) 
                                                                              at 安卓.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.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                              at com.安卓.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 安卓.content.Context.getPackageName()' on a null object reference
                                                                              at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                                              at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                              at 安卓.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                              at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                              at 安卓.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at 安卓.os.Looper.loop(Looper.java:135)
                                                                              at 安卓.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.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                              at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String 安卓.content.Context.getPackageName()' on a null object reference
                                                                              at 安卓.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
                                                                              at 安卓.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
                                                                              at 安卓.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 安卓.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                                              at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                                                                              at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                              at 安卓.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                              at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                              at 安卓.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at 安卓.os.Looper.loop(Looper.java:135) 
                                                                              at 安卓.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.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                              at com.安卓.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 安卓.content.Context.getPackageName()' on a null object reference
                                                                              at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                                              at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                              at 安卓.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                              at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                              at 安卓.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at 安卓.os.Looper.loop(Looper.java:135)
                                                                              at 安卓.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.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                              at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String 安卓.content.Context.getPackageName()' on a null object reference
                                                                              at 安卓.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
                                                                              at 安卓.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
                                                                              at 安卓.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 安卓.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                                              at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                                                                              at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                              at 安卓.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                              at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                              at 安卓.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at 安卓.os.Looper.loop(Looper.java:135) 
                                                                              at 安卓.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.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                              at com.安卓.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 安卓.content.Context.getPackageName()' on a null object reference
                                                                              at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                                              at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                              at 安卓.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                              at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                              at 安卓.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at 安卓.os.Looper.loop(Looper.java:135)
                                                                              at 安卓.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.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                              at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String 安卓.content.Context.getPackageName()' on a null object reference
                                                                              at 安卓.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
                                                                              at 安卓.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
                                                                              at 安卓.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 安卓.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                                              at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                                                                              at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                              at 安卓.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                              at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                              at 安卓.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at 安卓.os.Looper.loop(Looper.java:135) 
                                                                              at 安卓.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.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                              at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

这是我的代码:

package com.example.florian.fessee;

import 安卓.content.SharedPreferences;
import 安卓.preference.PreferenceManager;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.os.Bundle;
import 安卓.view.View;
import 安卓.widget.Button;
import 安卓.widget.TextView;
import 安卓.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.");
        }
    };
}

共 (2) 个答案

  1. # 1 楼答案

    这就是你的问题:

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

    在创建活动之前,无法初始化SharedReferences。将声明和实例化分开,如下所示:

    ...
    
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    
    ...
    
    @Override
    public void onCreate(Bundle savedInstanceState){
    
        ...
    
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = preferences.edit();
    
        ...
    
    }
    
  2. # 2 楼答案

    你的论点似乎可以归结为这样一个观点:将活动上下文传递给getDefaultSharedPreferences()应该是有效的

    通常情况下,它应该,但只有在活动的上下文完全初始化后才。我相信只有在呼叫^{期间或之后才是这样

    您可以在您所在的位置声明与首选项相关的变量,但在onCreate()期间或之后才尝试初始化它们