All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.solovyev.android.prefs.StringPreference Maven / Gradle / Ivy

There is a newer version: 1.1.18
Show newest version
/*
 * Copyright (c) 2009-2011. Created by serso aka se.solovyev.
 * For more information, please, contact [email protected]
 * or visit http://se.solovyev.org
 */

package org.solovyev.android.prefs;

import android.content.SharedPreferences;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.common.text.EnumMapper;
import org.solovyev.common.text.Mapper;
import org.solovyev.common.text.StringMapper;

/**
 * User: serso
 * Date: 12/25/11
 * Time: 12:37 PM
 */

/**
 * {@link Preference} implementation which uses {@link String} way of storing object in persistence.
 * This class provides methods for mapping real java objects to String and vice versa.
 * @param 
 */
public class StringPreference extends AbstractPreference {

	@NotNull
	private final Mapper mapper;

	public StringPreference(@NotNull String id, @Nullable T defaultValue, @NotNull Mapper mapper) {
		super(id, defaultValue);
		this.mapper = mapper;
	}

	@NotNull
	public static StringPreference newInstance(@NotNull String id, @Nullable String defaultValue) {
		return new StringPreference(id, defaultValue, new StringMapper());
	}

	@NotNull
	public static  StringPreference newInstance(@NotNull String id, @Nullable String defaultValue, @NotNull Mapper parser) {
		return new StringPreference(id, parser.parseValue(defaultValue), parser);
	}

	@NotNull
	public static  StringPreference newInstance(@NotNull String id, @Nullable T defaultValue, @NotNull Class enumType) {
		return new StringPreference(id, defaultValue, new EnumMapper(enumType));
	}

	@Override
	protected T getPersistedValue(@NotNull SharedPreferences preferences) {
		return mapper.parseValue(preferences.getString(getKey(), null));
	}

	@Override
	protected void putPersistedValue(@NotNull SharedPreferences.Editor editor, @NotNull T value) {
		editor.putString(getKey(), mapper.formatValue(value));
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy