登录活动使用共享Prefrence

时间:2016-05-06 20:17:42

标签: android sharedpreferences

我使用共享偏好设置了登录活动。代码如下。

我登录时遇到错误。它始终显示密码不正确。

任何正文帮助我改进代码,以便我完成我的项目。

UserSession Class

 package com.achal089.pestcontrol;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import java.util.HashMap;

/**
 * Created by as on 5/7/2016.
 */
public class UserSession {

    SharedPreferences pref;

    // Editor reference for Shared preferences
    SharedPreferences.Editor editor;

    // Context
    Context _context;

    // Shared preferences mode
    int PRIVATE_MODE = 0;

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

    // 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 Email = "Email";

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


    // 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 uName, String uPassword){
        // Storing login value as TRUE
        editor.putBoolean(IS_USER_LOGIN, true);

        // Storing name in preferences
        editor.putString(Email, uName);

        // Storing email in preferences
        editor.putString(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, Login.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(Email, pref.getString(Email, null));

        // user email id
        user.put(Password, pref.getString(Password, 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, MainActivity.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);
    }
}

登录活动

package com.achal089.pestcontrol;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends Activity {

    private static final String PREFER_NAME = "Register";

    UserSession session;

    private SharedPreferences sharedPreferences;



    TextView login;
    TextView pass;


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



     login = (TextView)findViewById(R.id.email);
        pass = (TextView)findViewById(R.id.password);


      Button buttonLogin = (Button) findViewById(R.id.btnLogin);

        sharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);


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

            @Override
            public void onClick(View arg0) {

                // Get username, password from EditText
                String username = login.getText().toString();
                String password = pass.getText().toString();

                // Validate if username, password is filled             
                if(username.trim().length() > 0 && password.trim().length() > 0){
                    String uName = null;
                    String uPassword =null;

                    if (sharedPreferences.contains("Email"))
                    {
                        uName = sharedPreferences.getString("Email", "");

                    }

                    if (sharedPreferences.contains("Password"))
                    {
                        uPassword = sharedPreferences.getString("Password", "");

                    }

                    // Object uName = null;
                    // Object uEmail = null;
                    if(username.equals(uName) && password.equals(uPassword)){

                        session.createUserLoginSession(uName,
                                uPassword);

                        // Starting MainActivity
                        Intent i = new  Intent(getApplicationContext(),MainActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

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

                        finish();

                    }else{

                        // username / password doesn't match&
                        Toast.makeText(getApplicationContext(),
                                "Username/Password is incorrect",
                                Toast.LENGTH_LONG).show();

                    }
                }else{

                    // user didn't entered username or password
                    Toast.makeText(getApplicationContext(),
                            "Please enter username and password",
                            Toast.LENGTH_LONG).show();

                }

            }
        });




    }



    public void Reg(View view)
    {
        Intent a = new Intent(Login.this,Register.class);
        startActivity(a);
    }


}
}

注册活动

package com.achal089.pestcontrol;

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.widget.TextView;

public class Register extends Activity {

    UserSession session;
    SharedPreferences sharedpreferences;
    TextView name;
    TextView address;
    TextView email;
    TextView phone;
    TextView occupation;
    TextView password;
    private static final String PREFER_NAME = "Register";

    public static final String Name = "nameKey";
    public static final String Email = "emailKey";
    public static final String Phone = "Phone";
    public static final String Address = "Address";
    public static final String Occupation = "Occupation";
    public static final String Password = "Password";

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

        name = (TextView) findViewById(R.id.editText6);
        address = (TextView) findViewById(R.id.editText7);
        email = (TextView) findViewById(R.id.editText9);
        phone = (TextView) findViewById(R.id.editText8);
        password = (TextView)findViewById(R.id.editText11);
        occupation = (TextView)findViewById(R.id.editText10);
        sharedpreferences = getSharedPreferences(PREFER_NAME,
                Context.MODE_PRIVATE);
        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));

        }

        if (sharedpreferences.contains(Occupation)) {
            occupation.setText(sharedpreferences.getString(Occupation, ""));
        }

        if (sharedpreferences.contains(Password)) {
            password.setText(sharedpreferences.getString(Password, ""));
        }


        if (sharedpreferences.contains(Address)) {
            address.setText(sharedpreferences.getString(Address, ""));

        }

        if (sharedpreferences.contains(Phone)) {
            phone.setText(sharedpreferences.getString(Phone, ""));

        }



    }


    public void Save(View view) {
        String n = name.getText().toString();
        String e = email.getText().toString();
        String w = phone.getText().toString();
        String m = address.getText().toString();
        String p = password.getText().toString();
        String v = occupation.getText().toString();
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(Name, n);
        editor.putString(Email, e);
        editor.putString(Phone, w);
        editor.putString(Address,m);
        editor.putString(Occupation,v);
        editor.putString(Password,p);
        editor.commit();


        Intent a = new Intent(Register.this, Login.class);
        startActivity(a);
    }

    public void Login (View view)
    {
        Intent a = new Intent(Register.this, Login.class);
        startActivity(a);
    }
}

2 个答案:

答案 0 :(得分:0)

您似乎没有正确使用UserSession类。

你已经完成了这个

    sharedpreferences = getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);

并使用了与session变量和登录活动不同的SharedPreferences(字符串参数不匹配)。此外,会话变量似乎在注册活动代码中完全未使用,并且未在登录活动中正确使用

您可以像

一样使用它
session = new UserSession(getApplicationContext());

在两个类的onCreate中。在任一类中都不需要SharedPreferences对象。

您可以使用匹配用于定义SharedPreferences的字符串的任一方式,或者您可以实际使用UserSession代码。这个决定取决于你,但我建议不要混淆这两个。

您可能还想返回代码来自的the tutorial以查看其完整用法。

答案 1 :(得分:0)

登录活动中,您检索了&#34;注册&#34;共享首选项,您认为已在注册类中初始化了用户名和密码。但是,在注册类中:

public static final String mypreference = "mypref";//this name is different

登录课程中,您使用了:

private static final String PREFER_NAME = "Register";

这就是为什么当您从Login活动中的Register共享首选项中检索uname和密码时,您将始终获得默认值,并且验证将始终为您提供错误。在注册类中,将共享首选项的名称更改为&#34;注册&#34;。