在插入Android的数据库之前,如何检查Room数据库中是否存在数据?

时间:2018-10-10 12:03:36

标签: java android android-room

在我的应用程序中,我想使用房间数据库显示离线数据。
我写了下面的代码,但是当单击按钮添加数据时,如果该数据存在于 Room数据库中,则会显示 ForceClose 错误!
在添加到数据库之前,如何在数据库中检查这些数据?

我的NewsOfflineDatum类:

@Entity(tableName = "newsList")
public class NewsOfflineDatum {
    @PrimaryKey
    private int id;

    @ColumnInfo(name = "newsTitle")
    private String title;

    @ColumnInfo(name = "newsImage")
    private String image;

    public int getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}

我的适配器类:

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.MyViewHolder> {

    private List<Today> model;
    private Context context;

    public NewsAdapter(List<Today> model) {
        this.model = model;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_news, parent, false);
        context = parent.getContext();

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        final Today todayModel = model.get(position);

        Glide.with(context)
                .load(AppConstant.IMAGE_URL + todayModel.getImage())
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(holder.rowNews_img);
        holder.rowNews_txt.setText(todayModel.getTitle());
        holder.rowNews_dl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NewsOfflineDatum offlineDatum = new NewsOfflineDatum();
                offlineDatum.setId(todayModel.getId());
                offlineDatum.setTitle(todayModel.getTitle());
                offlineDatum.setImage(todayModel.getImage());

                MainActivity.myAppDatabase.getMyDao().addNews(offlineDatum);

                Toast.makeText(context, "Saved :)", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return model.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.rowNews_img)
        ImageView rowNews_img;
        @BindView(R.id.rowNews_txt)
        TextView rowNews_txt;
        @BindView(R.id.rowNews_dl)
        ImageView rowNews_dl;

        public MyViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}

LogCat错误:

Process: com.example.mac8.mvplearnclicksite, PID: 7697
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: newsList.id (code 1555)
#################################################################
Error Code : 1555 (SQLITE_CONSTRAINT_PRIMARYKEY)
Caused By : Abort due to constraint violation.
    (UNIQUE constraint failed: newsList.id (code 1555))
#################################################################
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:865)
    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
    at android.arch.persistence.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:50)
    at android.arch.persistence.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.java:64)
    at com.example.mac8.mvplearnclicksite.Data.DataBase.MyDao_Impl.addNews(MyDao_Impl.java:49)
    at com.example.mac8.mvplearnclicksite.Home.NewsAdapter$1.onClick(NewsAdapter.java:59)
    at android.view.View.performClick(View.java:6261)
    at android.view.View$PerformClick.run(View.java:23752)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

显示此的错误:MainActivity.myAppDatabase.getMyDao().addNews(offlineDatum);

我该如何解决?

5 个答案:

答案 0 :(得分:2)

使用此注释更新查询:

@Insert(onConflict = OnConflictStrategy.REPLACE)

答案 1 :(得分:1)

这是检查表中是否存在数据的有效解决方案。

  • 房间数据库从不返回布尔值,以表明它是否存在于数据库表中

对于支票数据是否存在,您可以获取 int 值。

0 = data is not exist in your table

为此,您必须尝试以下代码

@Query("SELECT * FROM TableName WHERE userName = :userName")
int isDataExist(String userName);

使用以下代码调用此查询。

if (AppDatabase.getInstance(this).employeeDao().isDataExist(tvUserName.getText().toString()) == 0) {
 // data not exist.
 } else {
 // data already exist.
 }

答案 2 :(得分:1)

如果您只想检查记录是否存在,请使用此查询。

    @Query("SELECT EXISTS(SELECT * FROM TableName WHERE userId = :userId)")
    boolean isRecordExistsUserId(String userId);

这将简单地返回真或假。并基于布尔值,您可以执行流程的其余部分。

答案 3 :(得分:0)

您遇到约束冲突,正在尝试添加具有相同ID的实体。根据您的逻辑,是否要使用新实体进行更新,或者如果它不为空,则以这种方式保留。

答案 4 :(得分:0)

您有两种方法: 1-当您想将数据输入数据库时​​,无需输入ID,也可以使用此方法输入重复数据

2-

 @Insert(onConflict = OnConflictStrategy.REPLACE)
 void addNews(offlineDatum);

我希望使用它