2010-02-05 44 views
0

好像我必须做一些基本的非常错误的事情,但结果 很奇怪,而且我在追踪问题时遇到了问题。当阅读Android默认共享首选项时,出现递归ClassCastExceptions

这是我我活动的onCreate()

PreferenceManager.setDefaultValues(this, R.xml.metronome_preferences, false); 
mSharedPrefs=PreferenceManager.getDefaultSharedPreferences(this); 

下面的代码家住在onStart()。

Map<String,?> map = mSharedPrefs.getAll(); 
boolean t = mSharedPrefs.contains("tempo_list_pref"); 
Log.d(logID, "t= " + t + " preferences=" + map.toString()); 
mBPMOption = mSharedPrefs.getLong("tempo_list_pref", 100); 

登录猫正确地显示:

十一月2日至五日:14:27.605:DEBUG /节拍器(16147):T =真 偏好= {graphics_list_pref = 1,conduct_list_pref = 12.0f, tempo_list_pref = 140,audio_list_pref = 2,meter_list_pref = 5}

mBPMOption很长。共享的prefs对象显然是有效的,因为我既可以检索首选项作为映射,也可以测试首选项的存在,但调用getLong()会导致ClassCastExceptions被递归抛出。至少,这是 我如何解释我在调试器中看到的内容。错误对象 e包含e.cause,e.cause.cause,...。

我在模拟器和Google ION dev 手机中收到了同样的错误。

任何想法,将不胜感激。

回答

0

它会帮助,如果你表现出的堆栈跟踪,但...

private static final class SharedPreferencesImpl implements SharedPreferences { 
    ... 
    public long getLong(String key, long defValue) { 
     synchronized (this) { 
      Long v = (Long) mMap.get(key); 
      return v != null ? v : defValue; 
     } 
    } 

10便士说,你ClassCastException异常被抛出在那里。当文档说getLong会抛出ClassCastException不是一个Long时,它确实意味着它:一个int不会做。你确定你把这个存储了很久吗?将此行添加到您的代码将告诉你你有什么:

System.err.println(map.get("tempo_list_pref").getClass()); 
+0

很好的建议!事实证明,我的所有数字资源都以字符串形式存在于地图中,这与我的解决方法一致。我只对地图中的值使用适当的decode()或parseFloat()静态方法。如果Android内部首选项映射仅包含字符串值,则在我看来Android代码应为: Long v = Long.decode((String)map.get(key)); – Mark 2010-02-06 10:25:25