【发布时间】:2011-03-31 11:58:36
【问题描述】:
我刚遇到以下情况。我有一个 Android 应用程序,我猜它可能会在多个应用程序中发生。它是关于标记/标签/分类,随心所欲地调用它。我在SQLite DB中基本上有以下关系
-------- -------------- ---------
| Tags | | DeviceTags | | Devices |
|--------| |--------------| |---------|
| ID | 1 ------ * | ID | * ------ 1 | ID |
| NAME | | TAGS_ID | | NAME |
-------- | DEVICE_ID | | ... |
-------------- ---------
所有内容都通过我编写的 ContentProvider 公开。到目前为止一切都很好。
在 UI 部分,我有一个 ListActivity 显示所有存储的设备(来自 Devices 表),为了进一步自定义 UI,我创建了自定义行项,根据设备类型等在前面显示一个小图像.
我现在想要实现的是在该列表上为每个设备显示相关标签。现在我的问题来了。对于简单的设备列表,我创建了一个自定义 ResourceCursorAdapter,我在 bindView 方法中设置了相应的信息
@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
final int objectId = cursor.getInt(cursor.getColumnIndex(Devices._ID));
TextView deviceName = (TextView) view.findViewById(R.id.deviceName);
deviceName.setText(...); //set it from the cursor
...
TextView associatedTagsView = (TextView)...;
associatedTagsView.setText(...); //<<<???? This would need a call to a different table
...
}
如您所见,为了能够知道我的设备关联了哪种标签,我需要查询 DeviceTags。所以我做了:
@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
...
TextView associatedTagsView = (TextView)view.findViewById(R.id.deviceTags);
String tagsString = retrieveTagsString(view.getContext().getContentResolver(), objectId);
...
}
private String retrieveTagsString(ContentResolver contentResolver, int objectId) {
Cursor tagForDeviceCursor = contentResolver.query(DroidSenseProviderMetaData.TABLE_JOINS.TAG_DEVICETAG,...);
if(tagForDeviceCursor != null && tagForDeviceCursor.moveToFirst()){
StringBuffer result = new StringBuffer();
boolean isFirst = true;
do{
if(!isFirst)
result.append(", ");
else
isFirst = false;
result.append(retrieve name from cursor column...);
}while(tagForDeviceCursor.moveToNext());
return result.toString();
}
return null;
}
我对此进行了测试,它实际上工作得很好,但老实说,我觉得这样做并不好。不知怎的,我觉得很奇怪......
有没有更好的办法解决这个问题??
//编辑:
在 CommonsWare 的反馈之后,这里做了一点澄清。我对在 CursorAdapter 中对数据库进行第二次查询感到很奇怪,基本上这将导致每行一个查询,我担心这会严重影响我的性能(我仍然需要在具有大量的真实设备上对其进行测试数据,看看这有多大影响)。
我的问题因此是关于在给定我的数据模型的情况下是否有一些策略来避免这种情况,或者我是否必须基本上“忍受”它:)
【问题讨论】:
标签: android optimization listview