Access Android sharedPreferences from surfaceview - android

The code to access sharedpreferences is
SharedPreferences settings = getSharedPreferences("MySettings", 0);
float X = settings.getFloat("myFloat", 0);
But this only works from within an activity.
How do I access it from else where?
Would a singleton be a good idea? And how would I set up and access this singleton.
I only want to store 4 floats, and this would have been great! But nothing is straight forward :(

Isn't there a getContext() method for SurfaceView?
getContext().getSharedPreference();
If that didn't work, you can load those vars in a singleton on start up, since there are only 4 of them.
public class ClassicSingleton {
public float float1;
public float float2;
public float float3;
public float float4;
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}

Related

How to use Shared preferences in singleton of other class which not include context?

I got a singleton. In methods of this singleton i need to get access to shared preferences. How I can do that?
public class SubscriptionManager {
private static SubscriptionManager instance = null;
private SubscriptionManager() {}
private SharedPreferences mPrefs;
public static SubscriptionManager getInstance() {
if (instance == null)
instance = new SubscriptionManager();
return instance;
}
public void setFreeOpenSubscription(){
//here i need to write something like
// String type = mPrefs.getValue("type");
}
}

how to get same realm instance between two activitys?

public class MyApp extends MultiDexApplication {
private static MyApp instance;
private static class LazyHolder {
private static final Realm INSTANCE = Realm.getDefaultInstance();
}
public static Realm getRealm() {
return LazyHolder.INSTANCE;
}
public static Context getContext() {
return instance;
}
#Override
public void onCreate() {
instance = this;
super.onCreate();
Realm.init(this);
}
}
this is my application activity.
one recyclerView Adapter is using two activities.
first, normal Article List Activity.
second, find Article List Activity.
when I select an Article with the same Url for any Activity, I want to save the Url for that Article.
And this is how I determine if it's stored in Realm in onBindViewHolder().
RealmResults<Article> results = MyApp.getRealm().where(Article.class).equalTo("link", list.get(position).getLink()).findAll();
boolean isSeenArticle = results.size() >= 1;
if(hasKeyword(position)) {
String[] temp = list.get(position).getTitle().split(keyword);
setTitleSpannable(holder.title, temp, isSeenArticle);
}
else {
holder.title.setText(list.get(position).getTitle());
holder.title.setTextColor(isSeenArticle ? context.getResources().getColor(R.color.OneDarkSemiSemiGray) : context.getResources().getColor(R.color.textColorPrimary));
}
color of the holder.articler_title text changes on one side only.
However, both activities appear to have different Realm Instances.
How can I use the same Realm Instance?

Android save and read values from SharedPreferences

How to save values in preferences (and read) with quite compact way without creating several instances - i want be sure that i have only one instance of pref
A SharedPreferences object is a natural singleton. Your first call to read in a SharedPreferences (e.g., PreferenceManager.getDefaultSharedPreferences()) will create it. Second and subsequent calls within the same process will return that same instance. Hence, so long as you are consistent about where you get your SharedPreferences from, you will only ever have one instance (at most) in your process.
CommonsWare is right, but as i understood, you want somehow to structure you job with Preferences, i use singleton for this, something like this:
public class Preferences {
private static final String USERNAME = "username";
private static final String LOG_TAG = Preferences.class.getSimpleName();
private static Preferences sInstance;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private Context mContext;
private Preferences(Context context) {
mContext = context;
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
mEditor = mSharedPreferences.edit();
}
public static Preferences getInstance(Context context) {
if (sInstance == null) {
sInstance = new Preferences(context);
}
return sInstance;
}
public void setUsername(String username) {
mEditor.putString(USERNAME, username);
commit();
}
public String getUsername() {
return mSharedPreferences.getString(USERNAME, null);
}
public boolean commit() {
return mEditor.commit();
}
}
And where it is necessary write
Preferences.getInstance(this).setUsername("USERNAME");
and read
Preferences.getInstance(this).getUsername();

How to declare a variable that can be accessed by all the classes in android?

I'm a new to android please help me with the following.
I'm having an integer value which stores the id of a checked radiobutton. I need to access this value throughout the various classes of my app for a validation purpose.
Please let me know how to declare and access this variable from all the classes.
Thank you.
U can use:
MainActivity.class
Public static int myId;
In other Activities.
int otherId=MainActivity.myId;
following singleton pattern is the only way to do this.in java/android if u create a instance for a class every time it create a new object.what you should do is
1.create a model class and make its as singleton
2.try to access the modelclass from every class
public class CommonModelClass
{
private static CommonModelClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private CommonModelClass()
{
// Optional Code
}
public static synchronized CommonModelClass getSingletonObject()
{
if (singletonObject == null)
{
singletonObject = new CommonModelClass();
}
return singletonObject;
}
/**
* used to clear CommonModelClass(SingletonClass) Memory
*/
public void clear()
{
singletonObject = null;
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
//getters and setters starts from here.it is used to set and get a value
public String getcheckBox()
{
return checkBox;
}
public void setcheckBox(String checkBox)
{
this.checkBox = checkBox;
}
}
accessing the model class values from other class
commonModelClass = CommonModelClass.getSingletonObject();
commonModelClass.getcheckBox();
http://javapapers.com/design-patterns/singleton-pattern/
You can declare your integer variable as static and access in any class.Like this
class A{
static int a;
}
You can access in another class like this.
class B{
int b = A.a;
}

Android Singleton with Global Context

Per the Android Documentation it states:
There is normally no need to subclass Application. In most situation,
static singletons can provide the same functionality in a more modular
way. If your singleton needs a global context (for example to register
broadcast receivers), the function to retrieve it can be given a
Context which internally uses Context.getApplicationContext() when
first constructing the singleton.
How do I go about creating a static singleton that has global context so that it survives the running activity changing in my app? Is it enough to have a static context which references the getApplicationContext()?
Another edit to the question (2016)
Lately (as of 2016 and onward) what I've been doing, and would be my suggestion for any developer, is:
Just use Dagger 2. Wherever you need a Context you do:
#Inject Context context;
and that's it. While at it, inject all the other stuff that would be a singleton.
Edited/improved answer (2014)
because this answer is getting kinda-of popular, I'll improve my own answer with example code of what I've been using lately (as of Jul/2014).
Start by having the application keeping a reference to itself.
public class App extends Application {
private static App instance;
public static App get() { return instance; }
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
then on any singleton that needs access to the context I lazy load the singles in a thread safe manner using double check synchronization as explained here https://stackoverflow.com/a/11165926/906362
private static SingletonDemo instance;
public static SingletonDemo get() {
if(instance == null) instance = getSync();
return instance;
}
private static synchronized SingletonDemo getSync() {
if(instance == null) instance = new SingletonDemo();
return instance;
}
private SingletonDemo(){
// here you can directly access the Application context calling
App.get();
}
Original answer
what the documentation is suggesting is to use a normal singleton pattern
public class SingletonDemo {
private static SingletonDemo instance = null;
private SingletonDemo() { }
public static SingletonDemo getInstance() {
if (instance == null) {
instance = new SingletonDemo ();
}
return instance;
}
}
and include inside it a method like this:
private Context context;
init(Context context){
this.context = context.getApplicationContext();
}
and remember to call this to initialise the singleton.
The difference between the Application approach and the Singleton approach and why the Singleton is better is on the documentation same functionality in a more modular way
I have such class in my application :
public class ApplicationContext {
private Context appContext;
private ApplicationContext(){}
public void init(Context context){
if(appContext == null){
appContext = context;
}
}
private Context getContext(){
return appContext;
}
public static Context get(){
return getInstance().getContext();
}
private static ApplicationContext instance;
public static ApplicationContext getInstance(){
return instance == null ?
(instance = new ApplicationContext()):
instance;
}
}
and then for example in Launch Activity initialize it :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init
ApplicationContext.getInstance().init(getApplicationContext());
//use via ApplicationContext.get()
assert(getApplicationContext() == ApplicationContext.get());
}

Categories

Resources