Saving data between activities using external class - android

I'm developing an app that has to share strings between activities. I'm trying to get the seperate activities to call a public class with set and get methods. The calling the methods part works and I manage to get a response although the set value has to be rememberd by the set and get class. Here's a link to my set and get class, it's pretty basic: http://pastebin.com/0WabNKz3
Now my question is this: How do I make the set and get class to remember my values between sessions? Feel free ask questions if there's anything you didn't understand.
Thanks!

You need to use SharedPreferences. That's the way to save data even after the app is closed and you can access it from anywhere:
public void savePrefrences(String key, String value)
{
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), 0);
prefs.edit().putString(key, value).commit();
}
public String getPrefrences(String key)
{
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), 0);
return prefs.getString(key, "");
}
Save the prefrence when and whereever you want and get it whenever and from wherver you want.
The value will not delete when you close the app.

I ended up creating invisible EditTextPreference that now hold the data that I want to keep because they can be shared easily.

When you say saving between sessions, do you mean between the app being paused, or closed completely?
A good resource for lifecycle and storing data across sessions is:
//developer.android.com/training/basics/activity-lifecycle/index.html

Related

How to retrieve data prior to running an activity

I have 2 fragments.
Fragment 1
Loads sharedpreference to display string
Fragment 2
Saves sharedprefence for string
Is it possible to retrieve that string in my first Fragment without running the second Fragment?
Yes, this is possible. You just need to make sure you are reading with the same key you used to write with:
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
// Reading from SharedPreferences
String value = prefs.getString("myKey", "defaultValue");
Log.d(LOG_TAG, value);
Note that we've assigned a defaultValue as the return value here. If there is no value with the key "myKey" in your shared prefs, it will instead return "defaultValue". This is a nice safeguard, think of it like a null pointer check - you will always get a value from getString(), even if it's just the default.
You don't need to be in the same activity for this to work, you just need to make sure that 1) your preferences name is the same and 2) the key used to store the value is the same in both spots.
First, don't get confuse between Activity and Fragment.
And yes, you can.

Android application remember settings

I am coding using Xamarin and have a question about application settings.
Is it possible to have application wide settings? I will give you an example:
I have a map application. I have a ListView where the user can select if the map is using the Street View, Satellite View or default view.
Depending on the item that is selected in the ListView depends of the map view that is shown.
Where and how can I save this selection such that this value is visible throughout the application and when the user exits the application, this setting can be remembered for when the user starts the application up again?
Thanks in advance
Yes, it's possible and also very easy. Usually you save simple application settings using SharedPreferences. They can be read from anywhere in the app.
For writing.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sp.edit();
editor.putBoolean("someBoolean", true);
editor.putString("someString", "string");
editor.commit();
For reading
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean someBoolean = sp.getBoolean("someBoolean", false);
boolean someString = sp.getString("someString", null);
I suppose you are familiar to Java I/O and android basic concepts. So here I go:
For data persistance in Android, you have two main solutions:
SQLite database
File system
I recommend you to use file system, as you don't really need to organize your data with relational constraints and you will probably not have to make a lot of data persist.
Android documentation is very clear on how to save files:
http://developer.android.com/training/basics/data-storage/files.html
I recommend you to create a Setting class that contains a HashMap attribute:
public class Settings implements Parcelable{
public static HashMap<String,String> settings;
public static void readSettings(){
//Here you read your settings file and you fill your hashmap
}
public static void writeSettings(){
//Here you iterate through your hashmap and you write your setting files
}
}
Every activities will have access to the settings, as the attribute/methods are static. Settings will also be synchronized through every activities (if you change a setting in one activity, every other activities will notice).
If you need some clarifications, leave a comment below.

How to access a variable present in a service

I want to access a variable present in a service from another service/an activity....
Can anyone give an idea?
To communicate between two service or activity, you need to use AIDL
It is not really difficult to do, and there is a lot of tutorial like this.
You can make a public getter for that variable in your Service class, bind to that service, and access the getter to give you that variable.
If what you mean is that you want to access the variable after you close and open the app, then you're probably looking for SharedPreferences. Note that this requires a context (an activity or service).
To store:
int data = 5;
SharedPreferences storage = getSharedPreferences("storage", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = storage.edit();
editor.putInt("myInt", data);
editor.commit();
To get:
SharedPreferences storage = getSharedPreferences("storage", Context.MODE_PRIVATE);
int data = storage.getInt("myInt", 0);

Preference Screen as interface for database?

Is it possible to use a preference screen as a simple interface to read and write values to a database?
Basically, I like the way the preference screen looks and operates, but preferences aren't a suitable way to store all the data I have.
I know how to get it to display correctly, but I'm unsure on how to access the values represented on the screen, and how to keep it from writing a preference file.
Is this even a good idea?
Thanks.
Just to follow this up for anyone that is interested. I got it working by using a Preference.OnPreferenceChangeListener() to store the value as a int or string or whatever. For example:
et_model.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener(){
public boolean onPreferenceChange(Preference preference, Object newValue) {
String val = (String) newValue;
preference.setSummary(val);
model = val;
return true;
}
});
Then once the user presses done, I add the data to the database in the usual way with my SQLight database helper class.
When I load the values from the database, I simply use Preference.SetText(String), and Preference.SetSummary(String).
I guess it is still writing a preference file because if I don't set the preference's text it will load with whatever was set last, but I don't think this is a problem. I could also delete the preference file when I close the activity or something...
If you want a good example, just look at the source for the AlarmClock (now DeskClock) Look at SetAlarm.java and set_alarm.xml for the layout(Save and cancel keys) and alarm_prefs.xml for the actual preference layout.
I don't think that is such a hot idea, especially if you plan on having a tone of data in your database. How ever if you did want to do it, I would just extend the Preference widgets that you will use and have them interface with the database. For example, lets say you have 10 items in a table and you want to select one item (row in the database), you would override the ListPreference and fill it with the content of the applicable database row.

access preferences in live wallpaper

i have created a live wallpaper and in that there is a "setting" button which loads PreferenceActivity but without clicking on "settings" but i want to access the SharedPreferences within subclass of Engine or WallpaperService. As i just want to access the small single string so i don;t want user to go into settings and access that string.
So i want to execute this code inside Subclass of Engine or WallpaperSerivce
SharedPreferences mPrefs = getPreferenceManager().getSharedPreferences();
String option = mPrefs.getString(
this.getResources().getString(R.string.name),
this.getResources().getString(R.string.option));
It is not the best way to do it I'm sure but I use getters and setters to achieve this effect.
private int mySetting = defaultvalue
public int getMySetting() {
return mySetting;
}
public void setMySetting(int mySetting) {
this.mySetting = mySetting;
}
I obviously used some plain text in that code but hopefully it is pretty self explanitory
You set this variable while in Settings Class with...
Settings.this.setMySetting(value);
Remove "this" to call from other classes
You can retieve this information in any of your classes using the following
Settings.getMySetting();
You can use pretty much any variable type just make sure you define the mySetting variable as that type before trying to pass a value other than int as in this example. Hopefully this helps.

Categories

Resources