我正在使用Realm在Android上编写食谱应用。我在每个食谱对象中都有一个类型为成分的RealmList。对象创建代码工作正常。
现在我正在编写显示单个配方的Fragment代码。我能够为所有食谱标题列表创建一个Realm Adapter,因为我使用如下查询构建了该列表:
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不能应用于给定类型; required:Context,int,RealmResults,boolean 发现:Context,int,RealmList,boolean 原因:实际参数RealmList无法通过方法调用转换转换为RealmResults
答案 0 :(得分:2)
RealmList的行为类似于普通数组,因此如果您无法进行与要显示的匹配的查询,则可以使用任何常规适配器,例如:一个ArrayAdapter。使用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);
}