简体   繁体   中英

How can I check whether data exist in Room database before inserting into database on Android?

In my application I want to use Room Database to show offline data.
I wrote below code, but when clicked on button to add in data, if this data exist in the Room database it shows ForceClose error!
How can I check for this data in the database, before adding to the database?

My NewsOfflineDatum class :

@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;
    }
}

My adapter class :

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 error :

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)

Shows me error for this line : MainActivity.myAppDatabase.getMyDao().addNews(offlineDatum);

How can I fix this?

Here is working solution for check data exist or not in your table.

  • Room Database never returns a boolean for whether it exists or not on your database table

For check data exists or not you can get int value.

0 = data is not exist in your table

for do this you have to try below code

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

call this query using below code.

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

使用此注释更新您的查询:

@Insert(onConflict = OnConflictStrategy.REPLACE)

use this query if you want to simply check whether the record exists or not.

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

this will simply return true or false. and based on boolean you can execute your rest of the flow.

you have two way: 1- When you want to data into database You don't need to enter an ID ,you can also enter duplicate data with this method

2-

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

I hope use it

You have a constraint violation, you're trying to add entity with the same id. Depends on your logic do you want to update with the new entity or if it is not empty leave it that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM