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

如何为不同壁纸匹配对应Firestore数据ID并展示正确信息

解决Android壁纸跳转后Firestore数据不匹配问题

问题根源很明确:跳转时未传递对应壁纸的Firestore文档ID,且InfoActivity中查询了整个集合,循环覆盖TextView导致最终仅显示最后一条数据。按以下两步修改即可解决:

1. 壁纸列表点击时传递文档ID

假设你使用RecyclerView展示壁纸列表,在Adapter的onBindViewHolder中处理Item点击事件,传递对应壁纸的文档ID:

@Override
public void onBindViewHolder(WallpaperViewHolder holder, int position) {
    WallpaperModel wallpaper = wallpaperList.get(position);
    // 此处完成壁纸图片、标题等UI绑定逻辑

    holder.itemView.setOnClickListener(v -> {
        Intent intent = new Intent(v.getContext(), InfoActivity.class);
        // 传递当前壁纸对应的Firestore文档ID
        intent.putExtra("WALLPAPER_DOC_ID", wallpaper.getDocumentId());
        v.getContext().startActivity(intent);
    });
}

同时,需要在WallpaperModel中添加documentId字段及对应的get/set方法,并在查询壁纸列表时保存文档ID:

// 查询wallpaper集合获取列表
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("wallpaper")
  .get()
  .addOnSuccessListener(querySnapshot -> {
      List<WallpaperModel> wallpaperList = new ArrayList<>();
      for (DocumentSnapshot doc : querySnapshot) {
          WallpaperModel model = doc.toObject(WallpaperModel.class);
          // 将文档ID存入模型
          model.setDocumentId(doc.getId());
          wallpaperList.add(model);
      }
      // 更新RecyclerView Adapter数据
      yourAdapter.updateList(wallpaperList);
  });

2. InfoActivity根据文档ID查询对应数据

删除原有的全集合查询逻辑,改为根据传递的ID查询单个文档:

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

    // 获取跳转时传递的文档ID
    String docId = getIntent().getStringExtra("WALLPAPER_DOC_ID");
    if (docId == null || docId.isEmpty()) {
        Toast.makeText(this, "无法获取壁纸信息", Toast.LENGTH_SHORT).show();
        finish();
        return;
    }

    // 查询指定ID的文档
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    db.collection("wallpaper").document(docId)
      .get()
      .addOnSuccessListener(docSnapshot -> {
          if (docSnapshot.exists()) {
              // 读取对应字段
              String name = docSnapshot.getString("name");
              String secretariat = docSnapshot.getString("secretariat");

              // 更新UI显示
              TextView nameTv = findViewById(R.id.tv_name);
              TextView secretariatTv = findViewById(R.id.tv_secretariat);
              nameTv.setText(name);
              secretariatTv.setText(secretariat);
          } else {
              Toast.makeText(this, "未找到对应壁纸信息", Toast.LENGTH_SHORT).show();
          }
      })
      .addOnFailureListener(e -> {
          Toast.makeText(this, "加载失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
      });
}

修改完成后,点击不同壁纸会传递对应的文档ID,InfoActivity仅查询该ID对应的文档,即可显示正确的壁纸信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:31:12