2014-06-10 55 views
0

我使用SharedPreferences來存儲來自我的應用程序的一些信息,但正在創建一個對象來管理此活動。我也在這個班裏使用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

如果傳遞_secure = false_這個構造函數,最終場_writer_,_reader_和_keyWriter_仍然未初始化的。因此編譯器抱怨。如果你知道你不需要它們,將它們設置爲null。 – harism

+0

這似乎工作,如果也使它們非最終 –

回答

0

如果安全== false時,作家,讀者和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; 
0

嘗試初始化總決賽這樣的:

private final Cipher writer=null; 
private final Cipher reader=null; 
private final Cipher keyWriter=null; 
+0

因爲我也必須重新初始化它們,如果安全==真,最後的參數需要刪除 –

+0

你可以使它們不是最終的 –