I'm a complete beginner to Java and Android development and had a question about preferences.
A tutorial asked me to use preferences to read and save the time in which the onCreate method is called.
I've sat on this problem for at least two days but have come up with nothing. Can anyone give me an example on how to code such an action?
public static final String PREFS_NAME = "Time_Pref";
public class QuizSplashActivity extends QuizActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
SharedPreferences = getSharedPreferences ("Time_Pref", "MODE_PRIVATE);
}
But that's where I seem to get lost. I'm not even sure if I'm heading in the right direction.
Although I tend to agree with Falmarri's comment on your question, I'll provide some pointers...
The first thing you should do in onCreate() is to create an instance of GregorianCalendar using new GregorianCalendar() to initialize it to current date/time.
Next use getSharedPreferences to create your SharedPreferences then get an editor using its edit() method.
The simplest way to store the time would be in milliseconds so use the GregorianCalendar getTimeInMillis method (inherited from Calendar) to get a Long result.
Finally, use the SharedPreferences editor's putLong() method to store the result of getTimeInMillis and use the editor's commit() method to make the change permanent.
Searching these pages will give you all the information you need...
Android Developers
I'd recommend you to read the dev guide's chapter about SharedPreferences. You can find it here.
I suggest you to use System.currentTimeMillis() to get the time value to save.
Basic code to save something to preferences should look like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// view setup stuff here...
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putLong("onCreateCallTime", System.currentTimeMillis());
editor.commit();
}
Then use android.text.format.Time class to format that time after reading it from preferences:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
long timeMillis = settings.getLong("onCreateCallTime", 0);
Time t = new Time();
t.set(timeMillis);
Read the Time class documentation to learn how to format/convert time with its methods :)
Related
I am creating an android application using Android Studio.
I need to write a code that saves in a properties file the date and time when the user(for example myself) opened the app.
So anytime the user(me) opens the app, to write that date and time in that properties file.
I guess that this is done using SharedPreferences but I do not find a solution anywhere.
Thank you.
Write this code in your app's Launcher Activity (such as SplashActivity if there):
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String counterKey = "counterKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//doing basic stuff of set layout and all here...
//Initialize sharedpreferences here
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//call to increment counter here
updateAppOpenCounter();
//do remaining stuff here....
}
private void updateAppOpenCounter() {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(counterKey, getAppOpenedCount() + 1);
editor.commit();
}
private int getAppOpenedCount() {
sharedpreferences.getInt(counterKey, 0); //Kept 0 as default opened count if not set to shared yet.
}
You can get the current date by using either new Date() or Calendar.getInstance(), and you could then format this to a String using SimpleDateFormat.
Storing the String representation of the date the app was opened can be done easily using the documentation provided by Google on SharedPreferences.
In my app I want to have a tutorial when the user installs the app for the first time. I used google analytics app recently and the way they do it looks perfect to me.
I have seen such views in other apps as well. Is this some standard view or does a library exist for it? Or will I have to write it from scratch using a view pager? Thanks in advance !!
I think this 3rd party library is best for these types of tutorials.Here is one screen shot:
This is another library.
Another one is here.
You can also try this.
And last one is my favourite.
You can use this ViewPageIndicator also.
To make sure that this tutorial is shown only 1st time, you can use shared preference. sample code is:
public class MainActivity extends Activity {
public static final String MyPrefs = "MyPrefs";
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences(MyPrefs, Context.MODE_PRIVATE);
if (!sp.getBoolean("first", false)) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("first", true);
editor.commit();
Intent intent = new Intent(this, SampleCirclesDefault.class); //call your ViewPager class
startActivity(intent);
}
}
}
I am making an application that contains a form and whenever a data clicks a button loads from a BD in a EditText, but every time I press a different button, the other EditText are cleared, I tried with:
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("data", myVariable);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
other = savedInstanceState.getString("data");
name.setText(other);
}
Sorry if I have not explained well, I need that every time they change Activity variables and I have not deleted. Any suggestions? Thank you!
Try using Android SharedPreferences instead. This is a persistent key-value storage that Android offers for its apps and was designed to covers issues like this. Here's the easy way to use it:
SharedPreference prefs = PreferenceManager.getDefaultSharedPreferences(this);
// To put a data (in this case a String from your EditText)..
Editor editor = prefs.edit();
editor.putString("data", yourStringHere);
editor.commit();
...
// ..and to retrieve it..
prefs.getString("data", null);
// NOTE: The 'null' in above method call could be replaced by any String you want;
// it basically specifies a default value to get when "data" is empty or doesn't
// yet exist.
Hope this helps.
I need to set some values to their associated persistently stored data, if they exist, on initialization. If not I need to initialize them. Is there any disadvantage to using the SharedPreference to initialize the variable on the first run. That is, something like this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences("MyDataName", Context.MODE_PRIVATE);
String name = sp.getString("name", "");
boolean isFirstRunning = sp.getBoolean("firstTime", true);
if (isFirstRunning) {
Toast.makeText(this, "YEA", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("firstTime", false);
editor.commit();
}
}
If there is no disadvantage from a processing level, is there a standard practice as far as this situation is concerned? Also, is there any alternative way to handle the persistent data, or do we have to use SharedPreferences for this?
Yes that's perfectly acceptable. For neatness it may be better to define the keys, and default values as constants but the approach you have will work fine.
That is based on your requirement. if u need sharedpreference values quickly its good which you wrote. other wise no use.
i am creating login in my app. User type his info i send it to web service to check and get his ID. Now i need to save it somewhere in my app that i could check if he had login.
So where this info should be saved ? I know that every app have it's settings so there should be this info ? Maybe someone could give me more info what and how this is doing.
Thanks.
I found this post:
What is the most appropriate way to store user settings in Android application
I believe my question was duplicate. But it would be nice if you have something to share more.
First of all save user info like uname & password in SharedPreferences with this code.
SharedPreferences settings = getSharedPreferences("UserInfo", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("Username",txtUname.getText().toString());
editor.putString("Password",txtPWD.getText().toString());
editor.commit();
and then get SharedPreferences from below code
SharedPreferences settings = getSharedPreferences("UserInfo", 0);
txtUname.setText(settings.getString("Username", "").toString());
txtPWD.setText(settings.getString("Password", "").toString());
Answer is Use Application Class or Shared Preferences
I assume you can easily search for the Example of Application Class, SharedPreferences and SQLite Database
So I am mentioning Where Do I Use Which Options
Application Class
When I got anything(var , array , list , objects) to store just only for the LifeTime of the Application..and As it got close (for Android Force Close) I use Application Class.
SharedPreferences
I use this when I got some short information like id,token,username,flags and I want to store that as long as the application rest in the Device..and need to use those information everytime I start the Application..
SQLite Database
When there is a bulk data in Record format (Row - Column) I used it to store in database so it becomes easy to store , retrive and manipulate.
You can use SharedPreferences for this.
Some codes from references (taken from documentation):
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();
}
}
if user clear the application data from setting -> application manager -> your application -> clear data
then all data saved in shared preferences will get removed