Hello I am developing a simple project with android studio and I wanted to know how can I change the starting activity of the application via Java Code. I know how to do it with the androidmanifest.xml but I want the user to insert some data in the starting activity and then the next time the user loads the application the main activity pops up directly and not the starting activity again.
Thank you.
Use shared preference, with this you can save limited information. depending on what your user has selected you can save it and start an activity from it. the information remains even after the application is closed.
e.g. so you create a start activity that checks what settings have been selected and depending on that it starts the required activity with an intent.
search for shared preference and intent.
You should save a flag in Shared preference. For example in a first activity that launch save this:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "isNew");
editor.apply();
And when you want to Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "default value");//"default value defined" is the default value.
Then Check if (name == isNew) then start your MainActivity class
Related
I'm working on a practise 7 days exercise app. I set a progree bar on the main activity and want to change progress after days. Means if i complete exercise of day 1 ,progress bar set 15% . and when i complete day2 , progress set 30%. I can do it without shared preference , it working correctlt but when after day1 complete i closed the app it again set progress from 0 . So i want to use shared preferences for this reason . Kindly someone guide me regarding this issue;
For Set Value to Shared Prefrence
SharedPreferences.Editor editor = getSharedPreferences("ProgressBarData",
MODE_PRIVATE).edit();
editor.putInt("progress", 15);
editor.apply();
for get value From Shared Prefrence
SharedPreferences prefs = getSharedPreferences(ProgressBarData,
MODE_PRIVATE);
int progress = prefs.getInt("progress", 0);
1st ur know ur mistake
u can't store ur data in local variable because at the end of the activity it destroyed every things and when u come back to android activity it will be started all thing once again and every thing is restarted
[https://developer.android.com/guide/components/activities/activity-lifecycle
read this u have better understanding
Now ur solution
if u want to store the data and process every day better to use local storage like
Sqlite ,room or shared preference.
Step to do the task
There is three step to store, get and remove data into share preference
For storing , getting deleting data
//storing
SharedPreferences.Editor editor = context.getSharedPreferences(name,Context.MODE_PRIVATE).edit();
editor.putString(key, data);
editor.apply();
//getting
SharedPreferences getSharedPrefrence = context.getSharedPreferences(name, Context.MODE_PRIVATE);
int data = getSharedPrefrence.getInt(key, IntegerValuesAndStringValues.REGISTER_BEFORE_LOGIN);
return data;
BasicFunctions.removeSharedPrefrences(getContext(),"Name of the preference");
Say ActivityA with two buttons. Each of these button will open ActivityB but with a different fragment respectively. Both fragment contain an EditText. If I want to switch fragment while in ActivityB, I need to return to ActivityA and press the other button.
Now what I want to do is to save the value entered in each EditText when I switch fragment or close the app and repopulate the value in the right EditText when I re-open the fragment.
It seems to do it by it self when I open the SettingActivity then come back, but not if I destroy the activity. In the end I want the fragment to re-open just as I left it. Thank you.
You must save value and then restore them.A good way is Shared Preferences.
1-save:
SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("var1", edittext.getText().toString());
editor.commit();
2-restore:
String s = sharedpreferences.getString("var1","DEF");
Use SharedPreference to store the value
When you call your new activity use this
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("userEmail", youredittext.getText().toString());
editor.commit();
When you want to retrieve the stored value in any of your activities, get it like this
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String mUserEmail = getPrefs.getString("userEmail", null);
Yes if you have more fields or like you want to maintain relation for data.. in that case you also can use SQLite. Below is post on SQLite
http://www.kpblogs.com/mobile-development/sqlite-android-tutorial-with-crud-operations/
In MainActivity.java I write
SharedPreferences pref = getApplicationContext().getSharedPreferences("My_Pref" , 0);
Then I create object of Editor to put data in it
Editor edit = pref.edit();
Then I put data
edit.putString("1","Hello");
edit.commit(); / edit.apply();
In Second.java, I get preferences:
SharedPreferences pref = getPreferences(0);
then I try to receive data like
pref.getString("1",null);
and set it to text of textview. But this does not work.
Also, how do I access Preferences and editor in other java classes properly? I cannot understand the concept.
You are writing to and reading from different preference files. Use the same file and it should work.
To get an instance of SharedPreferences you do this:
1) In activity MainActivity:
SharedPreferences pref =
getApplicationContext().getSharedPreferences("My_Pref" , 0);
2) In activitySecond:
SharedPreferences pref =
getPreferences(0);
The first form opens preference file "My_Pref", the second form opens a file named after your activity class, i.e.: "Second". So they are reading and writing in different files.
I always use this form to open a preferences file:
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
Try this way
public void saveToSharedPrefrence(Context context, String word) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
if (sharedPreferences.contains("history")) {
preExistRemove(word, context);
} else {
editor.putString("history", word.trim());
editor.commit();
}
}
Check this for more details
Get the context of your activity
Context shrdContext= ActivityClass.getContextOfApplication();
Now pass the context to get your shared preferences in your another class
SharedPreferences myPrefs= PreferenceManager.getDefaultSharedPreferences(shrdContext);
You have 3 ways to access preferences for a Android application.
The first you used is
SharedPreferences pref = getApplicationContext().getSharedPreferences("My_Pref" , 0); is the first one. With this you can read and write to a custom-named shared preference file. In your case the name of your file would be My_Pref.
This one is useful if you want to have differents preferences differents domain as it allow you to create many shared preferences with differents names. (ex : preferences for timezone, preference for your user).
The second getPreferences(int) allow to access preferences for an Activity and is bind closely to the activity calling it. The file created is named using the Activity name. In your case Second.
The third method PreferenceManager.getDefaultSharedPreferences(Context) create a shared preference file like the first method, but this time the file is named using your application package name. This is the best methods to use shared preferences, if you intend to have only one shared preference file.
In your initial question you wrote a data in one file and tried to read in an other file, which result in an error. That's why like Rob Meeuwisse write you must use PreferenceManager.getDefaultSharedPreferences(Context)
I wrote an application with login/logout logic.
After login(set user and pass as vars) the user can minimize the application.
Minimize code:
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
When user clicks on the app icon in first activity I check is have set user and pass as vars, if they are app go to activity 2(next activity).
if they are not set go to login interface.
Everything is working fine but sometimes the app forgets the user and pass after minimizing and I go to the login interface....
Is like clearing cache I don't know... help
In Android, you cannot assume that your application will be kept in memory when it goes to the background, and you cannot assume it stays on the foreground (people may press the Home key or popups may come up). You should implement the onPause and onResume events and store the details of the logged in user there. These methods are guaranteed to be called by Android whenever your application goes into the background and is re-activated, respectively. You can use the SavedBundle object that you get in these methods to store your data. Also read about the app lifecycle here: http://developer.android.com/reference/android/app/Activity.html
you should use sharedPreferance to store login user and password.
below is code
private void storeUserPreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString("username", "xyz");
editor.putString("pass", "123");
editor.commit();
}
private void loadUserPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String pass =sharedPreferences.getString("pass","");
String username=sharedPreferences.getString("username","");
if(!TextUtils.isEmpty(pass)&&!TextUtils.isEmpty(username))
{
login.....success
}
else
{
redirect to login screen
}
}
this is ref doc http://developer.android.com/reference/android/content/SharedPreferences.html
I am trying to save the date of file parsing, so that when next time user, opens the application, the date can be checked against the last parsing date.
I am using shared preference to save the data and retrieve it, but getting error. Here is the code :
SharedPreferences settings = getPreferences(0);
String today = new Date(System.currentTimeMillis()).toString();
SharedPreferences.Editor edit = settings.edit();
System.out.println("******** Today : " + today);
edit.putString("lastdate", today);
String fetch = settings.getString("lastdate", "0");
System.out.println("******** Fetch : " + fetch);
txtTest.setText(fetch);
But I am getting null pointer error, am I missing something?
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 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 = PreferencesManager.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.
You need to change how you get the object
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);