1

I know there are n number of examples in android for shared preferences but I want to Register and store the info in shared preferences and in database using JSON. And then fetch data from JSON and Login with those credentials. If user is already logged in open Main Activity,else go to Splash screen and then open Login Activity. Please go through my detailed code :

RegisterActivity :

public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {

    private EditText password, phone, email;
    public static EditText name;
    ServerRequests serverRequests;
    JSONParser jsonParser;
    private Button registerButton;
    TextView alreadyMember;
    Editor editor;
    UserSession session;

    SharedPreferences sharedPreferences;
    public static final String MyPREFERENCES = "MyPrefs";
    public static final String Name1 = "nameKey";
    public static final String Phone1 = "phoneKey";
    public static final String Email1 = "emailKey";
    public static final String Password1 = "passwordKey";


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

        jsonParser = new JSONParser();
        serverRequests = new ServerRequests(getApplicationContext());
        serverRequests.setRegistereponse(this);


        alreadyMember = (TextView) findViewById(R.id.alreadyMember);

        name = (EditText) findViewById(R.id.FName);
        phone = (EditText) findViewById(R.id.PhoneNum);
        email = (EditText) findViewById(R.id.mail);
        password = (EditText) findViewById(R.id.password);
        registerButton = (Button) findViewById(R.id.email_sign_in_button);

        sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CharSequence temp_emailID = email.getText().toString();
                if (name.getText().toString().length() == 0) {
                    name.setError("Please enter your name");
                    name.requestFocus();

                } else if (phone.getText().toString().length() == 0) {
                    phone.setError("Please enter your phone number");
                    phone.requestFocus();

                } else if (!isValidEmail(temp_emailID)) {
                    email.setError("Please enter valid email");
                    email.requestFocus();

                } else if (password.getText().toString().length() == 0) {
                    password.setError("Please enter password");
                    password.requestFocus();

                } else {


                    try {
                        String Name = name.getText().toString();
                        String Email = email.getText().toString();
                        String Password = password.getText().toString();
                        String Phone = phone.getText().toString();

                        JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
                        Log.e("final Json", obj.toString());
                        serverRequests.register(obj);


                        SharedPreferences.Editor editor = sharedPreferences.edit();

                        editor.putString(Name1, Name);
                        editor.putString(Email1, Email);
                        editor.putString(Password1, Password);
                        editor.putString(Phone1, Phone);
                        editor.commit();
                        //    Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();


                    } catch (Exception e) {

                    }
                }

                //   startActivity(new Intent(RegisterActivity.this, LoginActivity.class));

            }
        });

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

                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        });

    }


    @Override
    public void onRegsiterReposne(JSONObject object) {
        Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();

    }

    public final static boolean isValidEmail(CharSequence target) {
        if (TextUtils.isEmpty(target)) {
            return false;
        } else {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    }

}

LoginActivity :

public class LoginActivity extends AppCompatActivity implements ServerRequests.Loginreponse {

    private static final String PREFER_NAME = "Reg";

    private Button email_sign_in_button;
    private EditText email, password;
    private TextView notMember, forgotPass;

    UserSession session;
    private SharedPreferences sharedPreferences;

    ServerRequests serverRequests;
    JSONParser jsonParser;


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

        jsonParser = new JSONParser();
        serverRequests = new ServerRequests(getApplicationContext());
        serverRequests.setLoginreponse(this);

        notMember = (TextView) findViewById(R.id.notMember);
        forgotPass = (TextView) findViewById(R.id.forgotPass);

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

                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                finish();
            }
        });

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

                startActivity(new Intent(LoginActivity.this, ForgotPassword.class));

            }
        });


        // get Email, Password input text
        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.pass);


        // User Login button
        email_sign_in_button = (Button) findViewById(R.id.login);

        sharedPreferences = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);


        // Login button click event
        email_sign_in_button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                try {
                    String Email = email.getText().toString();
                    String Password = password.getText().toString();

                    JSONObject obj = jsonParser.makeLoginJson(Email, Password);
                    Log.e("final Json", obj.toString());
                    serverRequests.login(obj);


                } catch (Exception e) {

                }

                //   startActivity(new Intent(LoginActivity.this, MainActivity.class));
                //    finish();

            }
        });
    }

    @Override
    public void onLoginReposne(JSONObject object) {

        Toast.makeText(LoginActivity.this, "helloo" + object.toString(), Toast.LENGTH_SHORT).show();


        if (object.toString().contains("true")) {

            Toast.makeText(LoginActivity.this, "Logged in..", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();

        }


    }
}

SplashScreen :

public class SplashScreen extends Activity {

    Thread splashTread;
    SharedPreferences preferences;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        StartAnimations();
    }

    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        Window window = getWindow();
        window.setFormat(PixelFormat.RGBA_8888);
    }

    private void StartAnimations() {
        Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
        anim.reset();
        LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay);
        l.clearAnimation();
        l.startAnimation(anim);

        anim = AnimationUtils.loadAnimation(this, R.anim.translate);
        anim.reset();

        ImageView iv = (ImageView) findViewById(R.id.splashImage);
        iv.clearAnimation();
        iv.startAnimation(anim);

    /*    TextView tv = (TextView) findViewById(R.id.splashText);
        tv.clearAnimation();
        tv.startAnimation(anim);*/


        splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    int waited = 0;
                    // Splash screen pause time
                    while (waited < 3500) {
                        sleep(100);
                        waited += 100;
                    }

                    startNextScreen();


                } catch (InterruptedException e) {
                    // do nothing
                } finally {
                    SplashScreen.this.finish();
                }

            }
        };
        splashTread.start();

    }

    private void startNextScreen() {
        preferences = getSharedPreferences("TrainingApp", MODE_PRIVATE);
        String userLoginStatus = preferences.getString("userLoginStatus", "no");
        if (userLoginStatus.equals("no")) {
            Intent intent = new Intent(SplashScreen.this,
                    LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivity(intent);
            SplashScreen.this.finish();
        } else {
            Intent intent = new Intent(SplashScreen.this,
                    MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivity(intent);
            SplashScreen.this.finish();
        }

    }

}

JSONParser class :

public class JSONParser {

    //----------For Register

    public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {

        JSONObject object = new JSONObject();

        object.put("name", name);
        object.put("email", email);
        object.put("password", password);
        object.put("phone", phone);
        // if its in array------
       /*JSONObject finalObject=new JSONObject();
       finalObject.put("request",object);
       return finalObject;*/
        return object;
    }

    //--------For Login--------------------------------------------------------

    public JSONObject makeLoginJson(String Name, String password) throws JSONException {

        JSONObject object = new JSONObject();

        object.put("userName", Name);
        object.put("password", password);
        /*JSONObject finalObject=new JSONObject();
        finalObject.put("request",object);
        return finalObject;*/
        return object;
    }
}

ServerRequests class :

  // ---------------- for register------------------------------------------------------------------------------

    public void setRegistereponse(Registereponse registereponse) {
        this.registereponse = registereponse;
    }

    private Registereponse registereponse;

    public interface Registereponse {
        void onRegsiterReposne(JSONObject object);
    }

    public void register(JSONObject jsonObject) {


        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Log.e("Json response", "" + response);
                            boolean b = response.getBoolean("success");

                            if (registereponse != null) {
                                registereponse.onRegsiterReposne(response);

                            }

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

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error ", "" + error);
                    }
                }
        );

        queue.add(jsonObjectRequest);
    }


    // --------------For Login ---------------------------------------------------------------------------

    public void setLoginreponse(Loginreponse loginreponse) {
        this.loginreponse = loginreponse;
    }

    private Loginreponse loginreponse;

    public interface Loginreponse {
        void onLoginReposne(JSONObject object);
    }

    public void login(JSONObject jsonObject) {


        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.LOGIN_URL, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Log.e("Json response", "" + response);
                            boolean b = response.getBoolean("success");

                            if (loginreponse != null) {
                                loginreponse.onLoginReposne(response);

                            }

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

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error ", "" + error);
                    }
                }
        );

        queue.add(jsonObjectRequest);
    }

UserSession class :

public class UserSession {
    // Shared Preferences reference
    SharedPreferences pref;

    // Editor reference for Shared preferences
    Editor editor;

    // Context
    Context _context;

    // Shared preferences mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    public static final String PREFER_NAME = "Reg";

    // All Shared Preferences Keys
    public static final String IS_USER_LOGIN = "IsUserLoggedIn";

    // User name (make variable public to access from outside)
    public static final String KEY_NAME = "Name";

    // Email address (make variable public to access from outside)
    public static final String KEY_EMAIL = "Email";

    // password
    public static final String KEY_PASSWORD = "Password";

    public static final String KEY_PHONE = "PhoneNumber";

    public static final String KEY_QUALIFICATION = "Qualification";


    // Constructor
    public UserSession(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    //Create login session
    public void createUserLoginSession(String uEmail, String uPassword) {
        // Storing login value as TRUE
        editor.putBoolean(IS_USER_LOGIN, true);

        // Storing name in preferences
        editor.putString(KEY_EMAIL, uEmail);

        // Storing email in preferences
        editor.putString(KEY_PASSWORD, uPassword);

        // commit changes
        editor.commit();
    }

    /**
     * Check login method will check user login status
     * If false it will redirect user to login page
     * Else do anything
     */
    public boolean checkLogin() {
        // Check login status
        if (!this.isUserLoggedIn()) {

            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, LoginActivity.class);

            // Closing all the Activities from stack
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            _context.startActivity(i);

            return true;
        }
        return false;
    }


    /**
     * Get stored session data
     */
    public HashMap<String, String> getUserDetails() {

        //Use hashmap to store user credentials
        HashMap<String, String> user = new HashMap<String, String>();

        // user name
        user.put(KEY_NAME, pref.getString(KEY_NAME, null));

        // user email id
        user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

        user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));

        user.put(KEY_PHONE, pref.getString(KEY_PHONE, null));

        user.put(KEY_QUALIFICATION, pref.getString(KEY_QUALIFICATION, null));

        // return user
        return user;
    }

    /**
     * Clear session details
     */
    public void logoutUser() {

        // Clearing all user data from Shared Preferences
        editor.clear();
        editor.commit();

        // After logout redirect user to MainActivity
        Intent i = new Intent(_context, LoginActivity.class);

        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        _context.startActivity(i);
    }


    // Check for login
    public boolean isUserLoggedIn() {
        return pref.getBoolean(IS_USER_LOGIN, false);
    }
}
Sallu
  • 141
  • 3
  • 17
  • _I want to store Register and Login information in shared preferences in android_ OK, what is your question here? – JonZarate Mar 14 '17 at 10:07
  • @JonZarate I want to store info using shared preferences and login using the data from JSON. If user is already logged in go to Main Activity else Splash screen – Sallu Mar 14 '17 at 10:10
  • I know what you want to do, what I don't know is where you are having trouble. _it is not working_ is not a valid question. – JonZarate Mar 14 '17 at 10:12
  • How much you achieve? and when and where is the problem? @Sallu – Zaki Pathan Mar 14 '17 at 10:12
  • 1
    @JonZarate I am trying to find a solution.. the code is not working as expected. I am able to register and login and the data is also stored in database. I want to manage user sessions properly using shared preferences. How can i do it? – Sallu Mar 14 '17 at 10:14
  • @ZakiPathan I want to store user sessions properly – Sallu Mar 14 '17 at 10:15
  • What is a user session? What does _manage user sessions properly_ mean? Edit your post and add specific questions we can answer. _How can I do it?_ is not an accurate question. – JonZarate Mar 14 '17 at 10:16
  • @Sallu you are storing it correctly but youe preference name is public static final String MyPREFERENCES = "MyPrefs"; and you are fetching preferences = getSharedPreferences("TrainingApp", MODE_PRIVATE); with "TrainingApp". please check – Zaki Pathan Mar 14 '17 at 10:17
  • @ZakiPathan what should I do in Login Activity? Can you edit my code? I have done all half code. – Sallu Mar 14 '17 at 10:21
  • In Login Activity when successfully logged in at that time add in sharedpreference userLoginStatus yes @Sallu – Zaki Pathan Mar 14 '17 at 10:34
  • @ZakiPathan not working properly..if you can show me in detail – Sallu Mar 15 '17 at 05:00
  • check my answer @Sallu – Zaki Pathan Mar 15 '17 at 06:29
  • @ZakiPathan http://stackoverflow.com/questions/42971772/showing-correct-response-in-postman-but-wrong-response-in-app help me on this – Sallu Mar 23 '17 at 09:27
  • @ZakiPathan I would be happy if you help me on this http://stackoverflow.com/questions/42971772/showing-correct-response-in-postman-but-wrong-response-in-android-app?noredirect=1#comment73042072_42971772 – Sallu Mar 28 '17 at 04:53

1 Answers1

6

At the time of login successfull put this code:

prefs = getSharedPreferences("logindetail", 0);
                        SharedPreferences.Editor edit = prefs.edit();
                        edit.putString("userLoginStatus", "yes");
                        edit.commit();

At the time of logout use this:

prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
                                edit.clear();
                                edit.commit();

And at the time of checking if user is login or not use below code:

 Loginprefs = getApplicationContext().getSharedPreferences("logindetail", 0);
            userLoginStatus = Loginprefs.getString("userLoginStatus", null);
if(userLoginStatus.tostring().equals("yes")){
    //the user is login
}else{
    //user is logout
}

Hope this helps you

Zaki Pathan
  • 1,762
  • 1
  • 13
  • 26