2

Android アプリケーションを作成していて、PreferenceActivity を使用しようとしています。

この行に到達するとjava.lang.ClassCastException: java.lang.Stringエラーが発生しますreturn PreferenceManager.getDefaultSharedPreferences(context).getInt(USER_TERM, USER_TERM_DEF);

EditTextボックスの文字列値から必要なintに適切に変換していないためだと思いましたが、これを修正する方法がわかりませんか、それとも原因ですか? 私は困惑しています。

私の好みのアクティビティクラスは次のとおりです。

public class UserPrefs extends PreferenceActivity {
//option names and default vals
private static final String USER_TERM = "term_length";
private static final String USER_YEAR = "year_length";
private static final int USER_TERM_DEF = 12;
private static final int USER_YEAR_DEF = 34;

@Override 
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences); 
}

public static int getTermLength(Context context){
    try{
    return PreferenceManager.getDefaultSharedPreferences(context).getInt(USER_TERM, USER_TERM_DEF);
    }catch (ClassCastException e){Log.v("getTermLength", "error::: " + e); }
    //return 1;//temporary, needed to catch the error and couldn't without adding a return outside the block.//
}
public static int getYearLength(Context context){
    return PreferenceManager.getDefaultSharedPreferences(context).getInt(USER_YEAR, USER_YEAR_DEF);
}

そして、別のクラス内で設定を使用しようとしているコードの一部を次に示します。

public float alterForFrequency(Context keypadContext, float enteredAmount, String spinnerPosition){

    int termLength = UserPrefs.getTermLength(keypadContext);
    int yearLength = UserPrefs.getYearLength(keypadContext);
}

完全な Android logcat、私はここにアップロードしました: http://freetexthost.com/v3t4ta3wbi

4

1 に答える 1

9

として保存されているプリファレンスがあり、それStringを として読み込もうとしているintため、ClassCastException.

設定を文字列として保存したままにしておきたい場合は、getStringその値を使用して に渡しInteger.parseInt()int.

それ以外の場合は、値が設定に int として書き込まれるようにする必要があります。

于 2011-01-29T15:20:20.187 に答える