Merge pull request #1102 from k9mail/remove_fake_shared_preferences

Don't implement SharedPreferences interface to store settings
This commit is contained in:
cketti 2016-02-20 01:17:06 +01:00
commit 3c68c8aeb5
22 changed files with 276 additions and 396 deletions

View file

@ -16,10 +16,8 @@ import java.util.concurrent.ConcurrentHashMap;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor; import android.database.Cursor;
import android.graphics.Color; import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Uri; import android.net.Uri;
import android.util.Log; import android.util.Log;
@ -36,6 +34,8 @@ import com.fsck.k9.mail.store.StoreConfig;
import com.fsck.k9.mailstore.StorageManager; import com.fsck.k9.mailstore.StorageManager;
import com.fsck.k9.mailstore.StorageManager.StorageProvider; import com.fsck.k9.mailstore.StorageManager.StorageProvider;
import com.fsck.k9.mailstore.LocalStore; import com.fsck.k9.mailstore.LocalStore;
import com.fsck.k9.preferences.StorageEditor;
import com.fsck.k9.preferences.Storage;
import com.fsck.k9.provider.EmailProvider; import com.fsck.k9.provider.EmailProvider;
import com.fsck.k9.provider.EmailProvider.StatsColumns; import com.fsck.k9.provider.EmailProvider.StatsColumns;
import com.fsck.k9.search.ConditionsTreeNode; import com.fsck.k9.search.ConditionsTreeNode;
@ -377,103 +377,103 @@ public class Account implements BaseAccount, StoreConfig {
*/ */
private synchronized void loadAccount(Preferences preferences) { private synchronized void loadAccount(Preferences preferences) {
SharedPreferences prefs = preferences.getPreferences(); Storage storage = preferences.getStorage();
mStoreUri = Base64.decode(prefs.getString(mUuid + ".storeUri", null)); mStoreUri = Base64.decode(storage.getString(mUuid + ".storeUri", null));
mLocalStorageProviderId = prefs.getString(mUuid + ".localStorageProvider", StorageManager.getInstance(K9.app).getDefaultProviderId()); mLocalStorageProviderId = storage.getString(mUuid + ".localStorageProvider", StorageManager.getInstance(K9.app).getDefaultProviderId());
mTransportUri = Base64.decode(prefs.getString(mUuid + ".transportUri", null)); mTransportUri = Base64.decode(storage.getString(mUuid + ".transportUri", null));
mDescription = prefs.getString(mUuid + ".description", null); mDescription = storage.getString(mUuid + ".description", null);
mAlwaysBcc = prefs.getString(mUuid + ".alwaysBcc", mAlwaysBcc); mAlwaysBcc = storage.getString(mUuid + ".alwaysBcc", mAlwaysBcc);
mAutomaticCheckIntervalMinutes = prefs.getInt(mUuid + ".automaticCheckIntervalMinutes", -1); mAutomaticCheckIntervalMinutes = storage.getInt(mUuid + ".automaticCheckIntervalMinutes", -1);
mIdleRefreshMinutes = prefs.getInt(mUuid + ".idleRefreshMinutes", 24); mIdleRefreshMinutes = storage.getInt(mUuid + ".idleRefreshMinutes", 24);
mPushPollOnConnect = prefs.getBoolean(mUuid + ".pushPollOnConnect", true); mPushPollOnConnect = storage.getBoolean(mUuid + ".pushPollOnConnect", true);
mDisplayCount = prefs.getInt(mUuid + ".displayCount", K9.DEFAULT_VISIBLE_LIMIT); mDisplayCount = storage.getInt(mUuid + ".displayCount", K9.DEFAULT_VISIBLE_LIMIT);
if (mDisplayCount < 0) { if (mDisplayCount < 0) {
mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT; mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT;
} }
mLastAutomaticCheckTime = prefs.getLong(mUuid + ".lastAutomaticCheckTime", 0); mLastAutomaticCheckTime = storage.getLong(mUuid + ".lastAutomaticCheckTime", 0);
mLatestOldMessageSeenTime = prefs.getLong(mUuid + ".latestOldMessageSeenTime", 0); mLatestOldMessageSeenTime = storage.getLong(mUuid + ".latestOldMessageSeenTime", 0);
mNotifyNewMail = prefs.getBoolean(mUuid + ".notifyNewMail", false); mNotifyNewMail = storage.getBoolean(mUuid + ".notifyNewMail", false);
mFolderNotifyNewMailMode = getEnumStringPref(prefs, mUuid + ".folderNotifyNewMailMode", FolderMode.ALL); mFolderNotifyNewMailMode = getEnumStringPref(storage, mUuid + ".folderNotifyNewMailMode", FolderMode.ALL);
mNotifySelfNewMail = prefs.getBoolean(mUuid + ".notifySelfNewMail", true); mNotifySelfNewMail = storage.getBoolean(mUuid + ".notifySelfNewMail", true);
mNotifySync = prefs.getBoolean(mUuid + ".notifyMailCheck", false); mNotifySync = storage.getBoolean(mUuid + ".notifyMailCheck", false);
mDeletePolicy = DeletePolicy.fromInt(prefs.getInt(mUuid + ".deletePolicy", DeletePolicy.NEVER.setting)); mDeletePolicy = DeletePolicy.fromInt(storage.getInt(mUuid + ".deletePolicy", DeletePolicy.NEVER.setting));
mInboxFolderName = prefs.getString(mUuid + ".inboxFolderName", INBOX); mInboxFolderName = storage.getString(mUuid + ".inboxFolderName", INBOX);
mDraftsFolderName = prefs.getString(mUuid + ".draftsFolderName", "Drafts"); mDraftsFolderName = storage.getString(mUuid + ".draftsFolderName", "Drafts");
mSentFolderName = prefs.getString(mUuid + ".sentFolderName", "Sent"); mSentFolderName = storage.getString(mUuid + ".sentFolderName", "Sent");
mTrashFolderName = prefs.getString(mUuid + ".trashFolderName", "Trash"); mTrashFolderName = storage.getString(mUuid + ".trashFolderName", "Trash");
mArchiveFolderName = prefs.getString(mUuid + ".archiveFolderName", "Archive"); mArchiveFolderName = storage.getString(mUuid + ".archiveFolderName", "Archive");
mSpamFolderName = prefs.getString(mUuid + ".spamFolderName", "Spam"); mSpamFolderName = storage.getString(mUuid + ".spamFolderName", "Spam");
mExpungePolicy = getEnumStringPref(prefs, mUuid + ".expungePolicy", Expunge.EXPUNGE_IMMEDIATELY); mExpungePolicy = getEnumStringPref(storage, mUuid + ".expungePolicy", Expunge.EXPUNGE_IMMEDIATELY);
mSyncRemoteDeletions = prefs.getBoolean(mUuid + ".syncRemoteDeletions", true); mSyncRemoteDeletions = storage.getBoolean(mUuid + ".syncRemoteDeletions", true);
mMaxPushFolders = prefs.getInt(mUuid + ".maxPushFolders", 10); mMaxPushFolders = storage.getInt(mUuid + ".maxPushFolders", 10);
goToUnreadMessageSearch = prefs.getBoolean(mUuid + ".goToUnreadMessageSearch", false); goToUnreadMessageSearch = storage.getBoolean(mUuid + ".goToUnreadMessageSearch", false);
subscribedFoldersOnly = prefs.getBoolean(mUuid + ".subscribedFoldersOnly", false); subscribedFoldersOnly = storage.getBoolean(mUuid + ".subscribedFoldersOnly", false);
maximumPolledMessageAge = prefs.getInt(mUuid + ".maximumPolledMessageAge", -1); maximumPolledMessageAge = storage.getInt(mUuid + ".maximumPolledMessageAge", -1);
maximumAutoDownloadMessageSize = prefs.getInt(mUuid + ".maximumAutoDownloadMessageSize", 32768); maximumAutoDownloadMessageSize = storage.getInt(mUuid + ".maximumAutoDownloadMessageSize", 32768);
mMessageFormat = getEnumStringPref(prefs, mUuid + ".messageFormat", DEFAULT_MESSAGE_FORMAT); mMessageFormat = getEnumStringPref(storage, mUuid + ".messageFormat", DEFAULT_MESSAGE_FORMAT);
mMessageFormatAuto = prefs.getBoolean(mUuid + ".messageFormatAuto", DEFAULT_MESSAGE_FORMAT_AUTO); mMessageFormatAuto = storage.getBoolean(mUuid + ".messageFormatAuto", DEFAULT_MESSAGE_FORMAT_AUTO);
if (mMessageFormatAuto && mMessageFormat == MessageFormat.TEXT) { if (mMessageFormatAuto && mMessageFormat == MessageFormat.TEXT) {
mMessageFormat = MessageFormat.AUTO; mMessageFormat = MessageFormat.AUTO;
} }
mMessageReadReceipt = prefs.getBoolean(mUuid + ".messageReadReceipt", DEFAULT_MESSAGE_READ_RECEIPT); mMessageReadReceipt = storage.getBoolean(mUuid + ".messageReadReceipt", DEFAULT_MESSAGE_READ_RECEIPT);
mQuoteStyle = getEnumStringPref(prefs, mUuid + ".quoteStyle", DEFAULT_QUOTE_STYLE); mQuoteStyle = getEnumStringPref(storage, mUuid + ".quoteStyle", DEFAULT_QUOTE_STYLE);
mQuotePrefix = prefs.getString(mUuid + ".quotePrefix", DEFAULT_QUOTE_PREFIX); mQuotePrefix = storage.getString(mUuid + ".quotePrefix", DEFAULT_QUOTE_PREFIX);
mDefaultQuotedTextShown = prefs.getBoolean(mUuid + ".defaultQuotedTextShown", DEFAULT_QUOTED_TEXT_SHOWN); mDefaultQuotedTextShown = storage.getBoolean(mUuid + ".defaultQuotedTextShown", DEFAULT_QUOTED_TEXT_SHOWN);
mReplyAfterQuote = prefs.getBoolean(mUuid + ".replyAfterQuote", DEFAULT_REPLY_AFTER_QUOTE); mReplyAfterQuote = storage.getBoolean(mUuid + ".replyAfterQuote", DEFAULT_REPLY_AFTER_QUOTE);
mStripSignature = prefs.getBoolean(mUuid + ".stripSignature", DEFAULT_STRIP_SIGNATURE); mStripSignature = storage.getBoolean(mUuid + ".stripSignature", DEFAULT_STRIP_SIGNATURE);
for (NetworkType type : NetworkType.values()) { for (NetworkType type : NetworkType.values()) {
Boolean useCompression = prefs.getBoolean(mUuid + ".useCompression." + type, Boolean useCompression = storage.getBoolean(mUuid + ".useCompression." + type,
true); true);
compressionMap.put(type, useCompression); compressionMap.put(type, useCompression);
} }
mAutoExpandFolderName = prefs.getString(mUuid + ".autoExpandFolderName", INBOX); mAutoExpandFolderName = storage.getString(mUuid + ".autoExpandFolderName", INBOX);
mAccountNumber = prefs.getInt(mUuid + ".accountNumber", 0); mAccountNumber = storage.getInt(mUuid + ".accountNumber", 0);
mChipColor = prefs.getInt(mUuid + ".chipColor", ColorPicker.getRandomColor()); mChipColor = storage.getInt(mUuid + ".chipColor", ColorPicker.getRandomColor());
mSortType = getEnumStringPref(prefs, mUuid + ".sortTypeEnum", SortType.SORT_DATE); mSortType = getEnumStringPref(storage, mUuid + ".sortTypeEnum", SortType.SORT_DATE);
mSortAscending.put(mSortType, prefs.getBoolean(mUuid + ".sortAscending", false)); mSortAscending.put(mSortType, storage.getBoolean(mUuid + ".sortAscending", false));
mShowPictures = getEnumStringPref(prefs, mUuid + ".showPicturesEnum", ShowPictures.NEVER); mShowPictures = getEnumStringPref(storage, mUuid + ".showPicturesEnum", ShowPictures.NEVER);
mNotificationSetting.setVibrate(prefs.getBoolean(mUuid + ".vibrate", false)); mNotificationSetting.setVibrate(storage.getBoolean(mUuid + ".vibrate", false));
mNotificationSetting.setVibratePattern(prefs.getInt(mUuid + ".vibratePattern", 0)); mNotificationSetting.setVibratePattern(storage.getInt(mUuid + ".vibratePattern", 0));
mNotificationSetting.setVibrateTimes(prefs.getInt(mUuid + ".vibrateTimes", 5)); mNotificationSetting.setVibrateTimes(storage.getInt(mUuid + ".vibrateTimes", 5));
mNotificationSetting.setRing(prefs.getBoolean(mUuid + ".ring", true)); mNotificationSetting.setRing(storage.getBoolean(mUuid + ".ring", true));
mNotificationSetting.setRingtone(prefs.getString(mUuid + ".ringtone", mNotificationSetting.setRingtone(storage.getString(mUuid + ".ringtone",
"content://settings/system/notification_sound")); "content://settings/system/notification_sound"));
mNotificationSetting.setLed(prefs.getBoolean(mUuid + ".led", true)); mNotificationSetting.setLed(storage.getBoolean(mUuid + ".led", true));
mNotificationSetting.setLedColor(prefs.getInt(mUuid + ".ledColor", mChipColor)); mNotificationSetting.setLedColor(storage.getInt(mUuid + ".ledColor", mChipColor));
mFolderDisplayMode = getEnumStringPref(prefs, mUuid + ".folderDisplayMode", FolderMode.NOT_SECOND_CLASS); mFolderDisplayMode = getEnumStringPref(storage, mUuid + ".folderDisplayMode", FolderMode.NOT_SECOND_CLASS);
mFolderSyncMode = getEnumStringPref(prefs, mUuid + ".folderSyncMode", FolderMode.FIRST_CLASS); mFolderSyncMode = getEnumStringPref(storage, mUuid + ".folderSyncMode", FolderMode.FIRST_CLASS);
mFolderPushMode = getEnumStringPref(prefs, mUuid + ".folderPushMode", FolderMode.FIRST_CLASS); mFolderPushMode = getEnumStringPref(storage, mUuid + ".folderPushMode", FolderMode.FIRST_CLASS);
mFolderTargetMode = getEnumStringPref(prefs, mUuid + ".folderTargetMode", FolderMode.NOT_SECOND_CLASS); mFolderTargetMode = getEnumStringPref(storage, mUuid + ".folderTargetMode", FolderMode.NOT_SECOND_CLASS);
searchableFolders = getEnumStringPref(prefs, mUuid + ".searchableFolders", Searchable.ALL); searchableFolders = getEnumStringPref(storage, mUuid + ".searchableFolders", Searchable.ALL);
mIsSignatureBeforeQuotedText = prefs.getBoolean(mUuid + ".signatureBeforeQuotedText", false); mIsSignatureBeforeQuotedText = storage.getBoolean(mUuid + ".signatureBeforeQuotedText", false);
identities = loadIdentities(prefs); identities = loadIdentities(storage);
String cryptoApp = prefs.getString(mUuid + ".cryptoApp", NO_OPENPGP_PROVIDER); String cryptoApp = storage.getString(mUuid + ".cryptoApp", NO_OPENPGP_PROVIDER);
setCryptoApp(cryptoApp); setCryptoApp(cryptoApp);
mCryptoKey = prefs.getLong(mUuid + ".cryptoKey", NO_OPENPGP_KEY); mCryptoKey = storage.getLong(mUuid + ".cryptoKey", NO_OPENPGP_KEY);
mAllowRemoteSearch = prefs.getBoolean(mUuid + ".allowRemoteSearch", false); mAllowRemoteSearch = storage.getBoolean(mUuid + ".allowRemoteSearch", false);
mRemoteSearchFullText = prefs.getBoolean(mUuid + ".remoteSearchFullText", false); mRemoteSearchFullText = storage.getBoolean(mUuid + ".remoteSearchFullText", false);
mRemoteSearchNumResults = prefs.getInt(mUuid + ".remoteSearchNumResults", DEFAULT_REMOTE_SEARCH_NUM_RESULTS); mRemoteSearchNumResults = storage.getInt(mUuid + ".remoteSearchNumResults", DEFAULT_REMOTE_SEARCH_NUM_RESULTS);
mEnabled = prefs.getBoolean(mUuid + ".enabled", true); mEnabled = storage.getBoolean(mUuid + ".enabled", true);
mMarkMessageAsReadOnView = prefs.getBoolean(mUuid + ".markMessageAsReadOnView", true); mMarkMessageAsReadOnView = storage.getBoolean(mUuid + ".markMessageAsReadOnView", true);
mAlwaysShowCcBcc = prefs.getBoolean(mUuid + ".alwaysShowCcBcc", false); mAlwaysShowCcBcc = storage.getBoolean(mUuid + ".alwaysShowCcBcc", false);
cacheChips(); cacheChips();
@ -485,7 +485,7 @@ public class Account implements BaseAccount, StoreConfig {
protected synchronized void delete(Preferences preferences) { protected synchronized void delete(Preferences preferences) {
// Get the list of account UUIDs // Get the list of account UUIDs
String[] uuids = preferences.getPreferences().getString("accountUuids", "").split(","); String[] uuids = preferences.getStorage().getString("accountUuids", "").split(",");
// Create a list of all account UUIDs excluding this account // Create a list of all account UUIDs excluding this account
List<String> newUuids = new ArrayList<String>(uuids.length); List<String> newUuids = new ArrayList<String>(uuids.length);
@ -495,7 +495,7 @@ public class Account implements BaseAccount, StoreConfig {
} }
} }
SharedPreferences.Editor editor = preferences.getPreferences().edit(); StorageEditor editor = preferences.getStorage().edit();
// Only change the 'accountUuids' value if this account's UUID was listed before // Only change the 'accountUuids' value if this account's UUID was listed before
if (newUuids.size() < uuids.length) { if (newUuids.size() < uuids.length) {
@ -572,7 +572,7 @@ public class Account implements BaseAccount, StoreConfig {
for (NetworkType type : NetworkType.values()) { for (NetworkType type : NetworkType.values()) {
editor.remove(mUuid + ".useCompression." + type.name()); editor.remove(mUuid + ".useCompression." + type.name());
} }
deleteIdentities(preferences.getPreferences(), editor); deleteIdentities(preferences.getStorage(), editor);
// TODO: Remove preference settings that may exist for individual // TODO: Remove preference settings that may exist for individual
// folders in the account. // folders in the account.
editor.commit(); editor.commit();
@ -605,8 +605,8 @@ public class Account implements BaseAccount, StoreConfig {
} }
public void move(Preferences preferences, boolean moveUp) { public void move(Preferences preferences, boolean moveUp) {
String[] uuids = preferences.getPreferences().getString("accountUuids", "").split(","); String[] uuids = preferences.getStorage().getString("accountUuids", "").split(",");
SharedPreferences.Editor editor = preferences.getPreferences().edit(); StorageEditor editor = preferences.getStorage().edit();
String[] newUuids = new String[uuids.length]; String[] newUuids = new String[uuids.length];
if (moveUp) { if (moveUp) {
for (int i = 0; i < uuids.length; i++) { for (int i = 0; i < uuids.length; i++) {
@ -637,9 +637,9 @@ public class Account implements BaseAccount, StoreConfig {
} }
public synchronized void save(Preferences preferences) { public synchronized void save(Preferences preferences) {
SharedPreferences.Editor editor = preferences.getPreferences().edit(); StorageEditor editor = preferences.getStorage().edit();
if (!preferences.getPreferences().getString("accountUuids", "").contains(mUuid)) { if (!preferences.getStorage().getString("accountUuids", "").contains(mUuid)) {
/* /*
* When the account is first created we assign it a unique account number. The * When the account is first created we assign it a unique account number. The
* account number will be unique to that account for the lifetime of the account. * account number will be unique to that account for the lifetime of the account.
@ -665,7 +665,7 @@ public class Account implements BaseAccount, StoreConfig {
} }
mAccountNumber++; mAccountNumber++;
String accountUuids = preferences.getPreferences().getString("accountUuids", ""); String accountUuids = preferences.getStorage().getString("accountUuids", "");
accountUuids += (accountUuids.length() != 0 ? "," : "") + mUuid; accountUuids += (accountUuids.length() != 0 ? "," : "") + mUuid;
editor.putString("accountUuids", accountUuids); editor.putString("accountUuids", accountUuids);
} }
@ -750,7 +750,7 @@ public class Account implements BaseAccount, StoreConfig {
editor.putBoolean(mUuid + ".useCompression." + type, useCompression); editor.putBoolean(mUuid + ".useCompression." + type, useCompression);
} }
} }
saveIdentities(preferences.getPreferences(), editor); saveIdentities(preferences.getStorage(), editor);
editor.commit(); editor.commit();
@ -1317,18 +1317,18 @@ public class Account implements BaseAccount, StoreConfig {
return mUuid.hashCode(); return mUuid.hashCode();
} }
private synchronized List<Identity> loadIdentities(SharedPreferences prefs) { private synchronized List<Identity> loadIdentities(Storage storage) {
List<Identity> newIdentities = new ArrayList<Identity>(); List<Identity> newIdentities = new ArrayList<Identity>();
int ident = 0; int ident = 0;
boolean gotOne = false; boolean gotOne = false;
do { do {
gotOne = false; gotOne = false;
String name = prefs.getString(mUuid + "." + IDENTITY_NAME_KEY + "." + ident, null); String name = storage.getString(mUuid + "." + IDENTITY_NAME_KEY + "." + ident, null);
String email = prefs.getString(mUuid + "." + IDENTITY_EMAIL_KEY + "." + ident, null); String email = storage.getString(mUuid + "." + IDENTITY_EMAIL_KEY + "." + ident, null);
boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse." + ident, true); boolean signatureUse = storage.getBoolean(mUuid + ".signatureUse." + ident, true);
String signature = prefs.getString(mUuid + ".signature." + ident, null); String signature = storage.getString(mUuid + ".signature." + ident, null);
String description = prefs.getString(mUuid + "." + IDENTITY_DESCRIPTION_KEY + "." + ident, null); String description = storage.getString(mUuid + "." + IDENTITY_DESCRIPTION_KEY + "." + ident, null);
final String replyTo = prefs.getString(mUuid + ".replyTo." + ident, null); final String replyTo = storage.getString(mUuid + ".replyTo." + ident, null);
if (email != null) { if (email != null) {
Identity identity = new Identity(); Identity identity = new Identity();
identity.setName(name); identity.setName(name);
@ -1344,10 +1344,10 @@ public class Account implements BaseAccount, StoreConfig {
} while (gotOne); } while (gotOne);
if (newIdentities.isEmpty()) { if (newIdentities.isEmpty()) {
String name = prefs.getString(mUuid + ".name", null); String name = storage.getString(mUuid + ".name", null);
String email = prefs.getString(mUuid + ".email", null); String email = storage.getString(mUuid + ".email", null);
boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse", true); boolean signatureUse = storage.getBoolean(mUuid + ".signatureUse", true);
String signature = prefs.getString(mUuid + ".signature", null); String signature = storage.getString(mUuid + ".signature", null);
Identity identity = new Identity(); Identity identity = new Identity();
identity.setName(name); identity.setName(name);
identity.setEmail(email); identity.setEmail(email);
@ -1360,12 +1360,12 @@ public class Account implements BaseAccount, StoreConfig {
return newIdentities; return newIdentities;
} }
private synchronized void deleteIdentities(SharedPreferences prefs, SharedPreferences.Editor editor) { private synchronized void deleteIdentities(Storage storage, StorageEditor editor) {
int ident = 0; int ident = 0;
boolean gotOne = false; boolean gotOne = false;
do { do {
gotOne = false; gotOne = false;
String email = prefs.getString(mUuid + "." + IDENTITY_EMAIL_KEY + "." + ident, null); String email = storage.getString(mUuid + "." + IDENTITY_EMAIL_KEY + "." + ident, null);
if (email != null) { if (email != null) {
editor.remove(mUuid + "." + IDENTITY_NAME_KEY + "." + ident); editor.remove(mUuid + "." + IDENTITY_NAME_KEY + "." + ident);
editor.remove(mUuid + "." + IDENTITY_EMAIL_KEY + "." + ident); editor.remove(mUuid + "." + IDENTITY_EMAIL_KEY + "." + ident);
@ -1379,8 +1379,8 @@ public class Account implements BaseAccount, StoreConfig {
} while (gotOne); } while (gotOne);
} }
private synchronized void saveIdentities(SharedPreferences prefs, SharedPreferences.Editor editor) { private synchronized void saveIdentities(Storage storage, StorageEditor editor) {
deleteIdentities(prefs, editor); deleteIdentities(storage, editor);
int ident = 0; int ident = 0;
for (Identity identity : identities) { for (Identity identity : identities) {

View file

@ -1,10 +1,12 @@
package com.fsck.k9; package com.fsck.k9;
import android.content.SharedPreferences;
import android.util.TypedValue; import android.util.TypedValue;
import android.widget.TextView; import android.widget.TextView;
import com.fsck.k9.preferences.GlobalSettings; import com.fsck.k9.preferences.GlobalSettings;
import com.fsck.k9.preferences.Storage;
import com.fsck.k9.preferences.StorageEditor;
/** /**
* Manage font size of the information displayed in the account list, folder * Manage font size of the information displayed in the account list, folder
@ -157,7 +159,7 @@ public class FontSizes {
* *
* @param editor Used to save the font size settings. * @param editor Used to save the font size settings.
*/ */
public void save(SharedPreferences.Editor editor) { public void save(StorageEditor editor) {
editor.putInt(ACCOUNT_NAME, accountName); editor.putInt(ACCOUNT_NAME, accountName);
editor.putInt(ACCOUNT_DESCRIPTION, accountDescription); editor.putInt(ACCOUNT_DESCRIPTION, accountDescription);
@ -183,40 +185,40 @@ public class FontSizes {
/** /**
* Load the font size settings from permanent storage. * Load the font size settings from permanent storage.
* *
* @param prefs Used to load the font size settings. * @param storage Used to load the font size settings.
*/ */
public void load(SharedPreferences prefs) { public void load(Storage storage) {
accountName = prefs.getInt(ACCOUNT_NAME, accountName); accountName = storage.getInt(ACCOUNT_NAME, accountName);
accountDescription = prefs.getInt(ACCOUNT_DESCRIPTION, accountDescription); accountDescription = storage.getInt(ACCOUNT_DESCRIPTION, accountDescription);
folderName = prefs.getInt(FOLDER_NAME, folderName); folderName = storage.getInt(FOLDER_NAME, folderName);
folderStatus = prefs.getInt(FOLDER_STATUS, folderStatus); folderStatus = storage.getInt(FOLDER_STATUS, folderStatus);
messageListSubject = prefs.getInt(MESSAGE_LIST_SUBJECT, messageListSubject); messageListSubject = storage.getInt(MESSAGE_LIST_SUBJECT, messageListSubject);
messageListSender = prefs.getInt(MESSAGE_LIST_SENDER, messageListSender); messageListSender = storage.getInt(MESSAGE_LIST_SENDER, messageListSender);
messageListDate = prefs.getInt(MESSAGE_LIST_DATE, messageListDate); messageListDate = storage.getInt(MESSAGE_LIST_DATE, messageListDate);
messageListPreview = prefs.getInt(MESSAGE_LIST_PREVIEW, messageListPreview); messageListPreview = storage.getInt(MESSAGE_LIST_PREVIEW, messageListPreview);
messageViewSender = prefs.getInt(MESSAGE_VIEW_SENDER, messageViewSender); messageViewSender = storage.getInt(MESSAGE_VIEW_SENDER, messageViewSender);
messageViewTo = prefs.getInt(MESSAGE_VIEW_TO, messageViewTo); messageViewTo = storage.getInt(MESSAGE_VIEW_TO, messageViewTo);
messageViewCC = prefs.getInt(MESSAGE_VIEW_CC, messageViewCC); messageViewCC = storage.getInt(MESSAGE_VIEW_CC, messageViewCC);
messageViewAdditionalHeaders = prefs.getInt(MESSAGE_VIEW_ADDITIONAL_HEADERS, messageViewAdditionalHeaders); messageViewAdditionalHeaders = storage.getInt(MESSAGE_VIEW_ADDITIONAL_HEADERS, messageViewAdditionalHeaders);
messageViewSubject = prefs.getInt(MESSAGE_VIEW_SUBJECT, messageViewSubject); messageViewSubject = storage.getInt(MESSAGE_VIEW_SUBJECT, messageViewSubject);
messageViewDate = prefs.getInt(MESSAGE_VIEW_DATE, messageViewDate); messageViewDate = storage.getInt(MESSAGE_VIEW_DATE, messageViewDate);
loadMessageViewContentPercent(prefs); loadMessageViewContentPercent(storage);
messageComposeInput = prefs.getInt(MESSAGE_COMPOSE_INPUT, messageComposeInput); messageComposeInput = storage.getInt(MESSAGE_COMPOSE_INPUT, messageComposeInput);
} }
private void loadMessageViewContentPercent(SharedPreferences prefs) { private void loadMessageViewContentPercent(Storage storage) {
int fallbackValue = 100; int fallbackValue = 100;
if (!prefs.contains(MESSAGE_VIEW_CONTENT_PERCENT)) { if (!storage.contains(MESSAGE_VIEW_CONTENT_PERCENT)) {
int oldValue = prefs.getInt(MESSAGE_VIEW_CONTENT, 3); int oldValue = storage.getInt(MESSAGE_VIEW_CONTENT, 3);
fallbackValue = GlobalSettings.SettingsUpgraderV31.convertFromOldSize(oldValue); fallbackValue = GlobalSettings.SettingsUpgraderV31.convertFromOldSize(oldValue);
} }
setMessageViewContentAsPercent(prefs.getInt(MESSAGE_VIEW_CONTENT_PERCENT, fallbackValue)); setMessageViewContentAsPercent(storage.getInt(MESSAGE_VIEW_CONTENT_PERCENT, fallbackValue));
} }
public int getAccountName() { public int getAccountName() {

View file

@ -36,6 +36,8 @@ import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.internet.BinaryTempFileBody; import com.fsck.k9.mail.internet.BinaryTempFileBody;
import com.fsck.k9.mailstore.LocalStore; import com.fsck.k9.mailstore.LocalStore;
import com.fsck.k9.preferences.Storage;
import com.fsck.k9.preferences.StorageEditor;
import com.fsck.k9.provider.UnreadWidgetProvider; import com.fsck.k9.provider.UnreadWidgetProvider;
import com.fsck.k9.mail.ssl.LocalKeyStore; import com.fsck.k9.mail.ssl.LocalKeyStore;
import com.fsck.k9.service.BootReceiver; import com.fsck.k9.service.BootReceiver;
@ -425,16 +427,7 @@ public class K9 extends Application {
Log.i(K9.LOG_TAG, "Registered: shutdown receiver"); Log.i(K9.LOG_TAG, "Registered: shutdown receiver");
} }
public static void save(StorageEditor editor) {
/**
* Save settings from our statics into the app database.
* <p/>
* If you're adding a preference here, odds are you'll need to add it to
* {@link com.fsck.k9.preferences.GlobalSettings}, too.
*
* @param editor Preferences to save into
*/
public static void save(SharedPreferences.Editor editor) {
editor.putBoolean("enableDebugLogging", K9.DEBUG); editor.putBoolean("enableDebugLogging", K9.DEBUG);
editor.putBoolean("enableSensitiveLogging", K9.DEBUG_SENSITIVE); editor.putBoolean("enableSensitiveLogging", K9.DEBUG_SENSITIVE);
editor.putString("backgroundOperations", K9.backgroundOps.name()); editor.putString("backgroundOperations", K9.backgroundOps.name());
@ -623,7 +616,7 @@ public class K9 extends Application {
/** /**
* Loads the last known database version of the accounts' databases from a * Loads the last known database version of the accounts' databases from a
* {@link SharedPreference}. * {@code SharedPreference}.
* *
* <p> * <p>
* If the stored version matches {@link LocalStore#DB_VERSION} we know that the databases are * If the stored version matches {@link LocalStore#DB_VERSION} we know that the databases are
@ -655,108 +648,108 @@ public class K9 extends Application {
* @param prefs Preferences to load * @param prefs Preferences to load
*/ */
public static void loadPrefs(Preferences prefs) { public static void loadPrefs(Preferences prefs) {
SharedPreferences sprefs = prefs.getPreferences(); Storage storage = prefs.getStorage();
DEBUG = sprefs.getBoolean("enableDebugLogging", BuildConfig.DEVELOPER_MODE); DEBUG = storage.getBoolean("enableDebugLogging", BuildConfig.DEVELOPER_MODE);
DEBUG_SENSITIVE = sprefs.getBoolean("enableSensitiveLogging", false); DEBUG_SENSITIVE = storage.getBoolean("enableSensitiveLogging", false);
mAnimations = sprefs.getBoolean("animations", true); mAnimations = storage.getBoolean("animations", true);
mGesturesEnabled = sprefs.getBoolean("gesturesEnabled", false); mGesturesEnabled = storage.getBoolean("gesturesEnabled", false);
mUseVolumeKeysForNavigation = sprefs.getBoolean("useVolumeKeysForNavigation", false); mUseVolumeKeysForNavigation = storage.getBoolean("useVolumeKeysForNavigation", false);
mUseVolumeKeysForListNavigation = sprefs.getBoolean("useVolumeKeysForListNavigation", false); mUseVolumeKeysForListNavigation = storage.getBoolean("useVolumeKeysForListNavigation", false);
mStartIntegratedInbox = sprefs.getBoolean("startIntegratedInbox", false); mStartIntegratedInbox = storage.getBoolean("startIntegratedInbox", false);
mMeasureAccounts = sprefs.getBoolean("measureAccounts", true); mMeasureAccounts = storage.getBoolean("measureAccounts", true);
mCountSearchMessages = sprefs.getBoolean("countSearchMessages", true); mCountSearchMessages = storage.getBoolean("countSearchMessages", true);
mHideSpecialAccounts = sprefs.getBoolean("hideSpecialAccounts", false); mHideSpecialAccounts = storage.getBoolean("hideSpecialAccounts", false);
mMessageListSenderAboveSubject = sprefs.getBoolean("messageListSenderAboveSubject", false); mMessageListSenderAboveSubject = storage.getBoolean("messageListSenderAboveSubject", false);
mMessageListCheckboxes = sprefs.getBoolean("messageListCheckboxes", false); mMessageListCheckboxes = storage.getBoolean("messageListCheckboxes", false);
mMessageListStars = sprefs.getBoolean("messageListStars", true); mMessageListStars = storage.getBoolean("messageListStars", true);
mMessageListPreviewLines = sprefs.getInt("messageListPreviewLines", 2); mMessageListPreviewLines = storage.getInt("messageListPreviewLines", 2);
mAutofitWidth = sprefs.getBoolean("autofitWidth", true); mAutofitWidth = storage.getBoolean("autofitWidth", true);
mQuietTimeEnabled = sprefs.getBoolean("quietTimeEnabled", false); mQuietTimeEnabled = storage.getBoolean("quietTimeEnabled", false);
mNotificationDuringQuietTimeEnabled = sprefs.getBoolean("notificationDuringQuietTimeEnabled", true); mNotificationDuringQuietTimeEnabled = storage.getBoolean("notificationDuringQuietTimeEnabled", true);
mQuietTimeStarts = sprefs.getString("quietTimeStarts", "21:00"); mQuietTimeStarts = storage.getString("quietTimeStarts", "21:00");
mQuietTimeEnds = sprefs.getString("quietTimeEnds", "7:00"); mQuietTimeEnds = storage.getString("quietTimeEnds", "7:00");
mShowCorrespondentNames = sprefs.getBoolean("showCorrespondentNames", true); mShowCorrespondentNames = storage.getBoolean("showCorrespondentNames", true);
mShowContactName = sprefs.getBoolean("showContactName", false); mShowContactName = storage.getBoolean("showContactName", false);
sShowContactPicture = sprefs.getBoolean("showContactPicture", true); sShowContactPicture = storage.getBoolean("showContactPicture", true);
mChangeContactNameColor = sprefs.getBoolean("changeRegisteredNameColor", false); mChangeContactNameColor = storage.getBoolean("changeRegisteredNameColor", false);
mContactNameColor = sprefs.getInt("registeredNameColor", 0xff00008f); mContactNameColor = storage.getInt("registeredNameColor", 0xff00008f);
mMessageViewFixedWidthFont = sprefs.getBoolean("messageViewFixedWidthFont", false); mMessageViewFixedWidthFont = storage.getBoolean("messageViewFixedWidthFont", false);
mMessageViewReturnToList = sprefs.getBoolean("messageViewReturnToList", false); mMessageViewReturnToList = storage.getBoolean("messageViewReturnToList", false);
mMessageViewShowNext = sprefs.getBoolean("messageViewShowNext", false); mMessageViewShowNext = storage.getBoolean("messageViewShowNext", false);
mWrapFolderNames = sprefs.getBoolean("wrapFolderNames", false); mWrapFolderNames = storage.getBoolean("wrapFolderNames", false);
mHideUserAgent = sprefs.getBoolean("hideUserAgent", false); mHideUserAgent = storage.getBoolean("hideUserAgent", false);
mHideTimeZone = sprefs.getBoolean("hideTimeZone", false); mHideTimeZone = storage.getBoolean("hideTimeZone", false);
mConfirmDelete = sprefs.getBoolean("confirmDelete", false); mConfirmDelete = storage.getBoolean("confirmDelete", false);
mConfirmDiscardMessage = sprefs.getBoolean("confirmDiscardMessage", true); mConfirmDiscardMessage = storage.getBoolean("confirmDiscardMessage", true);
mConfirmDeleteStarred = sprefs.getBoolean("confirmDeleteStarred", false); mConfirmDeleteStarred = storage.getBoolean("confirmDeleteStarred", false);
mConfirmSpam = sprefs.getBoolean("confirmSpam", false); mConfirmSpam = storage.getBoolean("confirmSpam", false);
mConfirmDeleteFromNotification = sprefs.getBoolean("confirmDeleteFromNotification", true); mConfirmDeleteFromNotification = storage.getBoolean("confirmDeleteFromNotification", true);
try { try {
String value = sprefs.getString("sortTypeEnum", Account.DEFAULT_SORT_TYPE.name()); String value = storage.getString("sortTypeEnum", Account.DEFAULT_SORT_TYPE.name());
mSortType = SortType.valueOf(value); mSortType = SortType.valueOf(value);
} catch (Exception e) { } catch (Exception e) {
mSortType = Account.DEFAULT_SORT_TYPE; mSortType = Account.DEFAULT_SORT_TYPE;
} }
boolean sortAscending = sprefs.getBoolean("sortAscending", Account.DEFAULT_SORT_ASCENDING); boolean sortAscending = storage.getBoolean("sortAscending", Account.DEFAULT_SORT_ASCENDING);
mSortAscending.put(mSortType, sortAscending); mSortAscending.put(mSortType, sortAscending);
String notificationHideSubject = sprefs.getString("notificationHideSubject", null); String notificationHideSubject = storage.getString("notificationHideSubject", null);
if (notificationHideSubject == null) { if (notificationHideSubject == null) {
// If the "notificationHideSubject" setting couldn't be found, the app was probably // If the "notificationHideSubject" setting couldn't be found, the app was probably
// updated. Look for the old "keyguardPrivacy" setting and map it to the new enum. // updated. Look for the old "keyguardPrivacy" setting and map it to the new enum.
sNotificationHideSubject = (sprefs.getBoolean("keyguardPrivacy", false)) ? sNotificationHideSubject = (storage.getBoolean("keyguardPrivacy", false)) ?
NotificationHideSubject.WHEN_LOCKED : NotificationHideSubject.NEVER; NotificationHideSubject.WHEN_LOCKED : NotificationHideSubject.NEVER;
} else { } else {
sNotificationHideSubject = NotificationHideSubject.valueOf(notificationHideSubject); sNotificationHideSubject = NotificationHideSubject.valueOf(notificationHideSubject);
} }
String notificationQuickDelete = sprefs.getString("notificationQuickDelete", null); String notificationQuickDelete = storage.getString("notificationQuickDelete", null);
if (notificationQuickDelete != null) { if (notificationQuickDelete != null) {
sNotificationQuickDelete = NotificationQuickDelete.valueOf(notificationQuickDelete); sNotificationQuickDelete = NotificationQuickDelete.valueOf(notificationQuickDelete);
} }
String lockScreenNotificationVisibility = sprefs.getString("lockScreenNotificationVisibility", null); String lockScreenNotificationVisibility = storage.getString("lockScreenNotificationVisibility", null);
if(lockScreenNotificationVisibility != null) { if(lockScreenNotificationVisibility != null) {
sLockScreenNotificationVisibility = LockScreenNotificationVisibility.valueOf(lockScreenNotificationVisibility); sLockScreenNotificationVisibility = LockScreenNotificationVisibility.valueOf(lockScreenNotificationVisibility);
} }
String splitViewMode = sprefs.getString("splitViewMode", null); String splitViewMode = storage.getString("splitViewMode", null);
if (splitViewMode != null) { if (splitViewMode != null) {
sSplitViewMode = SplitViewMode.valueOf(splitViewMode); sSplitViewMode = SplitViewMode.valueOf(splitViewMode);
} }
mAttachmentDefaultPath = sprefs.getString("attachmentdefaultpath", mAttachmentDefaultPath = storage.getString("attachmentdefaultpath",
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()); Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
sUseBackgroundAsUnreadIndicator = sprefs.getBoolean("useBackgroundAsUnreadIndicator", true); sUseBackgroundAsUnreadIndicator = storage.getBoolean("useBackgroundAsUnreadIndicator", true);
sThreadedViewEnabled = sprefs.getBoolean("threadedView", true); sThreadedViewEnabled = storage.getBoolean("threadedView", true);
fontSizes.load(sprefs); fontSizes.load(storage);
try { try {
setBackgroundOps(BACKGROUND_OPS.valueOf(sprefs.getString( setBackgroundOps(BACKGROUND_OPS.valueOf(storage.getString(
"backgroundOperations", "backgroundOperations",
BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC.name()))); BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC.name())));
} catch (Exception e) { } catch (Exception e) {
setBackgroundOps(BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC); setBackgroundOps(BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC);
} }
sColorizeMissingContactPictures = sprefs.getBoolean("colorizeMissingContactPictures", true); sColorizeMissingContactPictures = storage.getBoolean("colorizeMissingContactPictures", true);
sMessageViewArchiveActionVisible = sprefs.getBoolean("messageViewArchiveActionVisible", false); sMessageViewArchiveActionVisible = storage.getBoolean("messageViewArchiveActionVisible", false);
sMessageViewDeleteActionVisible = sprefs.getBoolean("messageViewDeleteActionVisible", true); sMessageViewDeleteActionVisible = storage.getBoolean("messageViewDeleteActionVisible", true);
sMessageViewMoveActionVisible = sprefs.getBoolean("messageViewMoveActionVisible", false); sMessageViewMoveActionVisible = storage.getBoolean("messageViewMoveActionVisible", false);
sMessageViewCopyActionVisible = sprefs.getBoolean("messageViewCopyActionVisible", false); sMessageViewCopyActionVisible = storage.getBoolean("messageViewCopyActionVisible", false);
sMessageViewSpamActionVisible = sprefs.getBoolean("messageViewSpamActionVisible", false); sMessageViewSpamActionVisible = storage.getBoolean("messageViewSpamActionVisible", false);
K9.setK9Language(sprefs.getString("language", "")); K9.setK9Language(storage.getString("language", ""));
int themeValue = sprefs.getInt("theme", Theme.LIGHT.ordinal()); int themeValue = storage.getInt("theme", Theme.LIGHT.ordinal());
// We used to save the resource ID of the theme. So convert that to the new format if // We used to save the resource ID of the theme. So convert that to the new format if
// necessary. // necessary.
if (themeValue == Theme.DARK.ordinal() || themeValue == android.R.style.Theme) { if (themeValue == Theme.DARK.ordinal() || themeValue == android.R.style.Theme) {
@ -765,11 +758,11 @@ public class K9 extends Application {
K9.setK9Theme(Theme.LIGHT); K9.setK9Theme(Theme.LIGHT);
} }
themeValue = sprefs.getInt("messageViewTheme", Theme.USE_GLOBAL.ordinal()); themeValue = storage.getInt("messageViewTheme", Theme.USE_GLOBAL.ordinal());
K9.setK9MessageViewThemeSetting(Theme.values()[themeValue]); K9.setK9MessageViewThemeSetting(Theme.values()[themeValue]);
themeValue = sprefs.getInt("messageComposeTheme", Theme.USE_GLOBAL.ordinal()); themeValue = storage.getInt("messageComposeTheme", Theme.USE_GLOBAL.ordinal());
K9.setK9ComposerThemeSetting(Theme.values()[themeValue]); K9.setK9ComposerThemeSetting(Theme.values()[themeValue]);
K9.setUseFixedMessageViewTheme(sprefs.getBoolean("fixedMessageViewTheme", true)); K9.setUseFixedMessageViewTheme(storage.getBoolean("fixedMessageViewTheme", true));
} }
/** /**

View file

@ -10,12 +10,11 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log; import android.util.Log;
import com.fsck.k9.mail.store.RemoteStore; import com.fsck.k9.mail.store.RemoteStore;
import com.fsck.k9.mailstore.LocalStore; import com.fsck.k9.mailstore.LocalStore;
import com.fsck.k9.preferences.Editor; import com.fsck.k9.preferences.StorageEditor;
import com.fsck.k9.preferences.Storage; import com.fsck.k9.preferences.Storage;
public class Preferences { public class Preferences {
@ -42,7 +41,7 @@ public class Preferences {
mContext = context; mContext = context;
if (mStorage.isEmpty()) { if (mStorage.isEmpty()) {
Log.i(K9.LOG_TAG, "Preferences storage is zero-size, importing from Android-style preferences"); Log.i(K9.LOG_TAG, "Preferences storage is zero-size, importing from Android-style preferences");
Editor editor = mStorage.edit(); StorageEditor editor = mStorage.edit();
editor.copy(context.getSharedPreferences("AndroidMail.Main", Context.MODE_PRIVATE)); editor.copy(context.getSharedPreferences("AndroidMail.Main", Context.MODE_PRIVATE));
editor.commit(); editor.commit();
} }
@ -51,7 +50,7 @@ public class Preferences {
public synchronized void loadAccounts() { public synchronized void loadAccounts() {
accounts = new HashMap<String, Account>(); accounts = new HashMap<String, Account>();
accountsInOrder = new LinkedList<Account>(); accountsInOrder = new LinkedList<Account>();
String accountUuids = getPreferences().getString("accountUuids", null); String accountUuids = getStorage().getString("accountUuids", null);
if ((accountUuids != null) && (accountUuids.length() != 0)) { if ((accountUuids != null) && (accountUuids.length() != 0)) {
String[] uuids = accountUuids.split(","); String[] uuids = accountUuids.split(",");
for (String uuid : uuids) { for (String uuid : uuids) {
@ -145,7 +144,7 @@ public class Preferences {
* there are no accounts on the system the method returns null. * there are no accounts on the system the method returns null.
*/ */
public Account getDefaultAccount() { public Account getDefaultAccount() {
String defaultAccountUuid = getPreferences().getString("defaultAccountUuid", null); String defaultAccountUuid = getStorage().getString("defaultAccountUuid", null);
Account defaultAccount = getAccount(defaultAccountUuid); Account defaultAccount = getAccount(defaultAccountUuid);
if (defaultAccount == null) { if (defaultAccount == null) {
@ -160,15 +159,15 @@ public class Preferences {
} }
public void setDefaultAccount(Account account) { public void setDefaultAccount(Account account) {
getPreferences().edit().putString("defaultAccountUuid", account.getUuid()).commit(); getStorage().edit().putString("defaultAccountUuid", account.getUuid()).commit();
} }
public SharedPreferences getPreferences() { public Storage getStorage() {
return mStorage; return mStorage;
} }
public static <T extends Enum<T>> T getEnumStringPref(SharedPreferences prefs, String key, T defaultEnum) { public static <T extends Enum<T>> T getEnumStringPref(Storage storage, String key, T defaultEnum) {
String stringPref = prefs.getString(key, null); String stringPref = storage.getString(key, null);
if (stringPref == null) { if (stringPref == null) {
return defaultEnum; return defaultEnum;

View file

@ -8,7 +8,6 @@ import android.app.ActionBar;
import android.app.SearchManager; import android.app.SearchManager;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration; import android.content.res.Configuration;
import android.net.Uri; import android.net.Uri;
import android.os.Build; import android.os.Build;
@ -42,6 +41,7 @@ import com.fsck.k9.activity.setup.Prefs;
import com.fsck.k9.crypto.PgpData; import com.fsck.k9.crypto.PgpData;
import com.fsck.k9.fragment.MessageListFragment; import com.fsck.k9.fragment.MessageListFragment;
import com.fsck.k9.fragment.MessageListFragment.MessageListFragmentListener; import com.fsck.k9.fragment.MessageListFragment.MessageListFragmentListener;
import com.fsck.k9.preferences.StorageEditor;
import com.fsck.k9.ui.messageview.MessageViewFragment; import com.fsck.k9.ui.messageview.MessageViewFragment;
import com.fsck.k9.ui.messageview.MessageViewFragment.MessageViewFragmentListener; import com.fsck.k9.ui.messageview.MessageViewFragment.MessageViewFragmentListener;
import com.fsck.k9.mailstore.StorageManager; import com.fsck.k9.mailstore.StorageManager;
@ -1530,7 +1530,7 @@ public class MessageList extends K9Activity implements MessageListFragmentListen
public void run() { public void run() {
Context appContext = getApplicationContext(); Context appContext = getApplicationContext();
Preferences prefs = Preferences.getPreferences(appContext); Preferences prefs = Preferences.getPreferences(appContext);
Editor editor = prefs.getPreferences().edit(); StorageEditor editor = prefs.getStorage().edit();
K9.save(editor); K9.save(editor);
editor.commit(); editor.commit();
} }

View file

@ -2,12 +2,13 @@ package com.fsck.k9.activity.setup;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle; import android.os.Bundle;
import android.preference.*; import android.preference.*;
import com.fsck.k9.*; import com.fsck.k9.*;
import com.fsck.k9.activity.K9PreferenceActivity; import com.fsck.k9.activity.K9PreferenceActivity;
import com.fsck.k9.preferences.Storage;
import com.fsck.k9.preferences.StorageEditor;
/** /**
* Activity to configure the font size of the information displayed in the * Activity to configure the font size of the information displayed in the
@ -178,8 +179,8 @@ public class FontSizeSettings extends K9PreferenceActivity {
fontSizes.setMessageComposeInput(Integer.parseInt(mMessageComposeInput.getValue())); fontSizes.setMessageComposeInput(Integer.parseInt(mMessageComposeInput.getValue()));
SharedPreferences preferences = Preferences.getPreferences(this).getPreferences(); Storage storage = Preferences.getPreferences(this).getStorage();
Editor editor = preferences.edit(); StorageEditor editor = storage.edit();
fontSizes.save(editor); fontSizes.save(editor);
editor.commit(); editor.commit();
} }

View file

@ -9,8 +9,6 @@ import java.util.Set;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.preference.CheckBoxPreference; import android.preference.CheckBoxPreference;
@ -29,11 +27,12 @@ import com.fsck.k9.Preferences;
import com.fsck.k9.R; import com.fsck.k9.R;
import com.fsck.k9.activity.ColorPickerDialog; import com.fsck.k9.activity.ColorPickerDialog;
import com.fsck.k9.activity.K9PreferenceActivity; import com.fsck.k9.activity.K9PreferenceActivity;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.helper.FileBrowserHelper; import com.fsck.k9.helper.FileBrowserHelper;
import com.fsck.k9.helper.FileBrowserHelper.FileBrowserFailOverCallback; import com.fsck.k9.helper.FileBrowserHelper.FileBrowserFailOverCallback;
import com.fsck.k9.notification.NotificationController; import com.fsck.k9.notification.NotificationController;
import com.fsck.k9.preferences.CheckBoxListPreference; import com.fsck.k9.preferences.CheckBoxListPreference;
import com.fsck.k9.preferences.Storage;
import com.fsck.k9.preferences.StorageEditor;
import com.fsck.k9.preferences.TimePickerPreference; import com.fsck.k9.preferences.TimePickerPreference;
import com.fsck.k9.service.MailService; import com.fsck.k9.service.MailService;
@ -443,7 +442,7 @@ public class Prefs extends K9PreferenceActivity {
} }
private void saveSettings() { private void saveSettings() {
SharedPreferences preferences = Preferences.getPreferences(this).getPreferences(); Storage storage = Preferences.getPreferences(this).getStorage();
K9.setK9Language(mLanguage.getValue()); K9.setK9Language(mLanguage.getValue());
@ -522,7 +521,7 @@ public class Prefs extends K9PreferenceActivity {
K9.setHideUserAgent(mHideUserAgent.isChecked()); K9.setHideUserAgent(mHideUserAgent.isChecked());
K9.setHideTimeZone(mHideTimeZone.isChecked()); K9.setHideTimeZone(mHideTimeZone.isChecked());
Editor editor = preferences.edit(); StorageEditor editor = storage.edit();
K9.save(editor); K9.save(editor);
editor.commit(); editor.commit();

View file

@ -26,7 +26,6 @@ import android.content.CursorLoader;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.content.Loader; import android.content.Loader;
import android.content.SharedPreferences.Editor;
import android.database.Cursor; import android.database.Cursor;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.Rect; import android.graphics.Rect;
@ -93,6 +92,7 @@ import com.fsck.k9.mailstore.DatabasePreviewType;
import com.fsck.k9.mailstore.LocalFolder; import com.fsck.k9.mailstore.LocalFolder;
import com.fsck.k9.mailstore.LocalMessage; import com.fsck.k9.mailstore.LocalMessage;
import com.fsck.k9.mailstore.LocalStore; import com.fsck.k9.mailstore.LocalStore;
import com.fsck.k9.preferences.StorageEditor;
import com.fsck.k9.provider.EmailProvider; import com.fsck.k9.provider.EmailProvider;
import com.fsck.k9.provider.EmailProvider.MessageColumns; import com.fsck.k9.provider.EmailProvider.MessageColumns;
import com.fsck.k9.provider.EmailProvider.SpecialColumns; import com.fsck.k9.provider.EmailProvider.SpecialColumns;
@ -1269,7 +1269,7 @@ public class MessageListFragment extends Fragment implements OnItemClickListener
K9.setSortAscending(mSortType, mSortAscending); K9.setSortAscending(mSortType, mSortAscending);
mSortDateAscending = K9.isSortAscending(SortType.SORT_DATE); mSortDateAscending = K9.isSortAscending(SortType.SORT_DATE);
Editor editor = mPreferences.getPreferences().edit(); StorageEditor editor = mPreferences.getStorage().edit();
K9.save(editor); K9.save(editor);
editor.commit(); editor.commit();
} }

View file

@ -23,7 +23,6 @@ import java.util.Stack;
import java.util.UUID; import java.util.UUID;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.util.Log; import android.util.Log;
@ -57,6 +56,8 @@ import com.fsck.k9.mailstore.LockableDatabase.WrappedException;
import com.fsck.k9.message.preview.MessagePreviewCreator; import com.fsck.k9.message.preview.MessagePreviewCreator;
import com.fsck.k9.message.preview.PreviewResult; import com.fsck.k9.message.preview.PreviewResult;
import com.fsck.k9.message.preview.PreviewResult.PreviewType; import com.fsck.k9.message.preview.PreviewResult.PreviewType;
import com.fsck.k9.preferences.Storage;
import com.fsck.k9.preferences.StorageEditor;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.james.mime4j.util.MimeUtil; import org.apache.james.mime4j.util.MimeUtil;
@ -542,7 +543,7 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
public void delete() throws MessagingException { public void delete() throws MessagingException {
String id = getPrefId(); String id = getPrefId();
SharedPreferences.Editor editor = this.localStore.getPreferences().edit(); StorageEditor editor = this.localStore.getStorage().edit();
editor.remove(id + ".displayMode"); editor.remove(id + ".displayMode");
editor.remove(id + ".syncMode"); editor.remove(id + ".syncMode");
@ -554,12 +555,12 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
} }
public void save() throws MessagingException { public void save() throws MessagingException {
SharedPreferences.Editor editor = this.localStore.getPreferences().edit(); StorageEditor editor = this.localStore.getStorage().edit();
save(editor); save(editor);
editor.commit(); editor.commit();
} }
public void save(SharedPreferences.Editor editor) throws MessagingException { public void save(StorageEditor editor) throws MessagingException {
String id = getPrefId(); String id = getPrefId();
// there can be a lot of folders. For the defaults, let's not save prefs, saving space, except for INBOX // there can be a lot of folders. For the defaults, let's not save prefs, saving space, except for INBOX
@ -595,10 +596,10 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
public void refresh(String name, PreferencesHolder prefHolder) { public void refresh(String name, PreferencesHolder prefHolder) {
String id = getPrefId(name); String id = getPrefId(name);
SharedPreferences preferences = this.localStore.getPreferences(); Storage storage = this.localStore.getStorage();
try { try {
prefHolder.displayClass = FolderClass.valueOf(preferences.getString(id + ".displayMode", prefHolder.displayClass = FolderClass.valueOf(storage.getString(id + ".displayMode",
prefHolder.displayClass.name())); prefHolder.displayClass.name()));
} catch (Exception e) { } catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to load displayMode for " + getName(), e); Log.e(K9.LOG_TAG, "Unable to load displayMode for " + getName(), e);
@ -608,7 +609,7 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
} }
try { try {
prefHolder.syncClass = FolderClass.valueOf(preferences.getString(id + ".syncMode", prefHolder.syncClass = FolderClass.valueOf(storage.getString(id + ".syncMode",
prefHolder.syncClass.name())); prefHolder.syncClass.name()));
} catch (Exception e) { } catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to load syncMode for " + getName(), e); Log.e(K9.LOG_TAG, "Unable to load syncMode for " + getName(), e);
@ -619,7 +620,7 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
} }
try { try {
prefHolder.notifyClass = FolderClass.valueOf(preferences.getString(id + ".notifyMode", prefHolder.notifyClass = FolderClass.valueOf(storage.getString(id + ".notifyMode",
prefHolder.notifyClass.name())); prefHolder.notifyClass.name()));
} catch (Exception e) { } catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to load notifyMode for " + getName(), e); Log.e(K9.LOG_TAG, "Unable to load notifyMode for " + getName(), e);
@ -629,7 +630,7 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
} }
try { try {
prefHolder.pushClass = FolderClass.valueOf(preferences.getString(id + ".pushMode", prefHolder.pushClass = FolderClass.valueOf(storage.getString(id + ".pushMode",
prefHolder.pushClass.name())); prefHolder.pushClass.name()));
} catch (Exception e) { } catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to load pushMode for " + getName(), e); Log.e(K9.LOG_TAG, "Unable to load pushMode for " + getName(), e);
@ -637,8 +638,8 @@ public class LocalFolder extends Folder<LocalMessage> implements Serializable {
if (prefHolder.pushClass == FolderClass.NONE) { if (prefHolder.pushClass == FolderClass.NONE) {
prefHolder.pushClass = FolderClass.INHERITED; prefHolder.pushClass = FolderClass.INHERITED;
} }
prefHolder.inTopGroup = preferences.getBoolean(id + ".inTopGroup", prefHolder.inTopGroup); prefHolder.inTopGroup = storage.getBoolean(id + ".inTopGroup", prefHolder.inTopGroup);
prefHolder.integrate = preferences.getBoolean(id + ".integrate", prefHolder.integrate); prefHolder.integrate = storage.getBoolean(id + ".integrate", prefHolder.integrate);
} }
@Override @Override

View file

@ -4,7 +4,6 @@ package com.fsck.k9.mailstore;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.net.Uri; import android.net.Uri;
@ -26,6 +25,7 @@ import com.fsck.k9.mailstore.StorageManager.StorageProvider;
import com.fsck.k9.mailstore.LockableDatabase.DbCallback; import com.fsck.k9.mailstore.LockableDatabase.DbCallback;
import com.fsck.k9.mailstore.LockableDatabase.WrappedException; import com.fsck.k9.mailstore.LockableDatabase.WrappedException;
import com.fsck.k9.message.preview.MessagePreviewCreator; import com.fsck.k9.message.preview.MessagePreviewCreator;
import com.fsck.k9.preferences.Storage;
import com.fsck.k9.provider.EmailProvider; import com.fsck.k9.provider.EmailProvider;
import com.fsck.k9.provider.EmailProvider.MessageColumns; import com.fsck.k9.provider.EmailProvider.MessageColumns;
import com.fsck.k9.search.LocalSearch; import com.fsck.k9.search.LocalSearch;
@ -236,8 +236,8 @@ public class LocalStore extends Store implements Serializable {
return mAccount; return mAccount;
} }
protected SharedPreferences getPreferences() { protected Storage getStorage() {
return Preferences.getPreferences(context).getPreferences(); return Preferences.getPreferences(context).getStorage();
} }
public long getSize() throws MessagingException { public long getSize() throws MessagingException {

View file

@ -10,7 +10,6 @@ import java.util.Locale;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteException;
@ -32,6 +31,8 @@ import com.fsck.k9.mail.internet.MimeHeader;
import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mailstore.LocalFolder.DataLocation; import com.fsck.k9.mailstore.LocalFolder.DataLocation;
import com.fsck.k9.mailstore.LocalFolder.MessagePartType; import com.fsck.k9.mailstore.LocalFolder.MessagePartType;
import com.fsck.k9.preferences.Storage;
import com.fsck.k9.preferences.StorageEditor;
import org.apache.james.mime4j.codec.QuotedPrintableOutputStream; import org.apache.james.mime4j.codec.QuotedPrintableOutputStream;
import org.apache.james.mime4j.util.MimeUtil; import org.apache.james.mime4j.util.MimeUtil;
@ -1033,13 +1034,13 @@ class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition {
private static void db41UpdateFolderMetadata(SQLiteDatabase db, LocalStore localStore) { private static void db41UpdateFolderMetadata(SQLiteDatabase db, LocalStore localStore) {
Cursor cursor = null; Cursor cursor = null;
try { try {
SharedPreferences prefs = localStore.getPreferences(); Storage storage = localStore.getStorage();
cursor = db.rawQuery("SELECT id, name FROM folders", null); cursor = db.rawQuery("SELECT id, name FROM folders", null);
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
try { try {
int id = cursor.getInt(0); int id = cursor.getInt(0);
String name = cursor.getString(1); String name = cursor.getString(1);
update41Metadata(db, localStore, prefs, id, name); update41Metadata(db, localStore, storage, id, name);
} catch (Exception e) { } catch (Exception e) {
Log.e(K9.LOG_TAG, " error trying to ugpgrade a folder class", e); Log.e(K9.LOG_TAG, " error trying to ugpgrade a folder class", e);
} }
@ -1051,7 +1052,7 @@ class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition {
} }
} }
private static void update41Metadata(SQLiteDatabase db, LocalStore localStore, SharedPreferences prefs, private static void update41Metadata(SQLiteDatabase db, LocalStore localStore, Storage storage,
int id, String name) { int id, String name) {
Folder.FolderClass displayClass = Folder.FolderClass.NO_CLASS; Folder.FolderClass displayClass = Folder.FolderClass.NO_CLASS;
@ -1068,11 +1069,11 @@ class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition {
} }
try { try {
displayClass = Folder.FolderClass.valueOf(prefs.getString(localStore.uUid + "." + name + ".displayMode", displayClass.name())); displayClass = Folder.FolderClass.valueOf(storage.getString(localStore.uUid + "." + name + ".displayMode", displayClass.name()));
syncClass = Folder.FolderClass.valueOf(prefs.getString(localStore.uUid + "." + name + ".syncMode", syncClass.name())); syncClass = Folder.FolderClass.valueOf(storage.getString(localStore.uUid + "." + name + ".syncMode", syncClass.name()));
pushClass = Folder.FolderClass.valueOf(prefs.getString(localStore.uUid + "." + name + ".pushMode", pushClass.name())); pushClass = Folder.FolderClass.valueOf(storage.getString(localStore.uUid + "." + name + ".pushMode", pushClass.name()));
inTopGroup = prefs.getBoolean(localStore.uUid + "." + name + ".inTopGroup", inTopGroup); inTopGroup = storage.getBoolean(localStore.uUid + "." + name + ".inTopGroup", inTopGroup);
integrate = prefs.getBoolean(localStore.uUid + "." + name + ".integrate", integrate); integrate = storage.getBoolean(localStore.uUid + "." + name + ".integrate", integrate);
} catch (Exception e) { } catch (Exception e) {
Log.e(K9.LOG_TAG, " Throwing away an error while trying to upgrade folder metadata", e); Log.e(K9.LOG_TAG, " Throwing away an error while trying to upgrade folder metadata", e);
} }
@ -1109,7 +1110,7 @@ class StoreSchemaDefinition implements LockableDatabase.SchemaDefinition {
private static void db42From41MoveFolderPreferences(LocalStore localStore) { private static void db42From41MoveFolderPreferences(LocalStore localStore) {
try { try {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
SharedPreferences.Editor editor = localStore.getPreferences().edit(); StorageEditor editor = localStore.getStorage().edit();
List<? extends Folder > folders = localStore.getPersonalNamespaces(true); List<? extends Folder > folders = localStore.getPersonalNamespaces(true);
for (Folder folder : folders) { for (Folder folder : folders) {

View file

@ -7,7 +7,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
import android.content.SharedPreferences;
import com.fsck.k9.Account; import com.fsck.k9.Account;
import com.fsck.k9.Account.DeletePolicy; import com.fsck.k9.Account.DeletePolicy;
import com.fsck.k9.Account.Expunge; import com.fsck.k9.Account.Expunge;
@ -245,7 +244,7 @@ public class AccountSettings {
return Settings.convert(settings, SETTINGS); return Settings.convert(settings, SETTINGS);
} }
public static Map<String, String> getAccountSettings(SharedPreferences storage, String uuid) { public static Map<String, String> getAccountSettings(Storage storage, String uuid) {
Map<String, String> result = new HashMap<String, String>(); Map<String, String> result = new HashMap<String, String>();
String prefix = uuid + "."; String prefix = uuid + ".";
for (String key : SETTINGS.keySet()) { for (String key : SETTINGS.keySet()) {

View file

@ -7,8 +7,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
import android.content.SharedPreferences;
import com.fsck.k9.mail.Folder.FolderClass; import com.fsck.k9.mail.Folder.FolderClass;
import com.fsck.k9.preferences.Settings.*; import com.fsck.k9.preferences.Settings.*;
@ -63,7 +61,7 @@ public class FolderSettings {
return Settings.convert(settings, SETTINGS); return Settings.convert(settings, SETTINGS);
} }
public static Map<String, String> getFolderSettings(SharedPreferences storage, String uuid, public static Map<String, String> getFolderSettings(Storage storage, String uuid,
String folderName) { String folderName) {
Map<String, String> result = new HashMap<String, String>(); Map<String, String> result = new HashMap<String, String>();
String prefix = uuid + "." + folderName + "."; String prefix = uuid + "." + folderName + ".";

View file

@ -10,7 +10,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
import android.content.SharedPreferences;
import android.os.Environment; import android.os.Environment;
import com.fsck.k9.Account; import com.fsck.k9.Account;
@ -297,7 +296,7 @@ public class GlobalSettings {
return Settings.convert(settings, SETTINGS); return Settings.convert(settings, SETTINGS);
} }
public static Map<String, String> getGlobalSettings(SharedPreferences storage) { public static Map<String, String> getGlobalSettings(Storage storage) {
Map<String, String> result = new HashMap<String, String>(); Map<String, String> result = new HashMap<String, String>();
for (String key : SETTINGS.keySet()) { for (String key : SETTINGS.keySet()) {
String value = storage.getString(key, null); String value = storage.getString(key, null);

View file

@ -7,8 +7,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
import android.content.SharedPreferences;
import com.fsck.k9.EmailAddressValidator; import com.fsck.k9.EmailAddressValidator;
import com.fsck.k9.K9; import com.fsck.k9.K9;
import com.fsck.k9.R; import com.fsck.k9.R;
@ -56,7 +54,7 @@ public class IdentitySettings {
return Settings.convert(settings, SETTINGS); return Settings.convert(settings, SETTINGS);
} }
public static Map<String, String> getIdentitySettings(SharedPreferences storage, String uuid, public static Map<String, String> getIdentitySettings(Storage storage, String uuid,
int identityIndex) { int identityIndex) {
Map<String, String> result = new HashMap<String, String>(); Map<String, String> result = new HashMap<String, String>();
String prefix = uuid + "."; String prefix = uuid + ".";

View file

@ -17,7 +17,6 @@ import com.fsck.k9.helper.FileHelper;
import org.xmlpull.v1.XmlSerializer; import org.xmlpull.v1.XmlSerializer;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment; import android.os.Environment;
import android.util.Log; import android.util.Log;
import android.util.Xml; import android.util.Xml;
@ -129,7 +128,7 @@ public class SettingsExporter {
Log.i(K9.LOG_TAG, "Exporting preferences"); Log.i(K9.LOG_TAG, "Exporting preferences");
Preferences preferences = Preferences.getPreferences(context); Preferences preferences = Preferences.getPreferences(context);
SharedPreferences storage = preferences.getPreferences(); Storage storage = preferences.getStorage();
Set<String> exportAccounts; Set<String> exportAccounts;
if (accountUuids == null) { if (accountUuids == null) {

View file

@ -184,11 +184,11 @@ public class SettingsImporter {
Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false);
Preferences preferences = Preferences.getPreferences(context); Preferences preferences = Preferences.getPreferences(context);
SharedPreferences storage = preferences.getPreferences(); Storage storage = preferences.getStorage();
if (globalSettings) { if (globalSettings) {
try { try {
SharedPreferences.Editor editor = storage.edit(); StorageEditor editor = storage.edit();
if (imported.globalSettings != null) { if (imported.globalSettings != null) {
importGlobalSettings(storage, editor, imported.contentVersion, importGlobalSettings(storage, editor, imported.contentVersion,
imported.globalSettings); imported.globalSettings);
@ -218,7 +218,7 @@ public class SettingsImporter {
if (imported.accounts.containsKey(accountUuid)) { if (imported.accounts.containsKey(accountUuid)) {
ImportedAccount account = imported.accounts.get(accountUuid); ImportedAccount account = imported.accounts.get(accountUuid);
try { try {
SharedPreferences.Editor editor = storage.edit(); StorageEditor editor = storage.edit();
AccountDescriptionPair importResult = importAccount(context, AccountDescriptionPair importResult = importAccount(context,
editor, imported.contentVersion, account, overwrite); editor, imported.contentVersion, account, overwrite);
@ -276,7 +276,7 @@ public class SettingsImporter {
} }
} }
SharedPreferences.Editor editor = storage.edit(); StorageEditor editor = storage.edit();
String defaultAccountUuid = storage.getString("defaultAccountUuid", null); String defaultAccountUuid = storage.getString("defaultAccountUuid", null);
if (defaultAccountUuid == null) { if (defaultAccountUuid == null) {
@ -304,8 +304,8 @@ public class SettingsImporter {
} }
} }
private static void importGlobalSettings(SharedPreferences storage, private static void importGlobalSettings(Storage storage,
SharedPreferences.Editor editor, int contentVersion, ImportedSettings settings) { StorageEditor editor, int contentVersion, ImportedSettings settings) {
// Validate global settings // Validate global settings
Map<String, Object> validatedSettings = GlobalSettings.validate(contentVersion, Map<String, Object> validatedSettings = GlobalSettings.validate(contentVersion,
@ -333,7 +333,7 @@ public class SettingsImporter {
} }
private static AccountDescriptionPair importAccount(Context context, private static AccountDescriptionPair importAccount(Context context,
SharedPreferences.Editor editor, int contentVersion, ImportedAccount account, StorageEditor editor, int contentVersion, ImportedAccount account,
boolean overwrite) throws InvalidSettingValueException { boolean overwrite) throws InvalidSettingValueException {
AccountDescription original = new AccountDescription(account.name, account.uuid); AccountDescription original = new AccountDescription(account.name, account.uuid);
@ -431,7 +431,7 @@ public class SettingsImporter {
Map<String, String> writeSettings; Map<String, String> writeSettings;
if (mergeImportedAccount) { if (mergeImportedAccount) {
writeSettings = new HashMap<String, String>( writeSettings = new HashMap<String, String>(
AccountSettings.getAccountSettings(prefs.getPreferences(), uuid)); AccountSettings.getAccountSettings(prefs.getStorage(), uuid));
writeSettings.putAll(stringSettings); writeSettings.putAll(stringSettings);
} else { } else {
writeSettings = stringSettings; writeSettings = stringSettings;
@ -472,7 +472,7 @@ public class SettingsImporter {
return new AccountDescriptionPair(original, imported, mergeImportedAccount); return new AccountDescriptionPair(original, imported, mergeImportedAccount);
} }
private static void importFolder(SharedPreferences.Editor editor, int contentVersion, private static void importFolder(StorageEditor editor, int contentVersion,
String uuid, ImportedFolder folder, boolean overwrite, Preferences prefs) { String uuid, ImportedFolder folder, boolean overwrite, Preferences prefs) {
// Validate folder settings // Validate folder settings
@ -490,7 +490,7 @@ public class SettingsImporter {
// Merge folder settings if necessary // Merge folder settings if necessary
Map<String, String> writeSettings; Map<String, String> writeSettings;
if (overwrite) { if (overwrite) {
writeSettings = FolderSettings.getFolderSettings(prefs.getPreferences(), writeSettings = FolderSettings.getFolderSettings(prefs.getStorage(),
uuid, folder.name); uuid, folder.name);
writeSettings.putAll(stringSettings); writeSettings.putAll(stringSettings);
} else { } else {
@ -506,7 +506,7 @@ public class SettingsImporter {
} }
} }
private static void importIdentities(SharedPreferences.Editor editor, int contentVersion, private static void importIdentities(StorageEditor editor, int contentVersion,
String uuid, ImportedAccount account, boolean overwrite, Account existingAccount, String uuid, ImportedAccount account, boolean overwrite, Account existingAccount,
Preferences prefs) throws InvalidSettingValueException { Preferences prefs) throws InvalidSettingValueException {
@ -588,7 +588,7 @@ public class SettingsImporter {
Map<String, String> writeSettings; Map<String, String> writeSettings;
if (mergeSettings) { if (mergeSettings) {
writeSettings = new HashMap<String, String>(IdentitySettings.getIdentitySettings( writeSettings = new HashMap<String, String>(IdentitySettings.getIdentitySettings(
prefs.getPreferences(), uuid, writeIdentityIndex)); prefs.getStorage(), uuid, writeIdentityIndex));
writeSettings.putAll(stringSettings); writeSettings.putAll(stringSettings);
} else { } else {
writeSettings = stringSettings; writeSettings = stringSettings;
@ -649,7 +649,7 @@ public class SettingsImporter {
* @param value * @param value
* The new value for the preference. * The new value for the preference.
*/ */
private static void putString(SharedPreferences.Editor editor, String key, String value) { private static void putString(StorageEditor editor, String key, String value) {
if (K9.DEBUG) { if (K9.DEBUG) {
String outputValue = value; String outputValue = value;
if (!K9.DEBUG_SENSITIVE && if (!K9.DEBUG_SENSITIVE &&

View file

@ -2,7 +2,6 @@ package com.fsck.k9.preferences;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement; import android.database.sqlite.SQLiteStatement;
@ -17,20 +16,15 @@ import java.net.URI;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class Storage implements SharedPreferences { public class Storage {
private static ConcurrentMap<Context, Storage> storages = private static ConcurrentMap<Context, Storage> storages =
new ConcurrentHashMap<Context, Storage>(); new ConcurrentHashMap<Context, Storage>();
private volatile ConcurrentMap<String, String> storage = new ConcurrentHashMap<String, String>(); private volatile ConcurrentMap<String, String> storage = new ConcurrentHashMap<String, String>();
private CopyOnWriteArrayList<OnSharedPreferenceChangeListener> listeners =
new CopyOnWriteArrayList<OnSharedPreferenceChangeListener>();
private int DB_VERSION = 2; private int DB_VERSION = 2;
private String DB_NAME = "preferences_storage"; private String DB_NAME = "preferences_storage";
@ -210,13 +204,7 @@ public class Storage implements SharedPreferences {
} }
} }
protected void put(String key, String value) { void put(Map<String, String> insertables) {
ContentValues cv = generateCV(key, value);
workingDB.get().insert("preferences_storage", "primkey", cv);
liveUpdate(key, value);
}
protected void put(Map<String, String> insertables) {
String sql = "INSERT INTO preferences_storage (primkey, value) VALUES (?, ?)"; String sql = "INSERT INTO preferences_storage (primkey, value) VALUES (?, ?)";
SQLiteStatement stmt = workingDB.get().compileStatement(sql); SQLiteStatement stmt = workingDB.get().compileStatement(sql);
@ -232,35 +220,20 @@ public class Storage implements SharedPreferences {
stmt.close(); stmt.close();
} }
private ContentValues generateCV(String key, String value) {
ContentValues cv = new ContentValues();
cv.put("primkey", key);
cv.put("value", value);
return cv;
}
private void liveUpdate(String key, String value) { private void liveUpdate(String key, String value) {
workingStorage.get().put(key, value); workingStorage.get().put(key, value);
keyChange(key); keyChange(key);
} }
protected void remove(String key) { void remove(String key) {
workingDB.get().delete("preferences_storage", "primkey = ?", new String[] { key }); workingDB.get().delete("preferences_storage", "primkey = ?", new String[] { key });
workingStorage.get().remove(key); workingStorage.get().remove(key);
keyChange(key); keyChange(key);
} }
protected void removeAll() { void doInTransaction(Runnable dbWork) {
for (String key : workingStorage.get().keySet()) {
keyChange(key);
}
workingDB.get().execSQL("DELETE FROM preferences_storage");
workingStorage.get().clear();
}
protected void doInTransaction(Runnable dbWork) {
ConcurrentMap<String, String> newStorage = new ConcurrentHashMap<String, String>(); ConcurrentMap<String, String> newStorage = new ConcurrentHashMap<String, String>();
newStorage.putAll(storage); newStorage.putAll(storage);
workingStorage.set(newStorage); workingStorage.set(newStorage);
@ -276,11 +249,6 @@ public class Storage implements SharedPreferences {
dbWork.run(); dbWork.run();
mDb.setTransactionSuccessful(); mDb.setTransactionSuccessful();
storage = newStorage; storage = newStorage;
for (String changedKey : changedKeys) {
for (OnSharedPreferenceChangeListener listener : listeners) {
listener.onSharedPreferenceChanged(this, changedKey);
}
}
} finally { } finally {
workingDB.remove(); workingDB.remove();
workingStorage.remove(); workingStorage.remove();
@ -294,7 +262,6 @@ public class Storage implements SharedPreferences {
return storage.isEmpty(); return storage.isEmpty();
} }
//@Override
public boolean contains(String key) { public boolean contains(String key) {
// TODO this used to be ConcurrentHashMap#contains which is // TODO this used to be ConcurrentHashMap#contains which is
// actually containsValue. But looking at the usage of this method, // actually containsValue. But looking at the usage of this method,
@ -303,17 +270,14 @@ public class Storage implements SharedPreferences {
return storage.containsKey(key); return storage.containsKey(key);
} }
//@Override public StorageEditor edit() {
public com.fsck.k9.preferences.Editor edit() { return new StorageEditor(this);
return new com.fsck.k9.preferences.Editor(this);
} }
//@Override
public Map<String, String> getAll() { public Map<String, String> getAll() {
return storage; return storage;
} }
//@Override
public boolean getBoolean(String key, boolean defValue) { public boolean getBoolean(String key, boolean defValue) {
String val = storage.get(key); String val = storage.get(key);
if (val == null) { if (val == null) {
@ -322,21 +286,6 @@ public class Storage implements SharedPreferences {
return Boolean.parseBoolean(val); return Boolean.parseBoolean(val);
} }
//@Override
public float getFloat(String key, float defValue) {
String val = storage.get(key);
if (val == null) {
return defValue;
}
try {
return Float.parseFloat(val);
} catch (NumberFormatException nfe) {
Log.e(K9.LOG_TAG, "Could not parse float", nfe);
return defValue;
}
}
//@Override
public int getInt(String key, int defValue) { public int getInt(String key, int defValue) {
String val = storage.get(key); String val = storage.get(key);
if (val == null) { if (val == null) {
@ -350,7 +299,6 @@ public class Storage implements SharedPreferences {
} }
} }
//@Override
public long getLong(String key, long defValue) { public long getLong(String key, long defValue) {
String val = storage.get(key); String val = storage.get(key);
if (val == null) { if (val == null) {
@ -364,7 +312,6 @@ public class Storage implements SharedPreferences {
} }
} }
//@Override
public String getString(String key, String defValue) { public String getString(String key, String defValue) {
String val = storage.get(key); String val = storage.get(key);
if (val == null) { if (val == null) {
@ -373,18 +320,6 @@ public class Storage implements SharedPreferences {
return val; return val;
} }
//@Override
public void registerOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
listeners.addIfAbsent(listener);
}
//@Override
public void unregisterOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
listeners.remove(listener);
}
private String readValue(SQLiteDatabase mDb, String key) { private String readValue(SQLiteDatabase mDb, String key) {
Cursor cursor = null; Cursor cursor = null;
String value = null; String value = null;
@ -422,10 +357,4 @@ public class Storage implements SharedPreferences {
Log.e(K9.LOG_TAG, "Error writing key '" + key + "', value = '" + value + "'"); Log.e(K9.LOG_TAG, "Error writing key '" + key + "', value = '" + value + "'");
} }
} }
@Override
public Set<String> getStringSet(String arg0, Set<String> arg1) {
throw new RuntimeException("Not implemented");
}
} }

View file

@ -8,18 +8,17 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set;
public class Editor implements android.content.SharedPreferences.Editor {
public class StorageEditor {
private Storage storage; private Storage storage;
private Map<String, String> changes = new HashMap<String, String>(); private Map<String, String> changes = new HashMap<String, String>();
private List<String> removals = new ArrayList<String>(); private List<String> removals = new ArrayList<String>();
private boolean removeAll = false;
Map<String, String> snapshot = new HashMap<String, String>(); Map<String, String> snapshot = new HashMap<String, String>();
protected Editor(Storage storage) { StorageEditor(Storage storage) {
this.storage = storage; this.storage = storage;
snapshot.putAll(storage.getAll()); snapshot.putAll(storage.getAll());
} }
@ -42,22 +41,6 @@ public class Editor implements android.content.SharedPreferences.Editor {
} }
} }
//@Override
public android.content.SharedPreferences.Editor clear() {
removeAll = true;
return this;
}
// TODO Android 2.3 provides a sexy new "apply" method we need to implement
public void apply() {
commit();
}
/* This method is poorly defined. It should throw an Exception on failure */
//@Override
public boolean commit() { public boolean commit() {
try { try {
commitChanges(); commitChanges();
@ -68,14 +51,11 @@ public class Editor implements android.content.SharedPreferences.Editor {
} }
} }
public void commitChanges() { private void commitChanges() {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
Log.i(K9.LOG_TAG, "Committing preference changes"); Log.i(K9.LOG_TAG, "Committing preference changes");
Runnable committer = new Runnable() { Runnable committer = new Runnable() {
public void run() { public void run() {
if (removeAll) {
storage.removeAll();
}
for (String removeKey : removals) { for (String removeKey : removals) {
storage.remove(removeKey); storage.remove(removeKey);
} }
@ -84,7 +64,7 @@ public class Editor implements android.content.SharedPreferences.Editor {
String key = entry.getKey(); String key = entry.getKey();
String newValue = entry.getValue(); String newValue = entry.getValue();
String oldValue = snapshot.get(key); String oldValue = snapshot.get(key);
if (removeAll || removals.contains(key) || !newValue.equals(oldValue)) { if (removals.contains(key) || !newValue.equals(oldValue)) {
insertables.put(key, newValue); insertables.put(key, newValue);
} }
} }
@ -97,35 +77,23 @@ public class Editor implements android.content.SharedPreferences.Editor {
} }
//@Override public StorageEditor putBoolean(String key,
public android.content.SharedPreferences.Editor putBoolean(String key,
boolean value) { boolean value) {
changes.put(key, "" + value); changes.put(key, "" + value);
return this; return this;
} }
//@Override public StorageEditor putInt(String key, int value) {
public android.content.SharedPreferences.Editor putFloat(String key,
float value) {
changes.put(key, "" + value); changes.put(key, "" + value);
return this; return this;
} }
//@Override public StorageEditor putLong(String key, long value) {
public android.content.SharedPreferences.Editor putInt(String key, int value) {
changes.put(key, "" + value); changes.put(key, "" + value);
return this; return this;
} }
//@Override public StorageEditor putString(String key, String value) {
public android.content.SharedPreferences.Editor putLong(String key, long value) {
changes.put(key, "" + value);
return this;
}
//@Override
public android.content.SharedPreferences.Editor putString(String key,
String value) {
if (value == null) { if (value == null) {
remove(key); remove(key);
} else { } else {
@ -134,15 +102,8 @@ public class Editor implements android.content.SharedPreferences.Editor {
return this; return this;
} }
//@Override public StorageEditor remove(String key) {
public android.content.SharedPreferences.Editor remove(String key) {
removals.add(key); removals.add(key);
return this; return this;
} }
@Override
public android.content.SharedPreferences.Editor putStringSet(String arg0, Set<String> arg1) {
throw new RuntimeException("Not implemented");
}
} }

View file

@ -32,7 +32,6 @@ import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.controller.MessagingListener;
import com.fsck.k9.helper.MessageHelper; import com.fsck.k9.helper.MessageHelper;
import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.Message; import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mailstore.LocalFolder; import com.fsck.k9.mailstore.LocalFolder;

View file

@ -7,7 +7,6 @@ import java.util.Date;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder; import android.os.IBinder;
import android.util.Log; import android.util.Log;
@ -18,6 +17,9 @@ import com.fsck.k9.Account.FolderMode;
import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.helper.Utility; import com.fsck.k9.helper.Utility;
import com.fsck.k9.mail.Pusher; import com.fsck.k9.mail.Pusher;
import com.fsck.k9.preferences.Storage;
import com.fsck.k9.preferences.StorageEditor;
public class MailService extends CoreService { public class MailService extends CoreService {
private static final String ACTION_CHECK_MAIL = "com.fsck.k9.intent.action.MAIL_SERVICE_WAKEUP"; private static final String ACTION_CHECK_MAIL = "com.fsck.k9.intent.action.MAIL_SERVICE_WAKEUP";
@ -176,8 +178,8 @@ public class MailService extends CoreService {
if (K9.DEBUG) if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Saving lastCheckEnd = " + new Date(lastCheckEnd)); Log.i(K9.LOG_TAG, "Saving lastCheckEnd = " + new Date(lastCheckEnd));
Preferences prefs = Preferences.getPreferences(context); Preferences prefs = Preferences.getPreferences(context);
SharedPreferences sPrefs = prefs.getPreferences(); Storage storage = prefs.getStorage();
SharedPreferences.Editor editor = sPrefs.edit(); StorageEditor editor = storage.edit();
editor.putLong(LAST_CHECK_END, lastCheckEnd); editor.putLong(LAST_CHECK_END, lastCheckEnd);
editor.commit(); editor.commit();
} }
@ -243,9 +245,9 @@ public class MailService extends CoreService {
} }
Preferences prefs = Preferences.getPreferences(MailService.this); Preferences prefs = Preferences.getPreferences(MailService.this);
SharedPreferences sPrefs = prefs.getPreferences(); Storage storage = prefs.getStorage();
int previousInterval = sPrefs.getInt(PREVIOUS_INTERVAL, -1); int previousInterval = storage.getInt(PREVIOUS_INTERVAL, -1);
long lastCheckEnd = sPrefs.getLong(LAST_CHECK_END, -1); long lastCheckEnd = storage.getLong(LAST_CHECK_END, -1);
if (lastCheckEnd > System.currentTimeMillis()) { if (lastCheckEnd > System.currentTimeMillis()) {
Log.i(K9.LOG_TAG, "The database claims that the last time mail was checked was in " + Log.i(K9.LOG_TAG, "The database claims that the last time mail was checked was in " +
@ -263,7 +265,7 @@ public class MailService extends CoreService {
shortestInterval = account.getAutomaticCheckIntervalMinutes(); shortestInterval = account.getAutomaticCheckIntervalMinutes();
} }
} }
SharedPreferences.Editor editor = sPrefs.edit(); StorageEditor editor = storage.edit();
editor.putInt(PREVIOUS_INTERVAL, shortestInterval); editor.putInt(PREVIOUS_INTERVAL, shortestInterval);
editor.commit(); editor.commit();

View file

@ -2,6 +2,8 @@ package com.fsck.k9.service;
import com.fsck.k9.Account; import com.fsck.k9.Account;
import com.fsck.k9.K9; import com.fsck.k9.K9;
import com.fsck.k9.preferences.Storage;
import com.fsck.k9.preferences.StorageEditor;
import com.fsck.k9.remotecontrol.K9RemoteControl; import com.fsck.k9.remotecontrol.K9RemoteControl;
import com.fsck.k9.Preferences; import com.fsck.k9.Preferences;
import com.fsck.k9.R; import com.fsck.k9.R;
@ -12,8 +14,6 @@ import static com.fsck.k9.remotecontrol.K9RemoteControl.*;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log; import android.util.Log;
import android.widget.Toast; import android.widget.Toast;
@ -127,9 +127,9 @@ public class RemoteControlService extends CoreService {
K9.setK9Theme(K9RemoteControl.K9_THEME_DARK.equals(theme) ? K9.Theme.DARK : K9.Theme.LIGHT); K9.setK9Theme(K9RemoteControl.K9_THEME_DARK.equals(theme) ? K9.Theme.DARK : K9.Theme.LIGHT);
} }
SharedPreferences sPrefs = preferences.getPreferences(); Storage storage = preferences.getStorage();
Editor editor = sPrefs.edit(); StorageEditor editor = storage.edit();
K9.save(editor); K9.save(editor);
editor.commit(); editor.commit();