Невозможно отобразить уведомление при обновлении списка action_booking, вместо этого мое приложение упало - PullRequest
0 голосов
/ 04 апреля 2020

На самом деле я хочу, чтобы уведомление о полной странице отображалось при каждом новом бронировании. Я уже создаю класс NotificationReceiver, у которого есть метод с именем sendNotification для отображения уведомления, и я вызываю этот метод внутри моего ActionBookingAdapter в bindObject. Но когда я запускаю приложение, я получаю исключение:

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
        at android.content.ContextWrapper.getPackageName(ContextWrapper.java:152)
        at android.content.ComponentName.<init>(ComponentName.java:130)
        at android.content.Intent.<init>(Intent.java:6108)
        at com.fitness.client.services.NotificationReceiver.sendNotification(NotificationReceiver.java:160)
        at com.fitness.client.ui.main.fragments.home.fragments.action.adapter.ActionBookingAdapter$ActionBookingHolder.bindObject(ActionBookingAdapter.java:65)
        at com.fitness.client.ui.main.fragments.home.fragments.action.adapter.ActionBookingAdapter$ActionBookingHolder.bindObject(ActionBookingAdapter.java:50)
        at com.fitness.client.base.classes.BaseRecyclerViewAdapter.onBindViewHolder(BaseRecyclerViewAdapter.java:39)
        at com.fitness.client.base.classes.BaseRecyclerViewAdapter.onBindViewHolder(BaseRecyclerViewAdapter.java:16)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)

Вот NotificationReceiver. java получена ошибка при создании объекта Intent с использованием «this»


import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;

import androidx.core.app.NotificationCompat;

import com.fitness.client.R;
import com.fitness.client.ui.main.MainActivity;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.messaging.FirebaseMessagingService;

import java.util.Objects;

public class NotificationReceiver extends FirebaseMessagingService {

    public void sendNotification(String messageBody) {
//        Intent intent = new Intent(NotificationReceiver.this, MainActivity.class);
//        Intent intent = new Intent(getBaseContext(), MainActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        **Intent intent = new Intent(this, MainActivity.class);**
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 113, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        String channelId = "fcm_default_channel";
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)

                        .setContentTitle("Standard message")
                        .setContentText(messageBody)
                        .setSmallIcon(R.drawable.logo)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent)
                        .setFullScreenIntent(pendingIntent,true);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            Objects.requireNonNull(notificationManager).createNotificationChannel(channel);
        }

        Objects.requireNonNull(notificationManager).notify(115 /* ID of notification */, notificationBuilder.build());
    }

}

И мой ActionBookingAdapter. java

package com.fitness.client.ui.main.fragments.home.fragments.action.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.fitness.client.R;
import com.fitness.client.api.RetroFitFactory;
import com.fitness.client.api.order.OrderAcceptResponse;
import com.fitness.client.api.order.OrderRejectResponse;
import com.fitness.client.api.order.OrderService;
import com.fitness.client.api.order.UpComingResponse;
import com.fitness.client.base.classes.BaseRecyclerViewAdapter;
import com.fitness.client.base.classes.BaseViewHolder;
import com.fitness.client.databinding.ItemActionBookingBinding;
import com.fitness.client.objects.Order;
import com.fitness.client.services.NotificationReceiver;
import com.fitness.client.ui.main.App;
import com.fitness.client.ui.main.MainActivity;
import com.fitness.client.ui.main.fragments.home.HomeFragment;
import com.fitness.client.ui.main.fragments.home.fragments.upcoming.UpComingFragment;
import com.fitness.client.ui.main.fragments.home.fragments.upcoming.adapter.UpcominBookingAdapter;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ActionBookingAdapter extends BaseRecyclerViewAdapter<ActionBookingAdapter.ActionBookingHolder, Order> {
    //TODO: Do something with upComingListener
    private ActionListener actionListener;
//    private UpcominBookingAdapter.UpComingListener upComingListener;
    public ActionBookingAdapter(List<Order> data, ActionListener actionListener) {
        super(data);
        this.actionListener = actionListener;
//        this.upComingListener = upComingListener;
    }

    @NonNull
    @Override
    public ActionBookingHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ActionBookingHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_action_booking, parent, false));
    }

    class ActionBookingHolder extends BaseViewHolder<Order, ItemActionBookingBinding> {

        public ActionBookingHolder(View itemView) {
            super(itemView);
        }

        @Override
        protected void bindObject(Order object) {

//            NotificationReceiver notificationReceiver = new NotificationReceiver();
//            notificationReceiver.sendNotification("You got New Booking");
            //TODO: Maybe we should call notificationReceiver here
            if (object != null) {
                //Set up the notification
                NotificationReceiver notificationReceiver = new NotificationReceiver();
                notificationReceiver.sendNotification("You got New Booking");
            }
            getViewDataBinding().setActionBooking(object);
            getViewDataBinding().accept.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    RetroFitFactory
                            .getRetrofitCallFor(OrderService.class)
                            .acceptOrder(object.getId())
                            .enqueue(new Callback<OrderAcceptResponse>() {
                                @Override
                                public void onResponse(Call<OrderAcceptResponse> call, Response<OrderAcceptResponse> response) {
                                    Toast.makeText(getContext(), "Accepted", Toast.LENGTH_LONG).show();
                                    actionListener.onReferesh();
                                    //Refresh the activity
                                    //TODO: Solve app crash on accept
                                    MainActivity activity = new MainActivity();
                                    activity.recreate();
                                }

                                @Override
                                public void onFailure(Call<OrderAcceptResponse> call, Throwable t) {
                                    Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });

                }
            });

            getViewDataBinding().reject.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    RetroFitFactory
                            .getRetrofitCallFor(OrderService.class)
                            .rejectOrder(object.getId())
                            .enqueue(new Callback<OrderRejectResponse>() {
                                @Override
                                public void onResponse(Call<OrderRejectResponse> call, Response<OrderRejectResponse> response) {
                                    Toast.makeText(getContext(), "Rejected", Toast.LENGTH_LONG).show();
                                    actionListener.onReferesh();
                                }

                                @Override
                                public void onFailure(Call<OrderRejectResponse> call, Throwable t) {
                                    Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });

                }
            });

        }
    }

    public interface ActionListener {
        void onReferesh();
    }
}

1 Ответ

0 голосов
/ 04 апреля 2020

Вы должны поместить public void sendNotification(String messageBody) в OnMessageReceived() метод, подобный этому

public class NotificationReceiver extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
           sendNotification(String messageBody);
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...