使用共享首选项登录活动



我使用共享偏好进行登录活动。代码如下。

我登录时出错。它总是显示密码不正确。

任何人都可以帮助我改进代码,从而完成我的项目。

用户会话类

 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);
    }
}

Login活动中,您检索到"Register"共享首选项,您认为该首选项已初始化Register类中的用户名和密码。但是,在注册类中:

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

登录类中,您使用了:

private static final String PREFER_NAME = "Register";

这就是为什么当您在登录活动中从注册共享首选项中检索uname和password时,总是会得到默认值,而验证总是会给您false。在Register类中,将共享首选项的名称更改为"Register"。

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

你已经完成了

    sharedpreferences = getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);

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

你可以像一样使用它

session = new UserSession(getApplicationContext());

在两个类的onCreate内部。两个类中都不需要SharedPreferences对象。

您可以使用任何一种方式来匹配用于定义SharedPreferences的字符串,也可以实际使用UserSession代码。这个决定由你决定,但我建议不要把两者混为一谈。

您可能还想回顾一下该代码的来源教程,看看它的全部用法。

最新更新