Home > Blockchain >  Room Database Query - Delete User
Room Database Query - Delete User

Time:10-18

I have built an app that acts as a user and inventory database using the Room persistence library. Currently I am able to make queries to view/output users to a recycler view, but I need to be able to delete a user using their name as the query object. Currently I have the following.

Remove User Class

                String usrNam = edtTxtUsrNam2.getText().toString();

                // Get all users from database   log
                List<Users> users = LoginMenu.mainDatabase.dao().getUsers();
                Log.d(LoginMenu.TAG, "Searching for "   usrNam);
                boolean userFound = false;

                // Check for User from text entry
                for (Users usr : users) {
                    // User is successfully found
                    if (usr.getName().equals(usrNam)) {
                        userFound = true;
                        break;
                    }
                }if (!userFound) {

                    Toast.makeText(getBaseContext(), "User not found", 
                    Toast.LENGTH_SHORT).show();
                    Log.d(LoginMenu.TAG, " User "   usrNam   " Not found");
                    edtTxtUsrNam2.getText().clear();

                } else {
                    // Build Messagebox Confirmation
                    builder.setTitle("User "   usrNam   " found!");
                    builder.setMessage("Confirm user deletion?");

                    // Selecting yes in Alert
                    builder.setPositiveButton("Yes", (dialogInterface, i) -> {

                        // Delete User from database

                        Users activeUser = new Users();
                        activeUser.setName(usrNam);
                        LoginMenu.mainDatabase.dao().delUser(activeUser);
                        
                        // Toast message   Log
                        Toast.makeText(getApplicationContext(),"User "   usrNam  
                                " successfully deleted!",Toast.LENGTH_SHORT).show();
                        
                        Log.d(LoginMenu.TAG,"User "   usrNam   " Successfully deleted");
                        
                        edtTxtUsrNam2.getText().clear();
                        dialogInterface.dismiss();
                    });
                    // Selecting no in Alert
                    builder.setNegativeButton("No", (dialogInterface, i) -> dialogInterface.dismiss());
                    // Create Alert Dialog
                    AlertDialog alert = builder.create();
                    alert.show();


DAO

@androidx.room.Dao
public interface Dao {

    // Add Users to Database
    @Insert
    void AddUsers(Users usr);

    // Request all users from DB
    @Query("SELECT * FROM Users")
    List<Users> getUsers();

    // Delete user from DB
    @Delete
    void delUser (Users usr);

User Class


@Entity(tableName = "Users")
public class Users {

    // Set User Entries for Database
    @ColumnInfo (name = "ID")
    @PrimaryKey (autoGenerate = true)
    private int id;

    @ColumnInfo(name = "EmployeeId")
    private String  employeeId;

    @ColumnInfo(name = "Name")
    private String name;

    @ColumnInfo(name = "Password")
    private String password;

    @ColumnInfo(name = "DateOfBirth")
    private String dateOfBirth;

    @ColumnInfo(name = "ContactNumber")
    private String contactNumber;

    @ColumnInfo(name = "Address")
    private String address;

It detects the user no problem at all but does not delete the User object, I'm quite new to this and would appreciate any assistance as I am sure its something simple.

CodePudding user response:

That is because you are creating new user and it only has the "name" value.

    Users activeUser = new Users();
    activeUser.setName(usrNam); // This user is not equal what's in db.
    LoginMenu.mainDatabase.dao().delUser(activeUser);

Instead when you loop the users in your db if you found the user, fetch it from there like this:

      Users activeUser = new Users();
      for (Users usr : users) {
           // User is successfully found
           if (usr.getName().equals(usrNam)) {
               userFound = true;
               activeUser = usr; // now we got the exact item on db
               break;
           }
      }

Now your function will delete the correct user.

      //Users activeUser = new Users();
      //activeUser.setName(usrNam); //you don't need them anymore.
      LoginMenu.mainDatabase.dao().delUser(activeUser);

CodePudding user response:

I changed the Dao query to:


// Delete user from DB
    @Query("DELETE FROM Users WHERE name =:userId")
    abstract void deleteByUserId(String userId);

And the query itself under RemoveUsers class


// Delete User from database
LoginMenu.mainDatabase.dao().deleteByUserId(usrNam);

Query now works as intended

  • Related