探索Android应用开发(三)
学习目标:
- 从下拉框中选中类型;
- 从数据库查询结果;
学习目的:
- 掌握Spinner的使用;
- 掌握数据库操作;
学习收获:
Spinner是一种widget,允许用户从一组选项中进行选中。这和下拉列表非常相像。在从数据库查询数据后,取出结果,然后根据结果选中Spinner的选项时,遇到了一个棘手的问题,异常如下:
ERROR/AndroidRuntime(536): java.lang.RuntimeException: Unable to start activity ComponentInfo{net.poemcode.android/net.poemcode.android.PurseEdit}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2141) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2157) at android.app.ActivityThread.access$1800(ActivityThread.java:112) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1581) at android.os.Handler.dispatchMessage(Handler.java:88) at android.os.Looper.loop(Looper.java:123) at android.app.ActivityThread.main(ActivityThread.java:3739) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:497) at dalvik.system.NativeStart.main(Native Method) Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 at android.database.AbstractCursor.checkPosition(AbstractCursor.java:559) at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:172) at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41) at net.poemcode.android.PurseEdit.onCreate(PurseEdit.java:41) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1122) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2104) ... 11 more |
于是,从获取Cursour的方法开始入手,如下代码所示:
public Cursor fetch(long rowId) { Cursor cursor = db.query(DATABASE_TABLE, new String[]{KEY_ROWID, KEY_TYPE, KEY_MONEY}, KEY_ROWID + "=?", new String[]{String.valueOf(rowId)}, null, null, null); return cursor; } |
然后调用方式如下:
Cursor cursor = adapter.fetch(mRowId); int typeIndex = cursor.getColumnIndexOrThrow(PurseDbAdapter.KEY_TYPE); String typeValue = cursor.getString(typeIndex); Log.v("PurseEdit", "index of column of type is " + typeIndex + ", value is" + typeValue); |
这样每次取值的时候,就会发生上面的异常,对比官方示例的代码,发现了原因所在,即在调用query方法以后,如果Cursor不为null,应该首先把调用moveToFirst方法。如下所示:
if (cursor != null) { cursor.moveToFirst(); } |
从 XML配置文件中读出数组,采用以下方法:
Resources res = this.getResources(); String[] typeArr = res.getStringArray(R.array.types); |