I'm making a toggle button which changes activity but it changes only for once but want to make it permanent so user does not need to change it again and again.
Use Shared Preference for that . When user Toggle Button ON (logged) into your application store login status into sharedPreference and clear sharedPreference when user click on OFF(logged Out).
Check every time when user enter into application if user status from shared Preference is true then no need to login otherwise move to login page.
To achieve that first create one class, in that class you need to write all the function regarding get and set value in the sharedpreference . Please look at this below Code.
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
}
Now first check
if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
{
// call Login Activity
}
else
{
// Call Next Activity
}
Related
I have a problem with save the value of string or editText in java android. When I redirect from FirstActivity to Second and return after it to First, I need that a String that i fill earlier stay in the place that I wrote it. (Like a cookies in js).
You could use shared preferences for this process.
In that case, Best practise to create SharedPreference and for global usage, you need to create a global class like below:
public class PreferenceHelper {
private final SharedPreferences mPrefs;
public PreferenceHelperDemo(Context context) {
mPrefs = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 -for private mode
}
private String PREF_Key= "Key";
public String getKey() { // To retrieve data
String str = mPrefs.getString(PREF_Key, null);
return str;
}
public void setKey(String pREF_Key) { // To store and edit Data
Editor mEditor = mPrefs.edit();
mEditor.putString(PREF_Key, pREF_Key);
mEditor.commit();
}
public void clearData(string pREF_Key){ // To delete data
editor.remove(pREF_Key);
editor.commit();
}
}
Then you could use these functions with global class in your activity class to store, retrieve and delete the shared preference data.
Hope this will solve your problem!
I used the radio group button to signup user like if the user is student then he register as student ,if user is teacher is then select the teacher radio button and sign up and i want that when user login he redirect to their related activity or profile and i'm using firebase realtime database
When you want to redirect the user every time, he uses your application, you should save the selected option using e.g. preferences. Here do you see, how to save and load them.
You can redirect the user/start an activity using Intents. Here do you see, how to start other Intents.
You can try like this in your activity:
enum UserType {STUDENT, TEACHER, STAFF}
static final String PREF_KEY_USER_TYPE = "USER_TYPE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set pref based on user type
if (condition) {
setUserType(UserType.STUDENT);
} else {
setUserType(UserType.TEACHER);
}
}
private SharedPreferences getSharedPref() {
return getSharedPreferences("user_type_pref", Context.MODE_PRIVATE);
}
private void setUserType(UserType userType) {
getSharedPref().edit().putString(PREF_KEY_USER_TYPE, userType.name()).apply();
}
private String getUserType() {
return getSharedPref().getString(PREF_KEY_USER_TYPE, "");
}
I made a Utils class where I have static properties and functions that serves my app. I also have the info of the user, such as name email etc., and 2 functions to store/restore this info, so in general it looks like this:
public class Utils {
static public int userId;
static public String name;
static public String email;
static public void writeData(Context context) {
SharedPreferences.Editor pref = context.getSharedPreferences("q", Context.MODE_PRIVATE).edit();
pref.putInt("userid", userId);
pref.putString("email", email);
pref.putString("name", name);
pref.commit();
}
static public void readData(Context context) {
SharedPreferences prefs = context.getSharedPreferences("q", Context.MODE_PRIVATE);
userId = prefs.getInt("userid", 0);
email = prefs.getString("email", "");
name = prefs.getString("name", "");
}
}
I don't need to explain the simplicity of the above but I was wondering if there is a more recommended/standard way to do this.
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 Preference Activity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences). Although, using SharedPreferences in your case is more than an okay way of storing simple data.
I have 2 activities: Login and Main
I also have App class that runs before the Activities.
public class App extends Application
{
#Override
public void onCreate()
{
super.onCreate();
}
}
My AndroidManifest.xml makes Login Activity be the first activity to run.
Should I go to the Login activity, check the SharedPreferences then determine if user has already logged in?
Or Should I make a blank Activity that does this check then launches the correct Activity, either Login or Main?
Or Maybe the check should be done in the App class and a change made to the Android Manifest.
So that this doesn't become an opinion fest, any suggestion has to have a logical reason behind it and why it would be best.
Good solution is create new class for holding information about session, e.g.:
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor
Editor editor;
// Context
Context mContext;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyPref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
private static final String KEY_EMAIL = "email";
private static final String KEY_ID = "id";
// Constructor
public SessionManager(Context context) {
this.mContext = context;
pref = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
*/
public void createLoginSession(String email, int id) {
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing email in pref
editor.putString(KEY_EMAIL, email);
// Storing id in pref
editor.putInt(KEY_ID, id);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
*/
public void checkLogin() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(mContext, LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Staring Login Activity
mContext.startActivity(i);
}
}
/**
* Quick check for login
* *
*/
// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
public int getId() {
return pref.getInt(KEY_ID, 0);
}
}
And in your MainActivity you have to check if user is logged in or not:
public class MainActivity extends Activity {
// Session Manager Class
SessionManager session;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Session class instance
session = new SessionManager(getApplicationContext());
session.checkLogin();
.
// code goes here
...
If user is not logged in he will be redirected to LoginActivity.
In LoginActivity just check email/pass or whatever,... call:
session.createLoginSession(mEmail, mId);
and redirect user back to MainActivity
Saving credentials its up on you. Ofc its better to keep it in safe place and encoded ; )
There are many possible solutions:
1) Splashscreen
Theoretically we should not use splash screens :P
But in this case it will be super easy ;)
Intent mIntentMain = ...
Intent mIntentLogin = ...
boolean mIsUserLogged = ...
startActvity(mIsUserLogged ? mIntentMain : mIntentLogin);
2) Main Activity
Start main activity, and before filling the screen with data, ws calls etc, just after the onCreate, check credentials ;) if its
ok -> start parsing data / filling stuff
else -> finish main activity, show toast, open login activity
3) Fragments
Activity Main -> check credentials -> put login fragment or main fragment
Check for login in SharedPreferences takes a little time and if you implement this check via blank activity the launch time of your app will be increased without a reason (time for launch 2 activities instead of 1 activity)
you can do check in your MainActivity and if it fails then run LoginActivity
How are you handling signups? The whole login/signup/authentication flow, while seemingly easy on paper, can get pretty complex with lots of edge cases when you take into account multiple simultaneous logins, password changes, forgotten passwords, account deletions etc. That said, Android provides AccountManager designed specifically for this purpose and this is one of the better tutorials on how to use it.
You can view splash screen while loading the application and in that time to check the user name and password.
Or you can upload the main screen with charging indicator to the user knew something was going on and the application not stuck.
First approach:
I would suggest you to go with Fragments.
Launch MainActivity , check inside onCreate() whether the user's login session is valid, if it is valid go with your normal workflow, otherwise launch your LoginFragment
Second approach:
Go with a SplashActivity , check your login user session validity and decide the workflow
Third approach
Assume that user is logged in, and launch your MainActivity inside onCreate() check your users session validity , if invalid then launch LoginActivity and finish() your MainActivity
Undoubtly First one can be your best choice , but I should leave this decision to you. :)
I have a Settings activity in my android application which purpose is to save preferences upon an item selection. My problem is, my settings don't get saved. The following method is called every time a user selection is made:
public void savePreferences()
{
defaultVolumeUnit = MySingleton.getInstance().getDefaultVolumeUnit();
defaultPressureUnit = MySingleton.getInstance().getDefaultPressureUnit();
defaultTempUnit = MySingleton.getInstance().getDefaultTempUnit();
settings = getSharedPreferences(SettingsTAG, 0);
Editor editor = settings.edit();
editor.putInt("selectVolume", defaultVolumeUnit);
editor.putInt("selectPressure", defaultPressureUnit);
editor.putInt("selectTemperature", defaultTempUnit);
editor.commit();
}
I also use the following code in my MAIN activity where all the settings get restored upon start up:
public void restoreValues()
{
settings = getSharedPreferences(SettingsTAG, 0);
int SelectedVolume = settings.getInt("selectVolume", 0);
int SelectedPressure = settings.getInt("selectPressure", 0);
int SelectedTemperature = settings.getInt("selectTemperature", 0);
// Necessary assignments here...
}
I use global variables throughout my whole application and those get saved but the settings do not. I'm positive that both savePreferences() and restoreValues() method gets called but whatever the user had selected doesn't get saved.
In other words, nothing gets saved/restored. I don't know what I'm doing wrong but this issue has been driving me nuts. This used to work for me before but I'm doing a Settings UI revamp and the same code suddenly isn't working...
Any help please?
Think you should be doing this in your activity:
private SharedPreferences prefSettings;
public void restoreValues()
{
prefSettings = PreferenceManager.getDefaultSharedPreferences(this);
int SelectedVolume = prefSettings.getInt("selectVolume", 0);
int SelectedPressure = prefSettings.getInt("selectPressure", 0);
int SelectedTemperature = prefSettings.getInt("selectTemperature", 0);
// Necessary assignments here...
}
In your method that I've noticed, your parameters do not look right actually...why are you using SettingsTAG, with 0 as parameters to the getSharedPreference method? Is your activity extending PreferenceActivity? You should be using the context.
public void savePreferences()
{
defaultVolumeUnit = MySingleton.getInstance().getDefaultVolumeUnit();
defaultPressureUnit = MySingleton.getInstance().getDefaultPressureUnit();
defaultTempUnit = MySingleton.getInstance().getDefaultTempUnit();
//settings = getSharedPreferences(SettingsTAG, 0);
settings = PreferenceManager.getDefaultSharedPreferences(context); // Notice CONTEXT!
Editor editor = settings.edit();
editor.putInt("selectVolume", defaultVolumeUnit);
editor.putInt("selectPressure", defaultPressureUnit);
editor.putInt("selectTemperature", defaultTempUnit);
editor.commit();
}
Edit:
If you want to debug it, it might be better to do it this way:
public class PreferencesActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
private static final String TAG = "PreferencesActivity";
///.... code....
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){
Log.d(TAG, "onSharedPreferenceChanged() - key = " + key);
// Yup! The key within the shared preferences was changed... inspect 'em via Log!
}
The reason: you're "listening" on the changes whenever its made to confirm that you are indeed saving the preferences. When you're done with debugging, be sure to take out the Log calls so that it does not appear in the logcat.