Good morning.
I have a login in my app, but I need to use the session data in the whole application. How should I do it? Thank you in advance.
Good morning.
I have a login in my app, but I need to use the session data in the whole application. How should I do it? Thank you in advance.
I'll give you some possibilities:
1. Pass the information by the intents of the activities
Intent intent = new Intent(this, MiActivity.class);
intent.putExtra("email", miEmail);
startActivity(intent);
//MiActivity
email = getIntent().getExtras().getString("email");
2. Use SharedPreferences:
Save data after login:
SharedPreferences prefs = getSharedPreferences("shared_login_data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("email", "[email protected]");
editor.commit();
Retrieve data when changing activity or fragment:
SharedPreferences prefs = getSharedPreferences("shared_login_data", Context.MODE_PRIVATE);
String email = prefs.getString("email", ""); // prefs.getString("nombre del campo" , "valor por defecto")
There is a way with SharedPreferences with the which you can create key
and values
and be able to access them in your Activity
When your user signs in, you can define
public static final String MyPREFERENCES = "MisPreferences" ;
public static final String userName = "nombreUsuario";
public static final String userPassword = "passwordUsuario";
String username = userName.getText().toString();
String password = passwordUser.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(userName , username);
editor.putString(userPassword , password);
editor.commit();
//redireccionas por ejemplo a otra Activity
perfil = new Intent(MainActivity.this,second_main.class);
startActivity(in);
And to access the data already saved in another Activity
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String username = getResources().getString("nombreUsuario");
A SharedPreferences object has an associated file containing key-value pairs and provides simple methods for reading and writing such pairs. Each SharedPreferences file is managed by the framework and can be private or shared.