简体   繁体   English

Firebase UI 3.0.0:检索数据以回收视图

[英]Firebase UI 3.0.0: Retrieve data to recycle view

Can anyone help me to retrieve data from the node "foods" and put it in the RecyclerView . 谁能帮助我从“食物”节点中检索数据并将其放入RecyclerView These are the file I've been working on but it turns out to be an empty list. 这些是我一直在处理的文件,但事实证明它是一个空列表。 I have viewed a tutorial on Internet but most of them were with an older version of Firebase. 我已经查看了Internet上的教程,但是其中大多数都是使用较旧版本的Firebase的。 Recently, Firebase UI has been updated and the data binding process has changed to their new FirebaseRecyclerAdapter structure 最近,Firebase UI已更新,并且数据绑定过程已更改为其新的FirebaseRecyclerAdapter结构

This is my database structure: 这是我的数据库结构:

"foods" : {
"AntipastoSalad" : {
  "duration" : "30",
  "img" : "https://firebasestorage.googleapis.com/v0/b/mealplanner-ec8ca.appspot.com/o/res%2Fsalad.jpg?alt=media&token=257d4392-8a1f-4fb7-84b5-b63abb4643f4",
  "name" : "Antipasto salad",
  "type" : "Salad"
},

This is my activity: 这是我的活动:

    private RecyclerView mRecycleView;
    private Query query;
    private FirebaseRecyclerOptions<Meal> options;
    private DatabaseReference mDatabase;

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

        mDatabase = FirebaseDatabase.getInstance().getReference().child("foods");

        //Recycle View
        mRecycleView = (RecyclerView) findViewById(R.id.meal_items);
        mRecycleView.setHasFixedSize(true);
        mRecycleView.setLayoutManager(new LinearLayoutManager(this));
    }


    @Override
    protected void onStart() {
        super.onStart();

        query = FirebaseDatabase.getInstance().getReferenceFromUrl("https://mealplanner-ec8ca.firebaseio.com/foods/AntipastoSalad");

        options = new FirebaseRecyclerOptions.Builder<Meal>()
                .setQuery(query, Meal.class)
                .build();

        FirebaseRecyclerAdapter<Meal, FoodListRowActivity.MealRowHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Meal, FoodListRowActivity.MealRowHolder>(
                options) {
            @Override
            public FoodListRowActivity.MealRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_row, parent, false);
                return new FoodListRowActivity.MealRowHolder(v);
            }

            @Override
            protected void onBindViewHolder(FoodListRowActivity.MealRowHolder holder, int position, Meal current) {
                holder.setTitle(current.getName());
                String duration = current.getDuration() + "min";
                holder.setDuration(duration);
            }
        };

        //Populate Item into Adapter
        mRecycleView.setAdapter(firebaseRecyclerAdapter);

        mRecycleView.addOnItemTouchListener(new RecycleViewItemClickListener(this, mRecycleView, new RecycleViewItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent viewMeal = new Intent(FoodListRowActivity.this, CookingInstructionActivity.class);
                startActivity(viewMeal);
            }

            @Override
            public void onLongItemClick(View view, int position) {
                //TODO: DELETE
            }
        }));
    }

    public static class MealRowHolder extends RecyclerView.ViewHolder {

        View mView;

        public MealRowHolder(View itemView) {
            super(itemView);
            mView = itemView;

        }

        public void setTitle(String title) {
            TextView foodTitle = (TextView) mView.findViewById(R.id.list_item_foodList_name);
            foodTitle.setText(title);
        }


        public void setDuration(String title) {
            TextView foodDuration = (TextView) mView.findViewById(R.id.list_item_foodList_calories);
            foodDuration.setText(title);
        }
    }
}

and class structure: 和类结构:

public class Meal{

private String img;
private String duration;
private String name;
private String instruction;

public Meal(){

}

public Meal (String img, String duration, String name, String instruction){
    this.img = img;
    this.name = name;
    this.duration = duration;
    this.instruction = instruction;
}

public void update(String duration, String name, String instruction)
{
    this.name = name;
    this.duration = duration;
    this.instruction = instruction;
}
public String getName(){
    return name;
}

public String getDuration() {
    return duration;
}

public String getInstruction() {
    return instruction;
}

public String getImg(){return img;}

The query specified in the setQuery() method should be a reference to the root of the list you want to show in the RecyclerView , so like this: setQuery()方法中指定的query应该是要在RecyclerView显示的列表根目录的引用,如下所示:

query = FirebaseDatabase.getInstance().getReference().child("foods");

You also need to call startListening() on the adapter to instruct it to start retrieving data from the database. 您还需要在适配器上调用startListening()来指示适配器开始从数据库中检索数据。

From the FirebaseRecyclerAdapter lifecycle documentation : FirebaseRecyclerAdapter生命周期文档中

The FirebaseRecyclerAdapter uses an event listener to monitor changes to the Firebase query. FirebaseRecyclerAdapter使用事件侦听器监视对Firebase查询的更改。 To begin listening for data, call the startListening() method. 要开始侦听数据,请调用startListening()方法。 You may want to call this in your onStart() method. 您可能要在onStart()方法中调用它。 Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail. 在调用startListening()之前,请确保已完成读取数据所需的所有身份验证,否则查询将失败。

 @Override protected void onStart() { super.onStart(); adapter.startListening(); } 

Similarly, the stopListening() call removes the event listener and all data in the adapter. 同样, stopListening()调用将删除事件侦听器和适配器中的所有数据。 Call this method when the containing Activity or Fragment stops: 当包含的ActivityFragment停止时调用此方法:

 @Override protected void onStop() { super.onStop(); adapter.stopListening(); } 

This is how I'm retrieving my data in recyclerview using Firebase UI: 这是我使用Firebase UI在recyclerview中检索数据的方式:

 private FirebaseRecyclerAdapter<TaskPOJO, TaskViewHolder> adapter;
 private void loadTasks() {


        database = FirebaseDatabase.getInstance();
        tasks = database.getReference("Tasks");
        adapter = new FirebaseRecyclerAdapter<TaskPOJO, TaskViewHolder>(TaskPOJO.class, R.layout.task_item, TaskViewHolder.class, tasks) {
            @Override
            protected void populateViewHolder(TaskViewHolder viewHolder, final TaskPOJO model, int position) {


                Log.wtf("valueTEst", "populateViewHolder: "+model.toString() );
                Log.wtf("TEstScript1", "populateViewHolder: "+model.getTitle() );
                viewHolder.title.setText(model.getTitle());
                viewHolder.desc.setText(model.getDescripttion()+"\n");
                viewHolder.remaining.setText(model.getRemaining()+"/"+model.getPoint());
                viewHolder.points.setText("Points "+model.getRemaining());
                Glide.with(viewHolder.title.getContext())
                        .load(model.getImage())
                        .into(viewHolder.image);


                viewHolder.setClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(View view, int position, boolean isLongClick) {
                        Toast.makeText(getActivity(), "" /*+ model.getTitle()*/, Toast.LENGTH_SHORT).show();

                        Intent TaskPOJODetail = new Intent(getActivity(), Main.class);
                        TaskPOJODetail.putExtra("value","detail");
                        TaskPOJODetail.putExtra("taskId",adapter.getRef(position).getKey());
                        startActivity(TaskPOJODetail);
                    }
                });
            }
        };
        progressBar.setVisibility(View.GONE);
        recyclerViewTasks.setAdapter(adapter);
    }

this is my firebase structure : 这是我的firebase结构:

Firebase中的结构

hope this will help you. 希望这会帮助你。

Please override getItemCount() method of FirebaseRecyclerAdapter . 请重写FirebaseRecyclerAdapter getItemCount()方法。

@Override
    public int getItemCount() {
        return 1;
    }

Reference. 参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM