Search code examples
androidrealm

Link Queries with Realm Android


I have the following classes:

public class Recipe  extends RealmObject {

  @PrimaryKey
  private long id;

  private String title;
  private String description;
  private RealmList<Ingredient> ingredients;
  private String imageUrl;
}

public class Ingredient extends RealmObject{

  @PrimaryKey
  private long id;

  private String name;
  private String category;
}

I need to find all the recipes that have the ingredients obtained through a SharedPreferences. This is the code I have to get the ids of the ingredients that I have to look for in all the recipes:

public RealmResults<Recipe> getRecipesByIngredients(){

    SharedPreferences prefs = getContext().getSharedPreferences("INGREDIENTS_USER_FILE", Context.MODE_PRIVATE);
    Map<String, ?> allEntries =  prefs.getAll();


    for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
        Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
        String id = entry.getValue().toString();
    }
}

I can not make a query that from a list of ids look in all the recipes stored in my db recipes that are made with the ingredients obtained.

Edit: This is an example of SharedPreferences of ingredients:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="IngredienteEspecias1">9</string>
<string name="IngredienteEspecias2">10</string>
<string name="IngredienteCarne0">12</string>
<string name="IngredienteEspecias0">0</string>
</map>

Numbers are the ids of the ingredients


Solution

  • public RealmResults<Recipe> getRecipesByIngredients(){
    
        SharedPreferences prefs = getContext().getSharedPreferences("INGREDIENTS_USER_FILE", Context.MODE_PRIVATE);
        Map<String, ?> allEntries =  prefs.getAll();
    
        List<Long> ingredientIds = new ArrayList<>();    
        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
            String id = entry.getValue().toString();
            ingredientIds.add(Long.valueOf(id));
        }
    
    
        RealmQuery<Recipe> query  = realm.where(Recipe.class);
        if(ingredientIds.size()  > 0) {
              query.beginGroup().equalTo("ingredients.id", ingredientIds.get(0));
              for (int i = 1; i < ingredientIds.size() ; i++) {
                  query.or().equalTo("ingredients.id", ingredientIds.get(i));
              }
              query.endGroup();
        } 
        return query.findAll();
    }