You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Firebase通知在Android ListView中显示为null的问题

Hey there! Let's break down the possible issues causing your Firebase notifications to show null content and fail to populate your ListView/RecyclerView properly. I'll walk through common pitfalls in the classes you mentioned, with actionable fixes:

1. Verify Data Handling in FcmMessagingService

Firebase has two notification types—notification messages and data messages—and their behavior changes depending on whether your app is in the foreground or background. If you're only relying on notification messages, your onMessageReceived won't trigger when the app is in the background, leading to null data when you tap the notification.

Here's a robust way to handle both types and pass data to your lst Activity:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    String title = "Default Title";
    String message = "Default Message";

    // Pull from notification payload (works for foreground apps)
    if (remoteMessage.getNotification() != null) {
        title = remoteMessage.getNotification().getTitle() != null 
            ? remoteMessage.getNotification().getTitle() 
            : title;
        message = remoteMessage.getNotification().getBody() != null 
            ? remoteMessage.getNotification().getBody() 
            : message;
    }

    // Pull from data payload (works for ALL app states)
    if (!remoteMessage.getData().isEmpty()) {
        title = remoteMessage.getData().getOrDefault("title", title);
        message = remoteMessage.getData().getOrDefault("message", message);
    }

    // Build intent to launch your lst Activity with data
    Intent intent = new Intent(this, lst.class);
    intent.putExtra("NOTIF_TITLE", title);
    intent.putExtra("NOTIF_MESSAGE", message);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    
    PendingIntent pendingIntent = PendingIntent.getActivity(
        this, 
        0, 
        intent, 
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
    );

    // Build and show the notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "YOUR_CHANNEL_ID")
            .setSmallIcon(R.drawable.ic_notif)
            .setContentTitle(title)
            .setContentText(message)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    NotificationManagerCompat.from(this).notify(1, builder.build());
}

Pro tip: Have your server send data messages (or a mix of notification + data) to ensure you always get the payload, regardless of app state.

2. Fix Data Retrieval in lst Activity

Make sure you're correctly pulling the intent extras and feeding them to your adapter. Double-check that the key names match exactly (they're case-sensitive!):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lst);

    // Initialize your list and adapter (adjust for ListView/RecyclerView)
    ArrayList<NotificationItem> notificationList = new ArrayList<>();
    RecyclerView recyclerView = findViewById(R.id.your_recycler_id);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    // Get data from intent
    String receivedTitle = getIntent().getStringExtra("NOTIF_TITLE");
    String receivedMessage = getIntent().getStringExtra("NOTIF_MESSAGE");

    // Add to list only if data isn't null
    if (receivedTitle != null && receivedMessage != null) {
        notificationList.add(new NotificationItem(receivedTitle, receivedMessage));
    } else {
        // Fallback for null cases
        notificationList.add(new NotificationItem("No Title", "No Message"));
    }

    // Attach adapter to your list
    RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, notificationList);
    recyclerView.setAdapter(adapter);
}

Note: If you're using a ListView instead of RecyclerView, swap out the RecyclerView code for a ListView and corresponding adapter.

3. Validate Your RecyclerViewAdapter Binding

Ensure your adapter is correctly mapping data to your list item layout. Typos in view IDs or model getters are a common culprit:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
    private Context context;
    private ArrayList<NotificationItem> items;

    public RecyclerViewAdapter(Context context, ArrayList<NotificationItem> items) {
        this.context = context;
        this.items = items;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_notif, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        NotificationItem currentItem = items.get(position);
        // Make sure these IDs match your item layout's TextView IDs
        holder.titleTv.setText(currentItem.getTitle());
        holder.messageTv.setText(currentItem.getMessage());
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView titleTv, messageTv;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            titleTv = itemView.findViewById(R.id.tv_notif_title);
            messageTv = itemView.findViewById(R.id.tv_notif_message);
        }
    }
}

Don't forget to confirm your NotificationItem model has proper getter methods for title and message.

4. Quick Additional Checks

  • Manifest Configuration: Ensure your FcmMessagingService is registered correctly in AndroidManifest.xml:
    <service
        android:name=".FcmMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    
  • Notification Channel: For Android 8.0+, create a notification channel in your MainActivity to ensure notifications show up:
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                "YOUR_CHANNEL_ID",
                "Notification Channel",
                NotificationManager.IMPORTANCE_HIGH
            );
            channel.setDescription("Firebase Notifications");
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }
    
  • Server Payload: Double-check your server's JSON payload uses the same key names as your client (e.g., "title" instead of "Title").

内容的提问来源于stack exchange,提问作者Doblist Doblist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:36:13