-4
package com.trid.sharedtask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
    TextView userName, password;
    Button ok, cancel;
    SharedPreferences shared;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        userName = (TextView) findViewById(R.id.userName);
        password = (TextView) findViewById(R.id.password);
        ok = (Button) findViewById(R.id.ok);
        cancel = (Button) findViewById(R.id.cancel);

        userName.setText(shared.getString("key1", ""));
        password.setText(shared.getString("key1", ""));

        ok.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getApplicationContext(), Activity2.class);
        startActivity(intent);
        SharedPreferences shared = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = shared.edit();
        editor.putString("key1", userName.getText().toString().trim());
        editor.putString("key2", password.getText().toString().trim());
        editor.commit();

    }

}

I have to create a login page using shared preference. if the user enters first time in a activity, the username and password should be stored in shared preference. if the user enters in consecutive time, the shared preference fetch the data to username and password.

Thanks for your Help...!

2 Answers2

0

First you will check the value of shared preference. You will keep default value as blank or anything that you want. If the shared preference return blank value then you will store the details otherwise you will fetch the details and will compare with current value.

Sandeep
  • 1,814
  • 21
  • 25
0

In Onclick method check if the key exist in sharedpreference using contains("key") method like :

@Override
public void onClick(View v) {
    Intent intent = new Intent(getApplicationContext(), Activity2.class);
    startActivity(intent);
    SharedPreferences shared = getPreferences(Context.MODE_PRIVATE);
    if(shared.contains("username") && shared.contains("password")){

     //Get data from shared preference here and do whatever you want
    } else {

    SharedPreferences.Editor editor = shared.edit();
    editor.putString("key1", userName.getText().toString().trim());
    editor.putString("key2", password.getText().toString().trim());
    editor.commit();
    }
}
Akshay Bhat 'AB'
  • 2,690
  • 3
  • 20
  • 32