my 的每一项都SherlockListFragment
包含 3 个TextView
:一个名字和两个数字。数据来自objective
我的数据库表,其结构如下:
CREATE TABLE objective (
_id INTEGER PRIMARY KEY,
id_project INTEGER NOT NULL,
activity_code INTEGER NOT NULL,
day_duration INTEGER NOT NULL,
week_frequency INTEGER NOT NULL,
FOREIGN KEY(id_project) REFERENCES project(id_project)
);
此外,我已经读过应该通过使用加载器来从游标填充列表(特别是在使用数据库时,因为它可能是一个非常慢的操作)。我在 stackoverflow 上SimpleCursorLoader
找到了一个类,但它直接将数据映射到一个字段。
这不是我真正想要的,因为如您所见,在我的objective
桌子上我有一个activity_code
. 所以我想用一个字符串替换它(我有一个枚举,它列出了我所有的活动代码,并为每个活动代码返回一个字符串资源标识符)。
你知道我如何在数据显示在TextView
s 之前对其进行操作吗?
这是我的SherlockListFragment
public class ObjectivesDisplayFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor>
{
private Activity activity;
private SimpleCursorAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.objectives_display, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
activity = getActivity();
String[] columns = new String[] { "activity_code", "day_duration", "week_frequency" };
int[] to = new int[] { R.id.activityName, R.id.objectiveDuration, R.id.objectiveFrequency };
getLoaderManager().initLoader(0x01, null, this);
adapter = new SimpleCursorAdapter(activity.getApplicationContext(), R.layout.objective_row, null, columns, to, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
}
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
return new SimpleCursorLoader(activity) {
@Override
public Cursor loadInBackground() {
DatabaseHelper dbHelper = DatabaseHelper.getInstance(activity);
String query = "SELECT _id, activity_code, day_duration, week_frequency FROM objective WHERE id_project = ?";
String[] args = new String[] { "1" }; // projectId
Cursor results = dbHelper.getReadableDatabase().rawQuery(query, args);
return results;
}
};
}
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
adapter.swapCursor(cursor);
}
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.swapCursor(null);
}
}
编辑:我不需要在 SimpleCursorLoader > loadInBackground 中关闭游标和数据库,对吗?否则无法读取数据。那么关闭操作是自动处理的还是我需要在其他地方自己做呢?