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
Related
In my Android application for my school project I want to make it such that:
Every day, when you first open the application, it will start an activity. However, if you open the application again even after closing it from the multitasking view, it will not start the activity again.
I want it to be much like Elevate (https://www.elevateapp.com/) where on first startup it will say "Your training session for the day is ready" but never display this again if you open the app at another time in the day.
This is a screenshot of the activity:
I have tried using AlarmManager in this link Alarm Manager Example and searching for answers but it did not work for me and I couldn't find any.
Is there a way to make it possible? Thanks in advance.
We can use SharedPreferences to store the system date when the app is launched and verify if it is the same date or a different one every time the app s run.
If the date is different, store the new date into the SharedPreferences handle that you used.
To understand how to use SharedPreference to store data you can look at my answer here for an example.
First declare this two method on global level
public static void commitPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String readPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
now maintain your logic..
if (!readPref("CHECK_IF_RUN_TODAY", getApplicationContext()).equals(new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date()))){
//YOUR LOGIC
commitPref("CHECK_IF_RUN_TODAY", new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date()), getApplicationContext());
}
but dont forget to upadte your prefrence after your logic
Hope this helps..
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 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.
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);
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