【发布时间】:2014-06-10 21:46:20
【问题描述】:
我正在使用 SharedPreferences 来存储我的应用程序中的一些信息,但正在为活动创建一个对象来管理它。我也在这堂课中使用encrypted-userprefs。我在
中收到错误“空白的最终字段编写器可能尚未初始化”public StoredPrefsHandler(Context context, boolean secure) throws SecurePreferencesException {
我不知道为什么会发生这种情况,尤其是当它似乎在我的类似课程中工作时。以下是相关代码。请注意,我已经定义了 writer。
public class StoredPrefsHandler {
public static class SecurePreferencesException extends RuntimeException {
private static final long serialVersionUID = 3051912281127821578L;
public SecurePreferencesException(Throwable e) {
super(e);
}
}
// Stripped down part, more fields unrelevant to the problem have been hidden
private final String SP_LOCATION = "org.conrogatio.lazyrace.prefs";
private final String SSP_LOCATION = "org.conrogatio.lazyrace.secureprefs";
private String LOCATION;
private Context c;
private SharedPreferences prefs;
private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static final String KEY_TRANSFORMATION = "AES/ECB/PKCS5Padding";
private static final String SECRET_KEY_HASH_TRANSFORMATION = "SHA-256";
private static final String CHARSET = "UTF-8";
private final Cipher writer;
private final Cipher reader;
private final Cipher keyWriter;
/**
* This will initialize an instance of the SecurePreferences class
*
* @param context
* your current context.
* @throws SecurePreferencesException
*/
public StoredPrefsHandler(Context context, boolean secure) throws SecurePreferencesException {
c = context;
secured = secure;
if (secured) {
LOCATION = SSP_LOCATION;
deviceId = Secure.getString(c.getContentResolver(), Secure.ANDROID_ID);
try {
this.writer = Cipher.getInstance(TRANSFORMATION);
this.reader = Cipher.getInstance(TRANSFORMATION);
this.keyWriter = Cipher.getInstance(KEY_TRANSFORMATION);
initCiphers(deviceId + SSP_SALT);
this.prefs = c.getSharedPreferences(SSP_LOCATION, Context.MODE_PRIVATE);
} catch (GeneralSecurityException e) {
throw new SecurePreferencesException(e);
} catch (UnsupportedEncodingException e) {
throw new SecurePreferencesException(e);
}
} else {
LOCATION = SP_LOCATION;
}
update();
}
【问题讨论】:
-
如果您将 secure=false 传递给此构造函数,则最终字段 writer、reader 和 keyWriter 保持未初始化。因此编译器抱怨。如果您知道不需要它们,请将它们设置为 null。
-
如果也使它们成为非最终版本,这似乎也有效
标签: android sharedpreferences encryption