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

Android日记应用RecyclerView报错:No adapter attached; skipping layout

解决建议

1. 提前初始化Adapter,消除"No adapter attached"错误

界面渲染时RecyclerView必须绑定Adapter,否则会触发该警告。在onCreate中直接用空列表初始化并设置Adapter:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ... 原有代码保留
    journalList = new ArrayList<>();
    recyclerView = findViewById(R.id.recycleView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    // 新增:提前绑定空列表Adapter
    journalRecyclerAdapter = new JournalRecyclerAdapter(JournalListActivity.this, journalList);
    recyclerView.setAdapter(journalRecyclerAdapter);
}

2. 清空列表再加载,避免重复数据

每次进入页面重新拉取数据时,先清空原有列表,防止旧数据重复添加:

@Override
protected void onStart() {
    super.onStart();
    journalList.clear(); // 清空旧数据
    collectionReference.whereEqualTo("userId", JournalApi.getInstance().getUserId())
            .get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                    noJournalEntry.setVisibility(View.GONE);
                    if (!queryDocumentSnapshots.isEmpty()) {
                        for (QueryDocumentSnapshot journals : queryDocumentSnapshots) {
                            Journal journal = journals.toObject(Journal.class);
                            journalList.add(journal);
                        }
                        // 仅通知数据变化,无需重新创建Adapter
                        journalRecyclerAdapter.notifyDataSetChanged();
                    } else {
                        noJournalEntry.setVisibility(View.VISIBLE);
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    // 添加错误日志方便排查
                    Log.e("JournalList", "加载失败: " + e.getMessage());
                }
            });
}

3. 移除finish(),保留页面栈状态

当前点击添加按钮后调用finish()会销毁当前页面,导致添加后需重新创建。移除该方法,让添加完成后回到原页面再刷新数据:

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId() == R.id.action_add) {
        if (user != null && firebaseAuth != null) {
            startActivity(new Intent(JournalListActivity.this, PostJournalActivity.class));
            // 移除finish()
            // finish();
        }
    } else if (item.getItemId() == R.id.action_signout) {
        if (user != null && firebaseAuth != null) {
            firebaseAuth.signOut();
            startActivity(new Intent(JournalListActivity.this, MainActivity.class));
            finish();
        }
    }
    return super.onOptionsItemSelected(item);
}

4. 优化添加后的实时刷新(可选)

用startActivityForResult监听添加操作结果,完成后主动刷新数据:

在JournalListActivity中启动添加页面:

// 替换原action_add的启动代码
startActivityForResult(new Intent(JournalListActivity.this, PostJournalActivity.class), 100);

重写结果回调方法:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 100 && resultCode == RESULT_OK) {
        // 添加成功,重新加载数据
        loadJournalData();
    }
}

// 抽离加载数据逻辑为单独方法,方便复用
private void loadJournalData() {
    journalList.clear();
    collectionReference.whereEqualTo("userId", JournalApi.getInstance().getUserId())
            .get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                    noJournalEntry.setVisibility(View.GONE);
                    if (!queryDocumentSnapshots.isEmpty()) {
                        for (QueryDocumentSnapshot journals : queryDocumentSnapshots) {
                            Journal journal = journals.toObject(Journal.class);
                            journalList.add(journal);
                        }
                        journalRecyclerAdapter.notifyDataSetChanged();
                    } else {
                        noJournalEntry.setVisibility(View.VISIBLE);
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.e("JournalList", "加载失败: " + e.getMessage());
                }
            });
}

在PostJournalActivity添加完成后设置结果:

// 添加日记成功后调用
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();

5. 添加用户状态监听,处理登录/退出逻辑

确保用户状态变化时自动跳转:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ... 原有代码保留
    authStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            user = firebaseAuth.getCurrentUser();
            if (user == null) {
                startActivity(new Intent(JournalListActivity.this, MainActivity.class));
                finish();
            }
        }
    };
}

@Override
protected void onResume() {
    super.onResume();
    firebaseAuth.addAuthStateListener(authStateListener);
}

@Override
protected void onPause() {
    super.onPause();
    if (authStateListener != null) {
        firebaseAuth.removeAuthStateListener(authStateListener);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:12:05