user9358862
user9358862

Reputation:

Non-Duplicating Entries in Room Database from Network Call

I am getting json data from an api call and persisting it in room db. The data saves successfully and I'm able to show it in my recyclerview correctly.

The problem occurs when I re-open the app. As the data is from a network call, the same data is re-fetched and again re-saved in the database.

Here's my code for fetching and saving data to room database:

    private void saveAllProducts() {
    AndroidNetworking.get(Constants.ALL_PRODUCTS_ENDPOINT)
            .setTag("Find All Products")
            .setPriority(Priority.HIGH)
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "All Products Response:\t" + response.toString());
                    saveProductsList = new ArrayList<>();

                    try {
                        JSONObject jsonObject = new JSONObject(response.toString());
                        JSONArray data = jsonObject.getJSONArray("products");

                        for (int d = 0; d < data.length(); d++) {
                            JSONObject allProductsObject = data.getJSONObject(d);

                            String id = allProductsObject.getString("_id");
                            String title = allProductsObject.getString("title");
                            String slug = allProductsObject.getString("slug");
                            String price = allProductsObject.getString("price");
                            String desc = allProductsObject.getString("desc");
                            String category = allProductsObject.getString("category");
                            String image = allProductsObject.getString("image");

                            Products products = new Products();
                            products.setProductId(id);
                            products.setProductName(title);
                            products.setProductDesc(desc);
                            products.setCategory(category);
                            products.setProductPrice(price);
                            products.setImage(image);

                            saveProductsList.clear();
                            saveProductsList.add(products);

                            Log.d(TAG, "Saved List Size:\t" + saveProductsList.size());

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    /**
                     *  Code block to save products
                     * */

                    ProductsDatabase database = 
  ProductsDatabase.getInstance(getBaseContext());

  database.getProductsDAO().insertAllProducts(saveProductsList);


                }

                @Override
                public void onError(ANError anError) {

                }
            });
}

I want to update the database with new data each time but also not duplicating existing data. Is it possible to count and remove the duplicates in the list before saving to room? How can I solve this? Thanks

Here's my DAO interface:

@Dao
public interface ProductsDAO {

     @Query("Select * from products")
     List<Products> getAllProducts();

     @Query("Select * from products where category = :category LIMIT 1")
     Products findByCategory(String category);

     @Insert(onConflict = OnConflictStrategy.IGNORE)
     void insertAllProducts(List<Products> productsList);

 }

Upvotes: 0

Views: 1674

Answers (1)

humazed
humazed

Reputation: 76922

In your, Dao add onConflictin the insert method

@Insert(onConflict = OnConflictStrategy.REPLACE)
public void insertProduct(Product product);

this way if the product with the same id is added with different data will be updated. and you will not end up with duplicate rows.

  • consider using OnConflictStrategy.IGNORE if it's guaranteed that a product with the same id won't change.

Upvotes: 1

Related Questions