如何从FIREBASE检索数据到回收站视图

时间:2016-01-23 10:21:30

标签: android json firebase android-recyclerview

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


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.menu_recycler);
    recyclerView.setHasFixedSize(true);

    LinearLayoutManager linearLayout = new LinearLayoutManager(this);
    linearLayout.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(linearLayout);

    MenuHomeAdapter menuHomeAdapter = new MenuHomeAdapter(this, createList(7));

    recyclerView.setAdapter(menuHomeAdapter);

    //FireBase
    Firebase.setAndroidContext(this);
    // Get a reference to our posts
    Firebase ref = new Firebase("LINK");

    // Attach an listener to read the data at our posts reference
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                Menu post = postSnapshot.getValue(Menu.class);
                Toast.makeText(MenuHome.this, post.getSNo() + "-" + post.getDishName(), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            System.out.println("The read failed: " + firebaseError.getMessage());
        }
    });
}

如何在回收站视图中显示数据。我尝试了一些方法,但它不合适。吐司工作但所有其他选项都是错误的。我只想在回收站视图中显示来自firebase的数据。

3 个答案:

答案 0 :(得分:9)

正如helldawg评论的那样,您需要创建自己的适配器:

  • 收听来自Firebase的onDataChange来电
  • 保留Firebase数据的内部副本
  • 数据更改时通知RecyclerView
  • 在需要时创建视图持有者
  • 将Firebase数据中的数据绑定到视图

我能想到的最低限度是:

public static class MenuHomeAdapter extends RecyclerView.Adapter<MenuViewHolder> {
    ArrayList<Menu> items = new ArrayList<>();

    public MenuHomeAdapter(Firebase ref) {
        ref.addValueEventListener(new ValueEventListener() {
            public void onDataChange(DataSnapshot snapshot) {
                items.clear();
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    Menu menu = postSnapshot.getValue(Menu.class);
                    items.add(menu);
                }
                notifyDataSetChanged();
            }

            public void onCancelled(FirebaseError firebaseError) {
                System.out.println("The read failed: " + firebaseError.getMessage());
            }
        });
    }

    public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
        return new MenuViewHolder(view);
    }

    public void onBindViewHolder(MenuViewHolder holder, int position) {
        Menu item = items.get(position);
        holder.getTitleView().setText(item.getTitle());
    }

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

要在上下文中查看,请在Activity34962254上查看this Github repo(以问题编号命名)。

你会注意到实现这一点并非易事。虽然这个实现工作,但它是非常次优的。例如:更改/添加/删除单个项目时,将重建整个列表。这是糟糕表现的秘诀。

除非您有特殊需求,否则您可能会更好using the FirebaseRecyclerAdapter from the FirebaseUI project。为了全面了解它提供的内容,我建议使用此codelab for building a chat app with FirebaseUI

答案 1 :(得分:4)

这里有一个非常好的教程

https://github.com/firebase/FirebaseUI-Android#using-firebaseui-to-populate-a-recyclerview

这将为您提供所需的功能,而且FirebaseUI可以为您提供很多帮助。

现在,如果你想包括数据绑定:

自定义ViewHolder

public class YourViewHolder extends RecyclerView.ViewHolder {

    public YourItemBinding binding;

    public YourViewHolder(View itemView) {
        super(itemView);

        binding = DataBindingUtil.bind(itemView);
    }

    public YourItemBinding getBinding() {
        return binding;
    }
}

<强> FirebaseRecyclerAdapter

mAdapter = new FirebaseRecyclerAdapter <YourFirebaseItem, YourViewHolder> (YourFirebaseItem.class, android.R.layout.two_line_list_item, YourViewHolder.class, mRef) {

    @Override
    public void populateViewHolder(YourViewHolder viewHolder, YourFirebaseItem item, int position) {

        YourItemBinding binding = viewHolder.getBinding();

        binding.setItem(item);

    }
};

recycler.setAdapter(mAdapter);

答案 2 :(得分:1)

为什么不简单地使用FirebaseRecyclerAdapter

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

RecyclerView messages = (RecyclerView) findViewById(R.id.messages);
messages.setLayoutManager(new LinearLayoutManager(this));

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();

mAdapter = new FirebaseRecyclerAdapter<Chat, ChatHolder>(
        Chat.class,
        R.layout.message,
        ChatHolder.class,
        ref) {
    @Override
    public void populateViewHolder(ChatHolder holder, Chat chat, int position) {
        holder.setName(chat.getName());
        holder.setMessage(chat.getMessage());
    }
};

messages.setAdapter(mAdapter);
}