java.lang.NullPointerException:尝试在空对象引用上调用虚方法 'int com.x.x.Helper.SharedPref.GetInt(java.lang.String)'

java.lang.NullPointerException: Attempt to invoke virtual method 'int com.x.x.Helper.SharedPref.GetInt(java.lang.String)' on a null object reference

我正在尝试对来自 OneSignal 的通知进行计数,并使其显示在徽章中,但我仍然收到此错误。我的代码有什么问题?

public class HomeActivity extends AppCompatActivity implements NetworkBroadcastListener.iNetStats, iNotif {

Context context;
SharedPref spref;
TextView notif_badge;

protected void onCreate(Bundle savedInstanceState){
 super.onCreate(savedInstanceState);
        OneSignal.startInit(this).init();
        setContentView(R.layout.activity_home);

notif_badge = findViewById(R.id.cart_badge);
        setupBadge();



private void setupBadge() {
        int counter = spref.GetInt(localPref.TOTALNOTIF);
        context=this;
        spref = new SharedPref(this);
        notif_badge.setText(String.valueOf(Math.min(counter,99)));
    }

这是我的 OneSignal ReceiveHandler

public class NotifReceivedHandler implements OneSignal.NotificationReceivedHandler {

    Context context;

    SharedPref spref;

    public NotifReceivedHandler(Context context){
        this.context = context;
        spref = new SharedPref(context);
    }

    @Override
    public void notificationReceived(OSNotification notification) {
        Intent intent = new Intent();
        intent.setAction("com.x.x.NOTIFICATION");
        intent.putExtra("body",notification.payload.body);
        intent.putExtra("title",notification.payload.title);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        spref.AddInt(localPref.TOTALNOTIF,spref.GetInt(localPref.TOTALNOTIF)+1);
    }
}

您的 SharedPref 对象是 null,请这样做:

private void setupBadge() {
    spref = new SharedPref(this); // This line initializes spref object.
    int counter = spref.GetInt(localPref.TOTALNOTIF); // here, spref was null because, it wasn't initialized yet.
    context=this;
    notif_badge.setText(String.valueOf(Math.min(counter,99)));
}