添加或删除数据后,Room数据库无法正确更新ID

时间:2019-05-21 06:15:24

标签: java android mvvm android-sqlite android-jetpack

我正在构建一个允许用户存储用户名和密码的应用程序。用户单击FAB,AddEditEntry.java活动开始。用户输入用户名,输入或生成密码,输入提示并单击保存。新数据将显示在Mainactivity.java中的列表中。如果用户选择编辑条目,则他/她需要做的就是长按该项目,并且相同的AddEditEntry.java类将从字段中的先前数据开始。然后,用户可以更改该数据并单击保存以更新条目。操作栏上还有一个按钮可以删除所有条目,或者用户可以向左/向右滑动条目以将其从数据库中删除。

相反,会发生以下情况:

  • 用户能够成功添加新条目。
  • 长按时,AddEditEntry.java成功地用以前的数据填充字段
  • 用户删除条目时(无论是通过向左/向右滑动还是点击全部删除按钮),新条目都不会从ID值1开始。该条目从上一个条目的上次中断处开始。因此,如果我删除ID = 1的条目,则新条目的ID = 2。
  • 更糟糕的是,当我按下“保存”按钮以更新一个条目时,ID变为-1。发生这种情况时,该条目的值根本不存在,因为我正在使用每种状态下的Toast消息检查它们。因此,没有更新,并且条目保持不变。

该应用程序是使用MVVM体系结构构建的,因此我具有(实体,DAO,数据库,存储库,视图模型)类以及必需的适配器类。我将只发布相关代码,以免造成混乱。我可以为每个请求添加更多代码。

MainActivity.java:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        //Sends the existing entry for editing
        adapter.setOnItemLongClickListener(new RecyclerViewAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(Entries entries) {
                Intent intent = new Intent(MainActivity.this, AddEditEntry.class);

                intent.putExtra(AddEditEntry.EXTRA_USERNAME, entries.getUsername());
                intent.putExtra(AddEditEntry.EXTRA_HINT, entries.getHint());
                intent.putExtra(AddEditEntry.EXTRA_PASSWORD, entries.getPassword());
                intent.putExtra(AddEditEntry.EXTRA_ID, entries.getId());
                startActivityForResult(intent, EDIT_ENTRY_REQUEST);

                Toast.makeText(MainActivity.this, entries.getUsername(), Toast.LENGTH_SHORT).show();
                Toast.makeText(MainActivity.this, entries.getHint(), Toast.LENGTH_SHORT).show();
                Toast.makeText(MainActivity.this, entries.getPassword(), Toast.LENGTH_SHORT).show();
                Toast.makeText(MainActivity.this, String.valueOf(entries.getId()), Toast.LENGTH_SHORT).show();
            }
        });
    }
...
    //The onActivityResult retrieves the result when the user adds
    // or edits an entry by checking for the specific request code
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == ADD_ENTRY_REQUEST && resultCode == RESULT_OK){
            String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
            String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
            String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);

            Entries entry = new Entries(username, hint, password);
            viewModel.insert(entry);

            Toast.makeText(this, "Entry added!", Toast.LENGTH_SHORT).show();

        }else if(requestCode == EDIT_ENTRY_REQUEST && resultCode == RESULT_OK){
            int id = getIntent().getIntExtra(AddEditEntry.EXTRA_ID, -1);
            String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
            String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
            String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);

            if (id == -1){Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();}

            Entries entry = new Entries(username, hint, password);
            entry.setId(id);
            viewModel.update(entry);

            Toast.makeText(this, String.valueOf(id), Toast.LENGTH_SHORT).show();
            Toast.makeText(this, username, Toast.LENGTH_SHORT).show();
            Toast.makeText(this, password, Toast.LENGTH_SHORT).show();
            Toast.makeText(this, hint, Toast.LENGTH_SHORT).show();

            Toast.makeText(this, "Entry updated", Toast.LENGTH_SHORT).show();

        }else{Toast.makeText(this, "Entry not added!", Toast.LENGTH_SHORT).show();}
    }

AddEditEntry.java

public class AddEditEntry extends AppCompatActivity {

    public static final String EXTRA_USERNAME = "com.ozbek.cryptpass.EXTRA_USERNAME";
    public static final String EXTRA_HINT = "com.ozbek.cryptpass.EXTRA_HINT";
    public static final String EXTRA_PASSWORD = "com.ozbek.cryptpass.EXTRA_PASSWORD";
    public static final String EXTRA_ID = "com.ozbek.cryptpass.EXTRA_ID";
    public static final int EDIT_ENTRY_REQUEST = 3;

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...

        final Intent intent = getIntent();
        // If the ID was passed, gets the extras for editing
        if(intent.hasExtra(EXTRA_ID)){
            setTitle("Edit Entry");
            saveEntry.setText("Update Entry");
            usernameEditText.setText(getIntent().getStringExtra(EXTRA_USERNAME));
            passwordEditText.setText(getIntent().getStringExtra(EXTRA_PASSWORD));
            hintEditText.setText(getIntent().getStringExtra(EXTRA_HINT));
            int id = getIntent().getIntExtra(EXTRA_ID, -1);

            Toast.makeText(this, "Info Received!!!", Toast.LENGTH_SHORT).show();
            Toast.makeText(this, getIntent().getStringExtra(EXTRA_USERNAME), Toast.LENGTH_SHORT).show();
            Toast.makeText(this, getIntent().getStringExtra(EXTRA_PASSWORD), Toast.LENGTH_SHORT).show();
            Toast.makeText(this, getIntent().getStringExtra(EXTRA_HINT), Toast.LENGTH_SHORT).show();
            Toast.makeText(this, String.valueOf(id), Toast.LENGTH_SHORT).show();
        }

        else{setTitle("Add Entry");}

        generatePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {passwordEditText.setText(generatedPassword());}});

        saveEntry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent data = new Intent();
                data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString());
                data.putExtra(EXTRA_HINT, hintEditText.getText().toString());
                data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString());

                setResult(RESULT_OK, data);
                finish();
            }
        });
    }

    ...
}

EntryViewModel.java

public class EntryViewModel extends AndroidViewModel {
    private EntryRepository repository;
    private LiveData<List<Entries>> allEntries;


    public EntryViewModel(@NonNull Application application) {
        super(application);
        repository = new EntryRepository(application);
        allEntries = repository.getAllEntries();
    }

    public void insert(Entries entries){repository.insert(entries);}

    public void update(Entries entries){repository.update(entries);}

    public void delete(Entries entries){repository.delete(entries);}

    public void deleteAll(){repository.deleteAllEntries();}

    public LiveData<List<Entries>> getAllEntries() {return allEntries;}
}

Entries.java

@Entity(tableName = "entries_table")
public class Entries {
    @PrimaryKey(autoGenerate = true)
    private int id;

    private String username, hint, password;

    public Entries(String username, String hint, String password){
        this.username = username;
        this.hint = hint;
        this.password = password;
    }

    public Entries(){}

    public int getId() {return id;}

    public void setId(int id) {this.id = id;}

    public String getUsername() {return username;}

    public void setUsername(String username) {this.username = username;}

    public String getHint() {return hint;}

    public void setHint(String hint) {this.hint = hint;}

    public String getPassword() {return password;}

    public void setPassword(String password) {this.password = password;}
}

这里是full source code

2 个答案:

答案 0 :(得分:1)

只需添加这些修复程序即可。

onClick()中您的saveEntry的{​​{1}}(我假设是按钮)中,将其更改为:

AddEditEntry.java

然后在 saveEntry.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent data = new Intent(); data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString()); data.putExtra(EXTRA_HINT, hintEditText.getText().toString()); data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString()); //You were missing these 2 lines int id = getIntent().getIntExtra(EXTRA_ID, -1); if(id != -1){data.putExtra(EXTRA_ID, id);} setResult(RESULT_OK, data); finish(); } }); 内部的onActivityResult方法中,进行以下快速修复:

MainActivity.java

应该在这些之后工作。让我知道您是否有任何问题。

答案 1 :(得分:0)

  

当用户删除一个条目时(无论是通过向左/向右滑动还是点击全部删除按钮),新的条目都不会从ID值1开始。该条目从上一个条目的上次中断处开始。因此,如果我删除ID = 1的条目,则新条目的ID = 2。

这是自动生成的主键的默认行为。怎么了?

  

更糟糕的是,当我按保存按钮更新条目时,ID变为-1。发生这种情况时,该条目的值根本不存在,因为我正在使用每种状态下的Toast消息检查它们。因此没有更新,并且条目保持不变。

我没有阅读所有代码,但这看起来像是一个冲突问题。尝试为查询添加替换策略。

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Entries entries);

@Update(onConflict = OnConflictStrategy.REPLACE)
void update(Entries entries);