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

时间:2018-10-13 06:56:44

标签: java android nullpointerexception onesignal

我试图计算来自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);
    }
}

1 个答案:

答案 0 :(得分:0)

您的SharedPref对象为,请按照以下方式操作:

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