After the User logged in and ticked the checkbox for "Keep me Logged in", the activity will proceed to another activity where it has many EditTexts. However, if the user accidentally close/shutdown the device, the data will be retrieved upon going back to that application since the user ticked the "Keep me Logged in". I used onSaveInstanceState and onRestoreInstanceState but it doesn't help. Please help me with this.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
final EditText txt_Fname = (EditText) findViewById(R.id.txt_Fname);
final EditText txt_Mname = (EditText) findViewById(R.id.txt_Mname);
final EditText txt_Lname = (EditText) findViewById(R.id.txt_Lname);
final EditText txt_Suffix = (EditText) findViewById(R.id.txt_Suffix);
String Fname = txt_Fname.getText().toString();
String Mname = txt_Mname.getText().toString();
String Lname = txt_Lname.getText().toString();
String Suffix = txt_Suffix.getText().toString();
outState.putString("shared_fname", Fname);
outState.putString("shared_mname", Mname);
outState.putString("shared_lname", Lname);
outState.putString("shared_suffix", Suffix);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final EditText txt_Fname = (EditText) findViewById(R.id.txt_Fname);
final EditText txt_Mname = (EditText) findViewById(R.id.txt_Mname);
final EditText txt_Lname = (EditText) findViewById(R.id.txt_Lname);
final EditText txt_Suffix = (EditText) findViewById(R.id.txt_Suffix);
txt_Fname.setText(savedInstanceState.getString("shared_fname"));
txt_Mname.setText(savedInstanceState.getString("shared_mname"));
txt_Lname.setText(savedInstanceState.getString("shared_lname"));
txt_Suffix.setText(savedInstanceState.getString("shared_suffix"));
}
Use SharedPreference to save data, when you switching between activities and shutting down the application. Below are example methods, you can call during onCreate() and onDestroy().
void saveText() {
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
ed.putString(SAVED_TEXT, etText.getText().toString());
ed.commit();
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
}
void loadText() {
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(SAVED_TEXT, "");
etText.setText(savedText);
Toast.makeText(this, "Text loaded", Toast.LENGTH_SHORT).show();
}
Related
i programmed my register activity to get my user details and store it with SharePreferences
Now , im trying to get those values stored in the data to log in in my app but it seems im missing something, when i put anything in my edittexts in my login layout it logs in without checking the user
RegisterActivity.class
public class RegistrarUsuario extends AppCompatActivity {
private Button mBtnRegistrarUsuario;
private TextView mRegistrarTxt;
private EditText mUsername,mPassword,mSecondPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrar_usuario);
mRegistrarTxt = (TextView) findViewById(R.id.titulo2);
mUsername = (EditText) findViewById(R.id.nombreUsuario);
mPassword = (EditText) findViewById(R.id.primeraContraseña);
mSecondPassword = (EditText) findViewById(R.id.segundaContraseña);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mRegistrarTxt.setTypeface(fuente);
mBtnRegistrarUsuario = (Button) findViewById(R.id.btnRegistrarUsuario);
mBtnRegistrarUsuario.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String secondpassword = mSecondPassword.getText().toString().trim();
if(username.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese un usuario.", Toast.LENGTH_SHORT).show();
}
else if(password.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese contraseña.", Toast.LENGTH_SHORT).show();
}
else if(secondpassword.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Confirme su contraseña.", Toast.LENGTH_SHORT).show();
}
else if(password.equals(secondpassword)){
SharedPreferences.Editor editor = preference.edit();
editor.putString("Username",username);
editor.putString("Password",password);
editor.putString("SecondPassword",secondpassword);
editor.commit();
finish();
Toast.makeText(RegistrarUsuario.this, "Usuario creado con exito!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegistrarUsuario.this,PantallaPrincipal.class);
startActivity(intent);
}
else{
Toast.makeText(RegistrarUsuario.this, "No coinciden las contraseñas.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
** LoginActivity.class**
public class MainActivity extends AppCompatActivity {
private EditText mUsername,mPassword;
private Button mLoginBtn,mBtnRecuperar,mBtnRegistrar;
private TextView mTextView;
private static String usuario ="admin";
private static String contraseña="123";
private final String KEY_USERNAME = "username";
private final String KEY_PASSWORD = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = (EditText) findViewById(R.id.usuario);
mPassword = (EditText) findViewById(R.id.contraseña);
mLoginBtn = (Button) findViewById(R.id.btnIngresar);
mTextView = (TextView) findViewById(R.id.titulo);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mTextView.setTypeface(fuente);
mBtnRecuperar = (Button) findViewById(R.id.btnRecuperar);
mBtnRecuperar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RecuperarContrasenia.class);
startActivity(intent);
}
});
mBtnRegistrar = (Button) findViewById(R.id.btnRegistrar);
mBtnRegistrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RegistrarUsuario.class);
startActivity(intent);
}
});
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
String userDetails = preference.getString(username + password + "data","No information on that user.");
SharedPreferences.Editor editor = preference.edit();
editor.putString("display",userDetails);
editor.commit();
if(mUsername.getText().toString().trim().length() == 0 && mPassword.getText().toString().trim().length() == 0 ){
Toast.makeText(MainActivity.this, "Los campos estan vacios", Toast.LENGTH_SHORT).show();
}else
{
if(mUsername.getText().toString().trim().equals(username) && mPassword.getText().toString().trim().equals(password)){
Toast.makeText(MainActivity.this, "Bienvenido", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this,PantallaPrincipal.class);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Los campos son incorrectos", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
i dont know what im missing that it dont verify the user if exists or login with the credentials i make in RegisterActivity.class
thanks
You are never retrieving the username and password from SharedPreferences. And at the end you are checking the information the user puts in the TextEdits against itself so the validation always returns true to any non empty value.
Change this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
To this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = preference.getString("Username", "");
String password = preference.getString("Password", "");
I am developing an app,in that i am maintaining Session using Shared Preferences.I that when user login,i am using their email id for further use.But when i tried to use that email in another activity, it is showing null.
Below in my code for mainActivity:
public class main extends AppCompatActivity {
public Button submit;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String email = "emailkey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
submit = (Button) findViewById(R.id.btn_login);
ImageView i1 = (ImageView) findViewById(R.id.imgLogo);
String checkBoxText = "I agree to all the";
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
checkBox.setText(Html.fromHtml(checkBoxText));
checkBox.setMovementMethod(LinkMovementMethod.getInstance());
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText e1 = (EditText) findViewById(R.id.input_email);
EditText p1 = (EditText) findViewById(R.id.input_password);
String e = e1.getText().toString();
final String password = p1.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(email, e);
editor.commit();
Here is my code for another activity:
String e,email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.internshipsdetails);
SharedPreferences sharedpreferences = getSharedPreferences(main.MyPREFERENCES, Context.MODE_PRIVATE);
sharedpreferences.getString(email,e);
String url = "url?COMP_REQ_ID=" + title + "&StuEmail=" + e;
AQuery mAQuery = new AQuery(InternShipsDetails.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
#Override
public void callback(String url, String data, AjaxStatus status) {
super.callback(url, data, status);
if (BuildConfig.DEBUG) {
Log.d("###$Request URL", url + "");
Log.d("###$Response ", data + "");
Log.d("###$Status Message : ", status.getMessage() + "");
Log.d("###$Status Code : ", status.getCode() + "");
}
You can manage session by changing shared preference values after doing logout action and check preference again at the time of login also. You can save current time also in a string at login and logout action. Make sure to use private shared preferences.
You are passing the wrong key to shared Pref because of that you are getting null.
Following is the updated code of yours which will give you the stored email address:
SharedPreferences sharedpreferences = getSharedPreferences(main.MyPREFERENCES, Context.MODE_PRIVATE);
e = sharedpreferences.getString(main.email,"");
String url = "url?COMP_REQ_ID=" + title + "&StuEmail=" + e;
Happy coding !!!
getString (String key, String defValue) method returns a String. So, you need to catch the output in a string variable.
Also, you are passing a nullkey. You need to pass the same key using which you saved the value.
So, in your case it would be
e = sharedpreferences.getString("emailkey","nodata");
public class Loginscreen extends Activity {
private EditText phonenumber,password;
private Button signin,joinus,supportus;
private TextView forgot_password;
String mobilenumber;
String passwordtxt;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
phonenumber = (EditText) findViewById(R.id.edt_username);
password = (EditText) findViewById(R.id.edt_password);
signin = (Button) findViewById(R.id.bt_signin);
joinus = (Button) findViewById(R.id.bt_joinus);
supportus = (Button) findViewById(R.id.bt_supportus);
forgot_password = (TextView) findViewById(R.id.txt_remember_pawd);
final String user = phonenumber.getText().toString();
final String pass = password.getText().toString();
signin.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//final Intent intent;
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
final String pasword = pref.getString("pwd", null);
final String phnenumber = pref.getString("mobilenumber", null);
if ( pass == pasword && user == phnenumber && !pass.isEmpty()){
Toast.makeText(Loginscreen.this, "correct ", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(Loginscreen.this, "Incorrect Mobile number or password", Toast.LENGTH_SHORT).show();
}
}
});
in above code how can i compare the shared preference value with current edit text value....i used shared preference in another page..
#Override
public void onPostExecute(String result) {
JSONObject jsonobject = null;
try {
jsonobject = new JSONObject(result);
JSONObject object = jsonobject.getJSONObject("data");
String id = object.getString("_id");
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
pref.getString("key_name1",null);
//final String encoded = pref.getString("key_name1",null);
String password = getIntent().getStringExtra("_password");
String mobilen = getIntent().getStringExtra("mobile");
SharedPreferences.Editor editor = pref.edit();
editor.putString("pwd",password);
editor.putString("mobilenumber",mobilen);
editor.putString("user_id",id);
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
the above code is present in another activity..how can i use that shared preference value in LoginScreen to compare both the values are equal are not
You should use equals() instead of ==.
Change this part of the code:
if ( pass == pasword && user == phnenumber && !pass.isEmpty()){
Toast.makeText(Loginscreen.this, "correct ", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(Loginscreen.this, "Incorrect Mobile number or password", Toast.LENGTH_SHORT).show();
}
to:
if ( password.getText().toString().equals(password) && phonenumber.getText().toString().equals(phnenumber) && !pass.isEmpty()){
Toast.makeText(Loginscreen.this, "correct ", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(Loginscreen.this, "Incorrect Mobile number or password", Toast.LENGTH_SHORT).show();
}
You can do this with intent.
in your first screen write below code on some button click.
Intent i=new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("editTextvalue",editText.getText().toString());
startActivity(i);
in your second screen write below code in onCreate()
String value=getIntent().getStringExtra("editTextvalue");
campare this value with your sharedPreferences value.
I have two strings that I want to save them I wrote the code as shown below
public class MainActivity extends Activity {
Button result;
EditText b951, b9511, sum95, t95, p95
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LoadPreferences();
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
}
public void close (View v){
SavePreferences("p2b951", b951.getText().toString());
SavePreferences("p2b9511", b9511.getText().toString());
finish();
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String p1b951 = sharedPreferences.getString("p2b951", "1");
String p1b9511 = sharedPreferences.getString("p2b9511", "1");
b951.setText(p1b951);
b9511.setText(p1b9511);
}
public void result (View v) {
try {
int ib951 = Integer.parseInt(b951.getText().toString());
int ib9511 = Integer.parseInt(b9511.getText().toString());
int iisum95 = (ib9511-ib951);
sum95.setText(String.valueOf(iisum95));
int isum95 = Integer.parseInt(sum95.getText().toString());
int ip95 = Integer.parseInt(p95.getText().toString());
int pp95 = (isum95*ip95);
t95.setText(String.valueOf(pp95));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
But it seems there is a problem with this two lines:
b951.setText(p1b951);
b9511.setText(p1b9511);
I tried this
b951.setText(String.valueOf.p1b951);
b9511.setText(String.valueOf.p1b9511);
Also the problems still exist
When I open the application and when the loadpreferences is called the app will force close
The logcat show me that the error is with this two lines for sure it's just with the first line coz he didn't get the second but they are the same so they are wrong wroted
Any help??
Change onCreate() as follows:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
LoadPreferences();
}
This is because you are using the EditTexts in the LoadPreferences() without calling findViewById() on the EditTexts.
You can follow and help from like codes. such as
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
it any confused about this then follow this link
I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.
My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.
Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.
public SharedPreferences sp;
public Editor e;
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settingmenu);
//SP
sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
Button tt = (Button)findViewById(R.id.savebutton);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public void save(View view)
{
//THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
savethethings();
this.finish();
return;
}
public String finishedtext(String userstring)
{
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
if(smsintroduction.isEmpty())
{
if(smsbody.isEmpty())
{
if(checkboxtext.isEmpty())
{
if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
{
//Essentially the DEFAULT if they're ALL null
smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
}
}
}
}
Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();
String thetext = "";
thetext = smsintroduction + " " + smsbody + " " + checkboxtext;
return thetext;
}
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
// if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
// {
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
Sample code given below.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setIntroMessage(String data) {
editor.putString("intro", data);
editor.commit();
}
public String getIntroMessage() {
return pref.getString("intro", null);
}
}