删除数据库时刷新/重新加载片段

时间:2017-03-06 07:30:21

标签: android android-fragments

我有一个简单的app片段和活动托管RecyclerView,来自数据库的数据,我的适配器中有一个删除功能,内容从数据库中删除,但View没有刷新。对于提出的类似问题,我已经尝试了几个答案,但无法修复它们。请找到我的片段和适配器的代码片段。

片段代码:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_medication, container, false);
    medicationsArrayList = new ArrayList<>();
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
    String userId = sharedPreferences.getString(Preferences.USERID,null);
    if (userId != null) {
        databaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(userId).child("medications");
    }
    toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
    toolbar.setTitle(getString(R.string.medication));
    addMedButton = (FloatingActionButton) view.findViewById(R.id.addMedicationButton);
    recyclerView = (RecyclerView) view.findViewById(R.id.medications_recycler);
    recyclerView.setNestedScrollingEnabled(false);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(mLayoutManager);
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                Medication medication = snapshot.getValue(Medication.class);
                String medicationKey = snapshot.getKey();
                medication.setKey(medicationKey);
                medicationsArrayList.add(medication);
            }
            mAdapter = new MedicationsAdapter(getContext(), medicationsArrayList);
            recyclerView.setAdapter(mAdapter);
            registerForContextMenu(recyclerView);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

适配器:

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.medications_adapter, parent, false);
    return new ViewHolder(itemView);
}



@Override
public void onBindViewHolder(final ViewHolder holder, int position) {

    Medication medication = mMedicationList.get(position);
    holder.dateMed.setText(medication.getDateMed());
    holder.medicationName.setText(medication.getMedicationName());
    holder.dosage.setText(medication.getDosage() + " " + mContext.getString(R.string.dosageUnit));
    holder.initialTime.setText(medication.getInitialTime());
    holder.startDate.setText(medication.getStartDate());
    holder.endDate.setText(medication.getEndDate());
    holder.frequency.setText(medication.getFrequency());
    holder.medication_key.setText(medication.getKey());
    holder.reason.setText(medication.getReason());
}

@Override
public int getItemCount() {
    if (mMedicationList == null) {
        return 0;
    } else {
        return mMedicationList.size();
    }
}

class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
    TextView dateMed, medicationName, dosage, initialTime, startDate, endDate, frequency, reason, medication_key;


    ViewHolder(View v) {
        super(v);
        v.setOnCreateContextMenuListener(this);
        dateMed = (TextView) v.findViewById(R.id.dateMedAdd);
        medicationName = (TextView) v.findViewById(R.id.medicationName);
        dosage = (TextView) v.findViewById(R.id.dosage);
        initialTime = (TextView) v.findViewById(R.id.initialTime);
        startDate = (TextView) v.findViewById(R.id.startDate);
        endDate = (TextView) v.findViewById(R.id.endDate);
        frequency = (TextView) v.findViewById(R.id.frequency);
        reason = (TextView) v.findViewById(R.id.reason);
        medication_key = (TextView) v.findViewById(R.id.medication_key);

    }

    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Medications Options");
        MenuItem editMed = menu.add(0, v.getId(), 0, "Edit");//groupId, itemId, order, title
        MenuItem deleteMed = menu.add(0, v.getId(), 0, "Delete");
        editMed.setOnMenuItemClickListener(medicationsMenuClicked);
        deleteMed.setOnMenuItemClickListener(medicationsMenuClicked);
    }

    private void deleteVitalsByKey(String key) {
        DatabaseReference databaseReference;
        databaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("medications").child(key);
        databaseReference.removeValue();

    }

    private final MenuItem.OnMenuItemClickListener medicationsMenuClicked = new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            View v = item.getActionView();
            if (item.getTitle() == "Edit") {
                Toast.makeText(mContext, "Redirecting to edit screen", Toast.LENGTH_LONG).show();
                Intent editMedIntent = new Intent(mContext, MedicationActivity.class);
                editMedIntent.putExtra("medications_key", medication_key.getText());
                mContext.startActivity(editMedIntent);
                return true;
            } else if (item.getTitle() == "Delete") {
                Toast.makeText(mContext, "Deleting", Toast.LENGTH_LONG).show();
                deleteVitalsByKey(medication_key.getText().toString());
                return true;
            }
            return false;
        }
    };

想要刷新片段UI以反映删除的更改。请帮助我。

1 个答案:

答案 0 :(得分:0)

从recyclerview列表中删除项目后执行相同的操作。 那就是当你点击删除然后调用一个你首先删除一个项目的函数然后更新数据库然后取回所有数据然后清理你的回收者视图然后再添加它。

 DatabasePayShare db= new DatabasePayShare(getContext());
        folderDatas= db.GetAllFolder();
        FolderAdapter folderAdapter= new FolderAdapter(getActivity(), folderDatas);
        folListView.setAdapter(folderAdapter);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DatabasePayShare db= new DatabasePayShare(getContext());
                FolderData folderData= new FolderData(0,"Folder "+(folListView.getCount()+1), getDate());
                long rowId= db.AddNewFolderToLocalDatabase(folderData);

                db= new DatabasePayShare(getContext());
                final ArrayList<FolderData> folderDatas= db.GetAllFolder();
                FolderAdapter folderAdapter= new FolderAdapter(getActivity(), folderDatas);
                folListView.setAdapter(folderAdapter);

            }
        });

检查这段代码我有一个列表视图,其中包含一个图像和两个textview。点击它上面的项目我想再添加一个列表项。所以我在数据库中添加了元组。添加i再次称为数据库后再次填写列表。 我在listview中做过你可以在你的查看。