简体   繁体   English

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

[英]Attempt to invoke virtual method on a null object reference

This is a script that counts how many times I pressed the button. 这是一个脚本,它计算了我按下按钮的次数。 When I run my code, I get this error: 运行代码时,出现以下错误:

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)

I have recently added code meant to save the amount of times I have clicked the button. 我最近添加了一些代码,以节省单击按钮的次数。

It looks like this: 看起来像这样:

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

Problem is in following line 问题在下一行

private int clickNo = numberOfClicks();

You are initializing variable clickNo before MainActivity instance is created and therefore getSharedPreferences call is made on null object (your activity basecontext) reference. 您将在创建MainActivity实例之前初始化变量clickNo ,因此getSharedPreferences空对象(您的活动basecontext)引用进行getSharedPreferences调用。

You should declare variable without initializing it and then call numberOfClicks later on. 您应该声明变量而不对其进行初始化,然后再调用numberOfClicks

For instance: 例如:

private int clickNo;

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

You're assigning a null value to: 您正在将空值分配给:

int clickNo = numberOfClicks();

The numberOfClicks() function returns null because you haven't ran saveClicks() yet, thus the preference value of clicks is null . numberOfClicks()函数返回null因为您尚未运行saveClicks() ,因此clicks的首选项值为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM