0

Hola tengo un login y un checkbox y quiero usarlo para que me recuerde el usuario y la contraseña como podria hacerlo?

Aqui dejo el login activity:

public class LoginActivity extends AppCompatActivity {

EditText email, password;
private Button sign_in_register;
private RequestQueue requestQueue;
private static final String URL = "";
private StringRequest request;
public CheckBox ch;
public static final String MY_PREFS_NAME = "user_pass_pref";


@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);


    email = (EditText) findViewById(R.id.editText2);
    password = (EditText) findViewById(R.id.editText);
    sign_in_register = (Button) findViewById(R.id.button);
    ch = (CheckBox)findViewById(R.id.checkBox);

    if(ch.isChecked())
    {
        SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
        editor.putString("username", email.getText().toString());
        editor.putString("password1", password.getText().toString());
        editor.apply();
    }
    SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
    String restoredText = prefs.getString("username", null);
    if (restoredText != null) {
        String name = prefs.getString("username", "");
        String password1 = prefs.getString("password1", "");
        email.setText(name);
        password.setText(password1);
    }


    requestQueue = Volley.newRequestQueue(this);

    sign_in_register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.names().get(0).equals("success")) {
                            Toast.makeText(getApplicationContext(), "SUCCESS " + jsonObject.getString("success"), Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(getApplicationContext(), MainActivity.class));
                        } else {
                            Toast.makeText(getApplicationContext(), "Error" + jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    HashMap<String, String> hashMap = new HashMap<String, String>();
                    hashMap.put("email", email.getText().toString());
                    hashMap.put("password", password.getText().toString());

                    return hashMap;
                }
            };

            requestQueue.add(request);
        }
    });
}
}

2 respuestas 2

1

Utiliza SharedPreferences, yo lo he realizado así y funciona (Ignora lo de VolleyDataSource). Aquí lo explica muy bien de todos modos http://www.sgoliver.net/blog/preferencias-en-android-i-shared-preferences/

private Button iniciarSesion;
private EditText email, password;
private SwitchCompat switchCompat;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.signin);

    iniciarSesion = findViewById(R.id.btn_iniciarSesion);
    email = findViewById(R.id.txt_signin_email);
    password = findViewById(R.id.txt_signin_password);
    switchCompat = findViewById(R.id.switch_signin);

    final SharedPreferences prefs = getSharedPreferences("recordarmeWallet", Context.MODE_PRIVATE);
    String emailtext = prefs.getString("email", "");
    String pass = prefs.getString("password", "");
    boolean stateSwitch = prefs.getBoolean("stateSwitch", false);
    switchCompat.setChecked(stateSwitch);
    email.setText(emailtext);
    password.setText(pass);

    iniciarSesion.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            if(switchCompat.isChecked()){

                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("email", email.getText().toString());
                editor.putString("password", password.getText().toString());
                editor.putBoolean("stateSwitch", switchCompat.isChecked());
                editor.commit();

            } else {
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("email","");
                editor.putString("password", "");
                editor.putBoolean("stateSwitch", switchCompat.isChecked());
                editor.commit();
            }
            VolleyDataSource.getInstance(v.getContext() , 10).checkLoging( email.getText().toString(), password.getText().toString());
        }
    });

}
1

Utiliza SharePreferences para almacenar el usuario y contraseña.

Para guardar has esto:

Define una variable estatica con el nombre de la preferencia:

public static final String = MY_PREFS_NAME = "user_pass_pref";

Luego cuando quieras guardar has lo siguiente:

if(checkbox.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("username", email.getText().toString());
 editor.putString("password", password.getText().toString());
 editor.apply();
}

Entonces para leerlos en caso de que vaya a hacer login otra vez:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
  String name = prefs.getString("username", "");
  String password = prefs.getString("password", ""); 
  username.setText(name);
  password.setText(password);
}

Actualizacion:

Estas guardando el usuario y contraseña cuando inica el activity y deberia de ser cuando se haya clic a login:

 //...

@Override
protected void onCreate(final Bundle savedInstanceState) {

    //...

    sign_in_register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(LoginActivity.this.ch.isChecked())
            {
                // guardas el usuario y contraseña cuando se haya hecho clic sobre el boton
                SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
                editor.putString("username", LoginActivity.this.email.getText().toString());
                editor.putString("password1", LoginActivity.this.password.getText().toString());
                editor.apply();
            }

            //...
9
  • me da error en MY_PREFS_NAME
    – Ismael
    el 18 sep. 2017 a las 15:31
  • no hace nada, hay algo mal? he subido el codigo con el sharedpreferences
    – Ismael
    el 18 sep. 2017 a las 15:48
  • no me guarda los datos de usuario y contraseña
    – Ismael
    el 18 sep. 2017 a las 15:51
  • como si no hubiese hecho nada
    – Ismael
    el 18 sep. 2017 a las 15:52
  • lo mismo, sin hacer nada
    – Ismael
    el 18 sep. 2017 a las 16:19

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.