在我的博客应用程序中,包含(标题,描述和图像(的帖子。无法从 Firebase 检索数据并使用回收器视图适配器显示数据。我无法确定问题所在。代码是:-
public class MainActivity extends AppCompatActivity {
private RecyclerView mBlogList;
private DatabaseReference mDatabase;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mBlogList = (RecyclerView)findViewById(R.id.blog_list);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(this));
}
@Override
protected void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Blog_Images");
FirebaseRecyclerOptions<Blog> options =
new FirebaseRecyclerOptions.Builder<Blog>()
.setQuery(query, Blog.class)
.build();
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>
(options) {
@Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_row,parent,false);
return new BlogViewHolder(view);
}
@Override
protected void onBindViewHolder(@NonNull BlogViewHolder holder, int position, @NonNull Blog model) {
holder.setTitle(model.getTitle());
holder.setDescription(model.getDescription());
holder.setImage(getApplicationContext(),model.getImage());
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
public class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title)
{
TextView post_title = (TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDescription(String desc)
{
TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setImage(Context ctx, String image)
{
ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
//Picasso.with(ctx).load(image).into(post_image);
Glide.with(MainActivity.this).load(image).into(post_image);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_add)
{
startActivity(new Intent(MainActivity.this,PostActivity.class));
}
return super.onOptionsItemSelected(item);
}
}
我的MainActivity
只是空白的。我不知道问题出在哪里。我尝试了ValueEventListener
,addValueEventListener
但没有结果,实际上它在 LOGCAT 中说:
找不到布局,跳过此布局
在聊天中与 OP 交谈后,他导出了 JSON,父节点的名称为 Blog
而不是 Blog_images
,所以我告诉他更改这个:
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Blog_Images");
进入这个:
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Blog");