我正在使用SharedPreferences来存储我的应用程序中的一些信息,但是正在创建一个Object for Activities来管理它。我也在这堂课中使用encrypted-userprefs。我收到错误"空白的最终字段编写器可能尚未初始化"在
public StoredPrefsHandler(Context context, boolean secure) throws SecurePreferencesException {
我不知道为什么会发生这种情况,特别是当它似乎在我所拥有的类似课程中工作时。以下是相关代码。请注意,我已经定义了编写器。
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();
}
答案 0 :(得分:0)
尝试像这样初始化决赛:
private final Cipher writer=null;
private final Cipher reader=null;
private final Cipher keyWriter=null;
答案 1 :(得分:0)
如果secure == false,则writer,reader和keyWriter将被取消初始化。这可以通过更早地初始化它们来解决,但是也可以将它们设置为非最终的。
private final Cipher writer;
private final Cipher reader;
private final Cipher keyWriter;
变为
private Cipher writer = null;
private Cipher reader = null;
private Cipher keyWriter = null;