Is it better to put user data in SharedPreferences or SQLite? - android

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

Related

How do I save the current state of an Android App?

I am new in Android Development. I am trying my hands on developing an alarm app. When I set the alarm, I use a TextView to show the time for which the alarm in set up(initially empty). But when I close or minimize the app and start it again the TextView is again empty. How to get rid of this?
I looked for its solution in android app development manual, but still couldn't find my way out.
Particularly visiting developer.android.com will help you to get started with android development. Anyways you can either use any of the following to save your data:
SharedPreferences
Sqlite Database
File (Pertaining to your app's location)
And when you are reopening your application you can retrieve the information from this methods.
Saving data can be done easily with the SharedPreferences.
private final String SAVED_ALARM_TIME_KEY = "SavedAlarmTime"
private final String ALARM_PREFERENCES = "AlarmPreferences"
private void saveAlarmTime(Context context, long alarmTimestamp) {
SharedPreferences sharedPref = context.getSharedPreferences(ALARM_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putLong(SAVED_ALARM_TIME, alarmTimestamp);
editor.commit();
}
private long getAlarmTime(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(ALARM_PREFERENCES, Context.MODE_PRIVATE);
return sharedPref.getLong(SAVED_ALARM_TIME, 0);
}
This is great for something like user settings in the application. But I imagine you will later want to add multiple alarms to your application. In this case it would be better if you used a database. It will provide you with more options to scale the implementation. For instance you wish to add a functionality for repeating alarms at certain days the database will come in very handy.
You can refer to the documentation: https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html

How to store strings in Shared Preferences

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();
}
}

How to check if a FileInputStream is "full"

I'm trying to write a file on users mobile following this example
Storage Options [data-storage]
I want to create that file the first time users run my app.
After the first time users run my app, I want FIRST read the file, and THEN write something in it (if i need).
Following the example above i'm using FileInputStream stream= openFileInput(FILENAME),
Is there a way to know if the file i put in FileInputStream exists by checking the fIleInpuStream itself?
Thank everybody for your help.
Maybe the best way to do what i want to do was suggested by #Durairaj P.
I used Preferences.
But i'm still wondering if it's suitable and appropriate for what i want to do. I want to keep track of the points that users earn while playing my game; when users re-open my app, i have to show all the points they earned since they installed my app. I'm just wondering if Preferences are suitable and appropriatefor this, or if i should use something else.
Anyway i post my code, it might help someone
public class managePreferences{
Context context;
managePreferences(Context context){
this.context = context;
}
public String readPreference(String fieldName, String defaultValue){
SharedPreferences prefs = context.getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE);
String value = prefs.getString(fieldName, defaultValue);
return value ;
}
public void writePreference(String fieldName, String value){
SharedPreferences prefs = context.getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(fieldName, value);
editor.commit();
}
}
I would use
context.fileList();
and test if my file is somewhere. (quickest way is to make a List of it and use contains()) :
Arrays.asList(context.fileList()).contains(FILENAME);

how to store data in shared preferences

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

Saving data between activities using external class

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

Categories

Resources