最近,我一直在开发一个博客应用程序上的项目,其中我使用Firebase保存并检索所有帖子,我正在Android Studio中开发我的应用程序。
问题是,每当发布新帖子时,最新的帖子都会发布到帖子列表的底部;因此,用户必须一直到帖子活动才能看到新帖子。我该怎么扭转呢?我希望最新的帖子出现在顶部。我想写什么代码?
这是我的代码:
public class AlertsActivity extends AppCompatActivity{
private Toolbar toolbar;
private RecyclerView mbloglist;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.alert);
toolbar= (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase= FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabase.keepSynced(true);
mbloglist= (RecyclerView) findViewById(R.id.alert_list);
mbloglist.setHasFixedSize(true);
mbloglist.setLayoutManager(new LinearLayoutManager(this));
}
@Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Blog,BlogViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.blog_row,
BlogViewHolder.class,mDatabase
){
@Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesp(model.getDesp());
}
};
mbloglist.setAdapter(firebaseRecyclerAdapter);
}
public static 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.blog_title);
post_title.setText(title);
}
public void setDesp(String desp){
TextView post_desp= (TextView) mview.findViewById(R.id.blog_desp);
post_desp.setText(desp);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_alerts,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_add){
Intent intent=new Intent(AlertsActivity.this,PostActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:0)
请为每个帖子添加一个字段,时间戳。从Firebase数据库中获取所有帖子时,请使用orderByChild(“timestamp”)按日期对帖子进行排序。