包含来自多个表连接的数据的Android列表视图

时间:2014-02-01 12:45:22

标签: android listview custom-adapter

我编写了一个ContentProvider,它使用join从多个表(父级和子级)返回数据。结果是Cursor,其中包含检索到的每个子表行的一行。例如。如果我的子表中有2行用于父表中的一行,则游标有2行,父列的重复值和子表的唯一值。

ListView中使用此功能时,我希望每个父级显示一个ListView项,即每两条记录。

我已经编写了一个自CursorAdaptor扩展的自定义适配器,我已按照以下方式覆盖了getViewnewViewbindView方法 -

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (!mDataValid) {
        throw new IllegalStateException("this should only be called when the cursor is valid");
    }
    if (!mCursor.moveToPosition(position)) {
        throw new IllegalStateException("couldn't move cursor to position " + position);
    }
    View v;
    if (convertView == null) {

  //If the lookup value _id is same for this record don't create new view
  //instead only bind view and set the data from child table into existing view

        String lookupValue = mCursor.getString(mCursor.getColumnIndex(mLookupColumn));
        v = parent.findViewWithTag(lookupValue);
        if(v == null){
            v = newView(mContext, mCursor, parent);
            v.setTag(lookupValue);
        }

    } else {
        v = convertView;
    }
    this.bindView(v, mContext, mCursor);
    return v;
}   

@Override
public void bindView(View view, Context context, Cursor cursor) {
    mAdapterView.setData(context, convertToDomainObject(cursor), view);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {

    return mInflater.inflate(mLayout, parent, false);

}

然而,结果很奇怪,我在备用位置得到空白视图是可以理解的(因为我的getView返回null)但是这也不一致。

我一直在努力解决这个问题。真的很感激任何帮助。

注意 - 使用distinct,group by没有帮助,因为我想获取两个记录并使用它们只将它们映射到一行,导致记录和列表项之间的*:1映射。

1 个答案:

答案 0 :(得分:0)

如果您只想整理您的结果,我只需在分配您的适配器之前执行此操作。您没有指定是否为ListView的行使用自定义布局,但这可能是一种可行的方法。

假设您有一个主要字段(例如,名称),并且对于该字段,还有其他几个字段(例如,几个电子邮件地址),第一个也可能是关键步骤是选择正确的数据容器。例如,我使用ArrayMap<String, ArrayList<String>>。名称的左侧值和电子邮件地址的右侧值。在那之后,我将构建我的ListView定义并覆盖getView()方法,构建我的自定义布局。

相关问题