尝试在空对象引用上调用虚方法

时间:2016-01-17 20:12:26

标签: java android

这是一个计算按下按钮次数的脚本。当我运行我的代码时,我收到此错误:

01-17 19:49:18.670 27354-27354/com.example.ben.testapp
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ben.testapp, PID: 27354
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.ben.testapp/com.example.ben.testapp.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.SharedPreferences
android.content.Context.getSharedPreferences(java.lang.String, int)'
on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2515)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.content.SharedPreferences
android.content.Context.getSharedPreferences(java.lang.String, int)'
on a null object reference
at
android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:184)
at
com.example.ben.testapp.MainActivity.numberOfClicks(MainActivity.java:89)
at com.example.ben.testapp.MainActivity.<init>(MainActivity.java:57)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1650)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2505)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723) 
at android.app.ActivityThread.access$900(ActivityThread.java:172) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5832) 
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:1399) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

我最近添加的代码用于节省点击按钮的次数。

看起来像这样:

package com.example.ben.testapp;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    private int clickNo = numberOfClicks();

    public void buttonClick(View view) {

        final TextView ClickCount = (TextView) findViewById(R.id.buttonClicks);

        clickNo = clickNo+1;

        if (clickNo == 10){
            Snackbar achievement10 = Snackbar.make(view,"acheivement unlocked: score of ten",Snackbar.LENGTH_LONG);
            achievement10.show();
        }

        if (clickNo == 20){
            Snackbar achievement20 = Snackbar.make(view,"acheivement unlocked: does your finger hurt?",Snackbar.LENGTH_LONG);
            achievement20.show();
        }

        if (clickNo == 50){
            Snackbar achievement50 = Snackbar.make(view,"acheivement unlocked: do you have a life?",Snackbar.LENGTH_LONG);
            achievement50.show();
        }

        String number = "" + clickNo ;

        ClickCount.setText(number);

        saveClicks();

    }

    private int numberOfClicks() {
        SharedPreferences prefs = getSharedPreferences("numberOf clicks",MODE_PRIVATE);
        return prefs.getInt("clicks", 0);
    }

    private void saveClicks(){
        SharedPreferences prefs = getSharedPreferences("numberOf clicks",MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("clicks", clickNo);
        editor.apply();
    }
}

2 个答案:

答案 0 :(得分:4)

问题出在以下一行

private int clickNo = numberOfClicks();

您在创建clickNo实例之前初始化变量MainActivity,因此在空对象(您的活动基础上下文)引用上进行getSharedPreferences调用。

您应该在不初始化变量的情况下声明变量,然后再调用numberOfClicks

例如:

private int clickNo;

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

答案 1 :(得分:0)

您将空值分配给:

int clickNo = numberOfClicks();

numberOfClicks()函数返回null,因为您尚未运行saveClicks(),因此点击的偏好值为null