简体   繁体   中英

RecyclerView is not stable in retrieving data from firebase to fragment

I have an app that uses firebase as a backend and displays the data in a RecyclerView what happens is that when I save the data to firebase it doesn't display the data in a proper way in the recyclerview some data is empty but when I rotate the screen all the data is displayed this video display and explain my problem

This is my fragment class

public class AddNewItemFragment extends Fragment {
public AddNewItemFragment() {

}
RecyclerView re;
FirebaseRecyclerAdapter<Note1, NoteHolder> adapter;
ProgressDialog pd;
String userid = "";
EditText textViewItemName;
EditText textViewItemPcs;
EditText textViewItemPssalePrice;
EditText textViewBoxCost;
DatabaseReference itemsDatabase;
FloatingActionButton fab;
Button itemSaveBtn;
private static final String KEY_ITEMNAME = "itemName";
private static final String KEY_ITEMSPCS = "itemPcs";
private static final String KEY_PSSALEPRICE = "itemPsSalePrice";
private static final String KEY_BOXCOST = "itemBoxCost";
private static final String KEY_ItemCat = "itemCat";
public View view;
String tabText;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.add_new_item_activity, container, false);
    //  if (getArguments() != null) {
    //      tabText = getArguments().getString("itemCat");
    //  } else {
    //      tabText = "CIGARETTE";
    //  }
    textViewItemName = view.findViewById(R.id.edittextItemsName);
    textViewItemPcs = view.findViewById(R.id.edittextItemsPcs);
    textViewItemPssalePrice = view.findViewById(R.id.edittextItemsPsSalePrice);
    textViewBoxCost = view.findViewById(R.id.edittextItemsBoxCost);

    re = view.findViewById(R.id.itemsListView);
    re.setLayoutManager(new LinearLayoutManager(getContext()));

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    userid = user.getUid();
    itemsDatabase = FirebaseDatabase.getInstance().getReference().child("users").child(userid).child("items");
    fab = view.findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v) {
            saveNote();
        }
    });
    return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}
@Override
public void onStart() {
    super.onStart();
    FirebaseRecyclerOptions<Note1> options =
            new FirebaseRecyclerOptions.Builder<Note1>()
                    .setQuery(itemsDatabase, Note1.class)
                    .build();
    adapter = new FirebaseRecyclerAdapter<Note1, NoteHolder>(options) {
                @Override
                protected void onBindViewHolder(@NonNull final NoteHolder holder, final int position, @NonNull final Note1 model) {
                    String ItemsID = getRef(position).getKey();
                    if (ItemsID != null) {
                        itemsDatabase.child(ItemsID).addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                if (dataSnapshot.exists()) {
                                    String itemName = (dataSnapshot.child("itemName").getValue()).toString();
                                    String itemPcs = (dataSnapshot.child("itemPcs").getValue()).toString();
                                    String itemPsSalePrice = (dataSnapshot.child("itemPsSalePrice").getValue()).toString();
                                    String boxCost = (dataSnapshot.child("itemBoxCost").getValue()).toString();
                                    holder.textViewItemName.setText(itemName);
                                    holder.textViewItemPcs.setText(itemPcs);
                                    holder.textViewItemPssalePrice.setText(itemPsSalePrice);
                                    holder.textViewBoxCost.setText(boxCost);
                                }
                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {
                            }
                        });
                    }
                }

                @NonNull
                @Override
                public NoteHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.add_item_design_adapter, parent, false);
                    return new NoteHolder(v);
                }
            };
    re.setAdapter(adapter);
    adapter.startListening();
}


private void setProgressStatus() {
    pd = new ProgressDialog(getActivity());

    // Set progress dialog style spinner
    pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);

    // Set the progress dialog title and message
    pd.setTitle("Please Wait Feras!!!!!.");
    pd.setMessage("Loading.........");

    // Set the progress dialog background color
    Objects.requireNonNull(pd.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.WHITE));

    pd.setCancelable(false);

    // Finally, show the progress dialog
    pd.show();


}

private void saveNote() {
    itemsDatabase = FirebaseDatabase.getInstance().getReference();
    String itemName = textViewItemName.getText().toString();
    String itemPcs = textViewItemPcs.getText().toString();
    String itemPsSalePrice = textViewItemPssalePrice.getText().toString();
    String itemBoxCost = textViewBoxCost.getText().toString();


    if (itemName.trim().isEmpty() || itemPcs.trim().isEmpty() ||
            itemPsSalePrice.trim().isEmpty() || itemBoxCost.trim().isEmpty()) {
        Toast.makeText(getActivity(), "Please enter all information", Toast.LENGTH_SHORT).show();
        return;
    }

    Map<String, Object> note = new HashMap<>();
    note.put(KEY_ITEMNAME, itemName);
    note.put(KEY_ITEMSPCS, itemPcs);
    note.put(KEY_PSSALEPRICE, itemPsSalePrice);
    note.put(KEY_BOXCOST, itemBoxCost);

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user != null) {
        userid = user.getUid();
    }
    String key = itemsDatabase.push().getKey();
    itemsDatabase.child("users").child(userid).child("items").child(key).setValue(note);

}

public static class NoteHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    private OnItemClickListener mListener;
    TextView textViewItemName;
    TextView textViewItemPcs;
    TextView textViewItemPssalePrice;
    TextView textViewBoxCost;


    NoteHolder(View itemView) {
        super(itemView);
        textViewItemName = itemView.findViewById(R.id.itemName);
        textViewItemPcs = itemView.findViewById(R.id.itemPcs);
        textViewItemPssalePrice = itemView.findViewById(R.id.itemPs);
        textViewBoxCost = itemView.findViewById(R.id.itemBoxCost);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (mListener != null) {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                mListener.onItemClick(position);
            }
        }
    }

    public interface OnItemClickListener {
        void onItemClick(int position);

        void onShowItemClick(int position);

        void onDeleteItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }
}

I guess your code is trying to read the data before it is written. This is because you are using push() to create a key and then write the data. But the ValueEventListener gets triggered when you create the key. But there is no data.And when you rotate the device, the code is ran again. But this time the write operation is complete. Try using OnSuccessListener to check for write completion and then refresh the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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