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