使用Realm Android链接查询

时间:2016-12-15 16:13:55

标签: android realm

我有以下课程:

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

我需要找到所有通过SharedPreferences获得成分的食谱。这是我必须在所有食谱中获取成分的ID的代码:

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();
    }
}

我无法通过id列表查询存储在我的db配方中的所有配方中的查询,这些配方是使用获得的成分制作的。

编辑: 这是成分的SharedPreferences的一个例子:

<?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>

数字是成分的ID

1 个答案:

答案 0 :(得分:0)

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();
}