我正在使用 Realm 在 Android 上编写一个食谱应用程序。我在每个 Recipe 对象中都有一个 Ingredient 类型的 RealmList。对象创建代码工作正常。
现在我正在为显示单个配方的 fragment 编写代码。我能够为所有食谱标题列表创建一个 Realm 适配器,因为我使用如下查询构建了该列表:
public class RecipeTitleAdapter extends RealmBaseAdapter<RecipeTitle> implements ListAdapter {
public RecipeTitleAdapter(Context context, int resId,
RealmResults<RecipeTitle> realmResults,
boolean automaticUpdate) {
...
recipeTitles = RecipeTitle.returnAllRecipeTitles(realm);
final RecipeTitleAdapter adapter = new RecipeTitleAdapter(RecipeParserApplication.appContext, R.id.recipe_list_view, recipeTitles, true);
但是现在我正在查看单个食谱的成分,我有一个成分的 RealmList 而不是 RealmResults 对象。我的成分适配器类具有与菜谱标题适配器相同类型的构造函数,因此我想知道如何(甚至是否)可以使其从 RealmList 开始工作。
public class IngredientAdapter extends RealmBaseAdapter<Ingredient> implements ListAdapter {
private static class ViewHolder {
TextView quantity;
TextView unitOfMeasure;
TextView ingredientItemName;
TextView processingInstructions;
}
public IngredientAdapter(Context context, int resId,
RealmResults<Ingredient> realmResults,
boolean automaticUpdate) {
....
final IngredientAdapter adapter = new IngredientAdapter(RecipeParserApplication.appContext, R.id.ingredientListView, recipe.getIngredients(), true);
public RealmList<Ingredient> getIngredients() {
return ingredients;
}
由于recipe.getIngredients返回RealmList,分配IngredientAdapter的行返回编译错误:
错误:(63, 43) 错误:类 IngredientAdapter 中的构造函数 IngredientAdapter 无法应用于给定类型; 必需:上下文、int、RealmResults、 bool 值 找到:上下文,int,RealmList, bool 值 原因:实参RealmList无法通过方法调用转换转换为RealmResults
最佳答案
RealmList 的行为类似于普通数组,因此如果您无法进行与要显示的内容匹配的查询,则可以使用任何普通适配器,例如一个数组适配器。使用 RealmBaseAdapter 的唯一优点是它会自动刷新,但这很容易自己完成:
// Pseudo code
ArrayAdapter adapter;
RealmChangeListener listener = new RealmChangeListener() {
public void onChange() {
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
}
protected void onCreate(Bundle savedInstanceState) {
// ...
realm.addChangeListener(listener);
RealmList data = getRealmListData();
adapter = new ArrayAdapter(data);
listView.setAdapter(adapter);
}
关于android - 在 Android 上,如何从 Realm 列表构建 Realm 适配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30541149/