I have an arraylist and I want to save the data, when the app is closed / terminated / destroyed.
//Class SimpleBookManager.java is a singleton
private ArrayList<Book> allBooks = new ArrayList<Book>();
public Book getBook(int index){
return allBooks.get(index);
}
public void saveChanges(){
//Save the allBooks into memory
}
public void loadBooks(){
//Load the allBooks into memory to the variable allBooks;
}
It is reached by writing SimpleBookManager.getSimpleBookManager().saveChanges(); in all the other classes in the package.
What is the best way to implement the method saveChanges() and loadBooks()? Could you give a brief example perhaps? I have read something about shared preferences in android but unfortunately I don't quite get it =)
You can get an instance of SharedPreferences from any context within your app.
The following code saves a preferences with key "some_pref_key, and value "some_pref_value" into a file named "your_preference_file_name"
SharedPreferences prefs = context.getSharedPreferences( "your_preference_file_name", MODE_APPEND );
SharedPreferences.Editor editor = prefs.edit();
editor.putString( "some_pref_key", "some_pref_value" );
editor.commit();
If you need to save other type of data, check the SharedPreferences.editor documentation
Here is a SO question that has the code that you are looking for in it
Android Shared Preferences
To store an array in shared preferences look here -
store Array in sharedpreferences
However, if your app has a lot of books, or a lot of information about each book it would be better to use an SQLite database
If you are going to store a single Data not more than 10,You can use shared preferences.
Example : If you are going to store bookid, then shared preferences is enough.
But If you are trying to store Array of Objects / data, you should store it in Database only. It is convenient for dealing with large amount of data
Related
I am making an app that is able to log in. Each time the user log in, the app will retrieve user data and save it locally so that each time user need to do something which need user information, the app need not to retrieve it again. Is it better to put it in a SharedPreferences or SQLite?
Since it will be always only one user data need to be stored, I think to put it in a SharedPreferences, but it makes my app have so many key-value data. I am also able to use SQLite instead. But, it looks awkward to have a database that always only have one record data in the table.
Is it a good practice to put only one record data in a database and keep replacing it once the data changes? Or is it better to put it in a Shared Preferences and make the SharedPreferences a bit messy because it has many key-value data.
I think SharedPreferences is best way to store profile data....
In SharedPreferences also we can replace stored data.
public class SharedPref {
private SharedPreferences pref;
private Editor editor;
private Context context;
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREFER_NAME = "SharedPreferences";
// All Shared Preferences Keys
private static final String IS_USER_LOGIN = "IsUserLoggedIn";
#SuppressLint("CommitPrefEdits")
public SharedPref(Context context){
this.context = context;
this.pref = context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
this.editor = pref.edit();
}
//Set current tab position
public void setCurrentTab(String currentTab) {
editor.putString(Constant.TabActivity.CURRENT_TAB,currentTab);
editor.commit();
}
public void setTabActivityTitle(String title) {
editor.putString(Constant.TabActivity.TAB_ACTIVITY_TITLE,title);
editor.commit();
}
public String getSessionValue(String key) {
return pref.getString(key, null);
}
}
It totally depend on your data, which you want to store. I would personally recommend you to store in sharedpreferences. SQLite is used to store large, Structured and Organized data where as sharedpreferences are used to store small, unstructured data like login info, user preferences etc
I would use SharedPreferences for your scenario.
A database would be good if you had several user profiles, but since you only want to store one user profile, it doesn't make sense to create a database for just one row.
You shouldn't use neither SQLite nor SharedPreferences, the thing is, android done it for you, you should something that's called AccountManager
Why you should it:
This class provides access to a centralized registry of the user's online accounts. The user enters credentials (username and password) once per account, granting applications access to online resources with "one-click" approval.
You can read about this class here : http://developer.android.com/reference/android/accounts/AccountManager.html
But what you should know is that you can also remove accounts there, so it's especially good for you, here is tutorial Step by step: http://www.finalconcept.com.au/article/view/android-account-manager-step-by-step-2
I would like the user to be able to create a nickname for a string that shows up in their textview. The app will feed a string into the activity through a service and display it in a textview. I would then like the user to be able to nickname that string, so that every time the string is displayed again the nickname will show up instead of the original string.
My question is, can I use shared preferences to do this? What would be the logic behind the user being able to assign nicknames? If you could point out any literature or sample code that would be greatly appreciated as well. Thank you for any help.
Algorhithm:
At a certain point in your app lifecycle, write a preference using a "name" and a value.
Retrieve the value when the app starts and compare it to something.
Act consequently.
From the reference site: http://developer.android.com/guide/topics/data/data-storage.html#pref
Using Shared Preferences
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).
To get a SharedPreferences object for your application, use one of two methods:
getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
To write values:
Call edit() to get a SharedPreferences.Editor.
Add values with methods such as putBoolean() and putString().
Commit the new values with commit()
To read values, use SharedPreferences methods such as getBoolean() and getString().
Here is an example that saves a preference for silent keypress mode in a calculator:
public class Calc extends Activity
{
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
//...
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop()
{
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
I have an application where I want to save username and password on Remember checkbox is checked.
I done the above requirement using Shared Preferences. But i created another application and tried to read the username and password and got the values successfully.
My Client needs the security so how can i stop other apps to read my shared preferences.
public SharedPreferences getSharedPreferences()
{
return this.mContext.getSharedPreferences(PREFERENCES_KEY, Context.MODE_PRIVATE);
}
public void saveLong(String paramString, long paramLong)
{
SharedPreferences.Editor localEditor = getSharedPreferences().edit();
localEditor.putLong(paramString, paramLong);
localEditor.commit();
}
If MODE_PRIVATE is not enough, you can encrypt the data, turn it into base64, and save it as a string in the Preferences object. Reverse the process on the way back. Your data will be accessible, but illegible.
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
I have one log in page for the project 'x'.My need is if at first i entered into the project by providing proper values in to the log in page of the project.The project always want to be signed-in, whenever i try to open the project.How to achieve this concept?
Thanks for your precious time!..
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of the getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
For more info, check this link:
Making data persistent in android
Whenever you login set the user inside the preference file. Then in your main activity give a check whether you have value for this preference or not. If present, goto the landing page. Otherwise show the login page.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getLandingPage();
}
private void getLandingPage() {
if (isLoggedIn()) {
//goto login page
} else {
//goto landing page
}
}
/**
* Checks whether preference contains any value
*
* #return
*/
private boolean isLoggedIn() {
return ProjectPreferences.getUserName() == ProjectPreferences.NULL_STRING
? true
: false;
}
}
Also don't forget to set username while you login.