Shared Preferences does not store login using JSON

1

I am not able to save the login using JSON, it logs in but when I close the application and start again it did not save the login.

private EditText editTextLogin;
private EditText editTextSenha;
private CheckBox checkBoxLembrarLogin;
private Button buttonLogin;
private Button buttonEsqueceuSenha;
private static final String PREF_NAME = "MainActivity";

// Clase JSONParser
JSONParser jsonParser = new JSONParser();

private static final String LOGIN_URL = "ENDEREÇO DA PAGINA COM JSON";

// Resposta do JSON
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

private ProgressDialog pDialog;

private static String username;
private static String password;

private static SharedPreferences sp;
private static SharedPreferences.Editor editor;

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

    editTextLogin = (EditText) findViewById(R.id.editTextLogin);
    editTextSenha = (EditText) findViewById(R.id.editTextSenha);

    checkBoxLembrarLogin = (CheckBox) findViewById(R.id.checkBoxLembrarLogin);

    buttonLogin = (Button) findViewById(R.id.buttonLogin);
    buttonLogin.setOnClickListener(this);

    buttonEsqueceuSenha = (Button) findViewById(R.id.buttonEsqueceuSenha);
    buttonEsqueceuSenha.setOnClickListener(this);

}

@Override
protected void onStart() {
    super.onStart();

    getSupportActionBar().setTitle(R.string.app_name);
    getSupportActionBar().setSubtitle(R.string.app_slogan);

         this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    // VERIFICA SHAREDPREFERENCES
    sp = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
    String login1 = sp.getString("username", "");
    String password1 = sp.getString("password", "");

    if(login1.equals(username) && password1.equals(password)){
        Intent intent = new Intent(MainActivity.this, UsuarioComum.class);
        startActivity(intent);
    }

}

@Override
public void onClick(View v) {

    if(v == buttonLogin){
        new AttemptLogin().execute();
    }

    else if(v == buttonEsqueceuSenha){
    }

}

class AttemptLogin extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Realizando Login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        int success;

        username = editTextLogin.getText().toString();
        password = editTextSenha.getText().toString();

        try {
            // Building Parameters
            List params = new ArrayList();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                    params);

            // check your log for json response
            Log.d("Tentando realizar login...", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Logado com sucesso!!!", json.toString());

                if(checkBoxLembrarLogin.isChecked()){

                    sp = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
                    editor = sp.edit();
                    editor.putString("username", username);
                    editor.putString("password", password);
                    editor.commit();

                } else {
                }

                Intent i = new Intent(MainActivity.this, UsuarioComum.class);
                finish();
                startActivity(i);

                return json.getString(TAG_MESSAGE);

            } else {
                Log.d("Falha no login! Verifique sua conexão com a internet ou se os dados estão corretos!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "Verifque sua conexão com a internet...", Toast.LENGTH_SHORT).show();
        }

        return null;

    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null) {
            Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
        }
    }
}

}

    
asked by anonymous 10.02.2015 / 19:17

1 answer

1

You'll need something like this:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String access_token = preferences.getString("username", null);

    if(access_token!=null){
    Log.d("Existe um username salvo neste dispositivo, agora deve-se criar a lógica para verificar a autenticação aqui neste if.", json.toString());
    }
    
10.02.2015 / 21:16