尝试获取Activity的DefaultSharedPreferences时发生NullPointerException [英] NullPointerException when trying to get DefaultSharedPreferences for Activity

查看:67
本文介绍了尝试获取Activity的DefaultSharedPreferences时发生NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to develop an app for an internship and I'm using AndroidStudio.

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

For now I'm just trying things and I'm developping a Spank counters app (yeah yeah I know).

我知道那里已经有一个回应:什么是NullPointerException,我该如何解决?和许多其他类似我的问题.事实是我误解了该错误,但在我的代码中找不到它.

I know that there is already a response there : What is a NullPointerException, and how do I fix it? and many other questions similar to mine. The fact is I understant the error but I can't find it in my code.

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

(I havn't put the xml file because I don't think it's usefull bet let me konw if you want to see it.)

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

Sorry if it's hard to read this post. It's the first time I ask something on a forum. Thanks in advance for those who will be brave enough to read it and help me.

这是错误:

                                                                          --------- 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.像这样分开声明和实例化:

You can't initialize SharedPreferences before the Activity has been created. Separate your declaration and instantiation like this:

...

SharedPreferences preferences;
SharedPreferences.Editor editor;

...

@Override
public void onCreate(Bundle savedInstanceState){

    ...

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

    ...

}

这篇关于尝试获取Activity的DefaultSharedPreferences时发生NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆