如何在Android中编辑和删除Firebase数据库中的信息?

qyzbxkaa  于 2023-04-27  发布在  Android
关注(0)|答案(1)|浏览(112)

我的问题是,我不能删除和编辑的数据,是在实时数据库,访问它,我有唯一的关键,uid和我需要改变的日期,时间标题的值(例如数据库中的截图)。

public class EditActivity extends AppCompatActivity implements View.OnClickListener {
    EditText aTime, aDate, aTitle;
    Button btnUpdate, btnDelete;
    DatabaseReference reminderref;
    String key;

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

        aTime = findViewById(R.id.editTime);
        aDate = findViewById(R.id.editDate);
        aTitle = findViewById(R.id.editTitle);
        btnUpdate = findViewById(R.id.editButton);
        btnDelete = findViewById(R.id.deleteButton);
        reminderref = FirebaseDatabase.getInstance().getReference().child("Reminder");

        // Retrieve the data to be edited from the Firebase Realtime Database
        key = getIntent().getStringExtra("key");
        reminderref.child(key).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()) {
                    Reminder reminder = snapshot.getValue(Reminder.class);
                    if (reminder != null) {
                        aTitle.setText(reminder.getTitle());
                        aDate.setText(reminder.getDate());
                        aTime.setText(reminder.getTime());
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // Handle database error
            }
        });

        btnUpdate.setOnClickListener(this);
        btnDelete.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.editButton:
                updateReminder();
                break;
            case R.id.deleteButton:
                deleteReminder();
                break;
        }
    }

    private void updateReminder() {
        String title = aTitle.getText().toString();
        String date = aDate.getText().toString();
        String time = aTime.getText().toString();

        Reminder reminder = new Reminder();
        reminder.setTitle(title);
        reminder.setDate(date);
        reminder.setTime(time);
        reminder.setUid(FirebaseAuth.getInstance().getCurrentUser().getUid());

        reminderref.child(key).setValue(reminder)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(EditActivity.this, "Reminder updated successfully", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(EditActivity.this, "Failed to update reminder", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void deleteReminder() {
        reminderref.child(key).removeValue()
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(EditActivity.this, "Reminder deleted successfully", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(EditActivity.this, "Failed to delete reminder", Toast.LENGTH_SHORT).show();
                    }
                });
    }
}

我还将包括将提醒保存到数据库的活动,希望它有所帮助。

public class SaveActivity extends AppCompatActivity implements View.OnClickListener {
    FirebaseAuth firebaseAuth;
    Button btnadd;
    SharedPreferences sp;
    EditText aTime,aDate,aTitle;
    FirebaseDatabase firebaseDatabase;
    DatabaseReference reminderref;
    StorageReference storageReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_activity);
        firebaseAuth = FirebaseAuth.getInstance();
        firebaseDatabase = FirebaseDatabase.getInstance();
        aTime = (EditText) findViewById(R.id.aTime);
        aDate = (EditText) findViewById(R.id.aDate);
        aTitle = (EditText) findViewById(R.id.aTitle);
        btnadd = (Button) findViewById(R.id.btnadd);
        reminderref = FirebaseDatabase.getInstance().getReference();

        aDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDatePickerDialog();
            }
        });

        aTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimePickerDialog();
            }
        });
        btnadd.setOnClickListener(this);

        FirebaseUser firebaseUser= firebaseAuth.getCurrentUser();
        firebaseDatabase = FirebaseDatabase.getInstance();}

    @Override
    public void onClick(View view) {
        if(btnadd == view) {
            writeNewReminder();
            Intent intent = new Intent(this, MainPageActivity.class);
            startActivity(intent);
        }
    }

    private void showDatePickerDialog() {
        // Get the current date
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        // Create a new DatePickerDialog and show it
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                // Update the EditText with the selected date
                aDate.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
            }
        }, year, month, day);
        datePickerDialog.show();
    }

    private void showTimePickerDialog() {
        // Get the current time
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        // Create a new TimePickerDialog and show it
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                // Update the EditText with the selected time
                String time = String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute);
                aTime.setText(time);
            }
        }, hour, minute, true);
        timePickerDialog.show();
    }
    private void writeNewReminder() {
        String uid = firebaseAuth.getUid();
        String title = aTitle.getText().toString();
        String date = aDate.getText().toString();
        String time = aTime.getText().toString();
        String key = reminderref.child(uid).push().getKey();

        Reminder rmd = new Reminder();
        rmd.setDate(date);
        rmd.setTime(time);
        rmd.setTitle(title);
        rmd.setUid(uid);
        rmd.key = key;

        reminderref.child("Reminder").child(uid).child(key).setValue(rmd)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(SaveActivity.this, "Reminder added successfully", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(SaveActivity.this, "Failed to add reminder", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.mmadd) {
            Intent intent = new Intent(this, SaveActivity.class);
            startActivity(intent);
        }
        if (id == R.id.mmreturn){
            Intent intent = new Intent(this, MainPageActivity.class);
            startActivity(intent);
        }[enter image description here](https://i.stack.imgur.com/Bu8tr.png)
        if (id == R.id.mmatapp){
            Intent intent = new Intent(this, MainFragment.class);
            startActivity(intent);
        }
        if (id == R.id.mmexit){
            finishAffinity();
        }
        return super.onOptionsItemSelected(item);
    }
}

并且,通过按下提醒应该访问被按下的特定提醒并编辑/删除它的主页面:

public class MainPageActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;
    private DatabaseReference databaseRef;
    private ArrayList<Reminder> remindersList;
    private ReminderAdapter reminderAdapter;
    private ListView mrlv;

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

        mAuth = FirebaseAuth.getInstance();
        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
        databaseRef = firebaseDatabase.getReference("Reminder").child(uid);

        remindersList = new ArrayList<>();
        reminderAdapter = new ReminderAdapter(getApplicationContext(), R.layout.templet_example, remindersList);
        mrlv = findViewById(R.id.mrv);
        mrlv.setAdapter(reminderAdapter);

        databaseRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                remindersList.clear();
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                    Reminder reminder = postSnapshot.getValue(Reminder.class);
                    remindersList.add(reminder);
                }
                reminderAdapter.notifyDataSetChanged();
            }

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

        mrlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Reminder reminder = remindersList.get(position);
                Intent intent = new Intent(MainPageActivity.this, EditActivity.class);
                intent.putExtra("key", reminder.key);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_top, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.mmadd) {
            Intent intent = new Intent(this, SaveActivity.class);
            startActivity(intent);
        }
        if (id == R.id.mmreturn){
            Intent intent = new Intent(this, MainPageActivity.class);
            startActivity(intent);
        }
        if (id == R.id.mmatapp){
            Intent intent = new Intent(this, MainFragment.class);
            startActivity(intent);
        }
        if (id == R.id.mmexit){
            finishAffinity();
        }
        return super.onOptionsItemSelected(item);
    }
}

kmb7vmvb

kmb7vmvb1#

创建新提醒时,可将其写入:

reminderref.child("Reminder").child(uid).child(key).setValue(rmd)

因此,数据库中的提醒路径是/Reminder/$uid/$key
这意味着要删除提醒,您还需要从该特定路径中删除它。然而,您删除提醒的代码是:

reminderref.child(key).removeValue()

因此,这将尝试只删除路径/$key上的数据,这与您上面写的数据不同。
要删除提醒,构造完全相同的路径并在其上调用removeValue

reminderref.child("Reminder").child(uid).child(key).removeValue()

相关问题