0

私のプログラムは、オプション (ボリューム、バイブレーションなど) が既に設定 (挿入) されているかどうか、オプション テーブルをチェックすることになっています。基本的に、オプションが設定されていない場合、テーブルの最初の列は 0 です。最初の行が空の場合はデフォルトのオプションに切り替え、そうでない場合はオプション セットに切り替えます。オプション チェッカーを try catch で囲み、このエラーを受け取ります。

CursorIndexOutOfBoundsException: サイズ 0 のインデックス 0 が要求されました。

私はまだこのSQLに慣れていないので、自分のコードが自分のニーズに合っているかどうかわかりません。

これは、OnCreate() での私のオプション チェッカーです。

options = new DBFunctions(this);

    try{
    String row = "0".toString();
    long l = Long.parseLong(row);
    options.open();
    String retId = options.getId(l);
    int id = Integer.parseInt(retId);
    options.close();
    //codes for setting the options if/if no data in option table exists will be put here
    }catch(Exception e){
    String error = e.toString();
    tv.setText(error);
}       

これは、DBFunctions の getId() です。ジャバ:

public String getId(long l) {

    String[] columns = new String[]{"id", "volume", "vibrate", "theme"};
    Cursor c = db.query(table, columns, "id=" + l, null, null, null, null);
    if(c !=null){
        c.moveToFirst();
        String id = c.getString(1);
        return id;
    }
    return null;
}

`

4

1 に答える 1

2

空(0行)のデータを取得しようとすると、Cursorその例外がスローされます。あなたの他の質問を見てid、表の列optionsが に設定されていることを確認しましたINTEGER PRIMARY KEY AUTOINCREMENTAUTOINCREMENTは、行がデータベースに挿入されるたびにこの列の値がインクリメントされることを意味し、0 を超える値から開始していると思います (不明)。これは、getIdメソッドで作成したクエリが常に空を返すことを意味しますCursor(0 の行をクエリしますidが、データベースには何もありません)。

データベースに挿入されている/挿入されていない質問の最初の部分とデフォルトへの切り替えが理解できなかったので、あなたが望むことを行う方法を言うことができます。

を使用したサンプル コードを次に示しますSharedPreferences

// When you want to check the status of the options
SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this); //in an activity
    // volumeStatus, vibrateStatus and themeStatus represent the current status of the options
boolean volumeStatus = prefs.getBoolean("volume_key", false); // if volumeStatus is false it is the first app run or the user put the volume to off
boolean vibrateStatus = prefs.getBoolean("vibrate_key", false); // the same as for volumestatus
String themeStatus = prefs.getString("theme_key", null); // if themeStatus is null it is the first run of the app or the user didn't choose a theme

    // when the user modifies one of the preferences use this
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("volume_key", true); // the use sets the volume to on like in the database
            editor.commit();
于 2012-04-08T16:55:19.290 に答える