安卓Android本地Sqlite实现注册账号和登录功能

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lift_class/article/details/51472416

实现了注册账号时将数据写入本地SQLite,登录账号时从本地SQLite匹配数据,并有记住密码功能,以及通过改密口令(类似于密保问题)修改密码的功能

思路很简单,登录账号的时候,先去数据库匹配账号,如果匹配到了相同账号,再去匹配同一行的密码,匹配成功则登录成功,匹配不成功则登录失败。如果没有匹配到账号,则也是登录失败。

注册账号的时候,先去匹配账号是否存在,如果账号存在,则提示账号已经存在,如果数据库中不存欲注册的账号,则允许注册。

在注册的时候,可以通过判断输入内容进行限制,如账号格式,密码位数,改密口令这些,我这里只对密码位数进行了限制。

如果账号界面及登录界面都输入了内容,则进行匹配:

db = new RegisterHelper(this, "user", null, RegisterHelper.REGISTER_DB_VERSION).getReadableDatabase();
            Cursor cursor = db.query("user", new String[]{"user", "pass"}, null, null, null, null, null);
            boolean login = false;//账号密码是否匹配
            //从数据库中匹配账号密码
            while (cursor.moveToNext()) {
                if (name.equals(cursor.getString(cursor.getColumnIndex("user")))
                        && pass.equals(cursor.getString(cursor.getColumnIndex("pass")))) {//用户名匹配后才会去匹配密码:&&逻辑的好处
                    login = true;
                    break;
                }
            }
接下来判断login,如果允许登录,则再判断有没有勾选记住密码:

//如果匹配成功,判断是否勾选记住账号,并进行账号信息存储
            if (login) {
                SharedPreferences.Editor editor = getSharedPreferences("remember", MODE_PRIVATE).edit();//这里利用SharedPreferences进行存储
                if (remember.isChecked()) {//如果勾选了记住密码
                    editor.putBoolean("remember", true);//是否保存了密码,在这个Activity创建的时候先判断此内容,如果为true则读取并写入输入框,实现记住密码
                    editor.putString("name", name);
                    editor.putString("pass", pass);
                    editor.commit();
                } else {
                    editor.clear();
                }
                editor.commit();
                Intent intent = new Intent(this, Main_Activity.class);
                startActivity(intent);
            } else {
                //账号密码在数据库中匹配不成功。即login==false
                Toast.makeText(this, "账号与密码不匹配", Toast.LENGTH_SHORT).show();
            }

在创建Acitivity的时候,判断是否保存了密码,如果保存了,从而实现将保存的密码输入到输入框中,在Activity的onCreate方法中调用此方法就行了


private void isRemember() {
        SharedPreferences prefer = getSharedPreferences("remember", MODE_PRIVATE);
        boolean isRemember = prefer.getBoolean("remember", false);
        if (isRemember) {
            et_Name.setText(prefer.getString("name", ""));
            et_Pass.setText(prefer.getString("pass", ""));
            remember.setChecked(true);
        }
    }

到这里,登录功能就OK了,但是数据库中根本没有任何一条账号信息!于是,当然少不了注册功能--往数据库里写入账号信息!




创建一个注册账号的layout和activity,进行代码编写

主要功能实现:当用户输入你所需求的信息,并符合要求(如密码不能低于6位等),接下来就去匹配数据库了,首先判断账号是否已经存在于数据库:


<pre name="code" class="java">            boolean creatUser=false;//是否允许创建用户
            dbHelper = new RegisterHelper(Register_Activity.this, "user", null, 1);
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            Cursor cursor = db.query("user", new String[]{"user"}, null, null, null, null, null);
            while (cursor.moveToNext()) {
                if (user_name.equals(cursor.getString(cursor.getColumnIndex("user")))) {//如果在数据库中找到了该账号,则不允许创建
                    Toast.makeText(Register_Activity.this, "该账户已存在", Toast.LENGTH_SHORT).show();//弹一条吐司提醒用户
                    creatUser = false;//不允许创建
                }
            }
接下来判断creatUser到底允许不允许创建用户,从而实现向数据库写入账号信息的逻辑:


<pre name="code" class="java">if (creatUser) {//如果允许创建用户
<span style="white-space:pre">		</span>//将用户信息以键值对形式存贮在ContentValues中
                ContentValues values = new ContentValues();
                values.put("user", user_name);
                values.put("pass", pass1);
                values.put("name", name);
                values.put("reSetPass", gmkl);
                db.insert("user", null, values);//插入数据
<span style="white-space:pre">		</span>//注册成功后弹出一个Dialog提示用户
                AlertDialog.Builder dialog = new AlertDialog.Builder(Register_Activity.this);
                dialog.setTitle("注册成功");
                dialog.setMessage("您已成功注册账户,请返回登录界面");
<span style="white-space:pre">		</span>//设置确认按钮,跳转至登录界面
                dialog.setPositiveButton("返回登录界面", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
<span style="white-space:pre">		</span>//设置取消按钮,留在注册界面
                dialog.setNegativeButton("留在注册界面", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                dialog.show();
            }


到这里,登录和注册功能就实现了!



还有一个修改密码(找回密码)的功能:

由于手欠,将此功能写在了一个自定义的Dialog里,其实可以写在Dialog类型的Activity中的,这里我就不再修改了

首先验证用户是否完整输入了我们改密所需要的各项内容,如果都输入了,则在数据库中匹配账号,账号匹配成功则再匹配改密口令,如果改密口令匹配成功,则修改密码,代码如下:


<span style="white-space:pre">	</span>    db = new RegisterHelper(context, "user", null, RegisterHelper.REGISTER_DB_VERSION).getReadableDatabase();
            Cursor cursor = db.query("user", new String[]{"user", "reSetPass"}, null, null, null, null, null);
            //验证账号与改密口令是否相符
            while (cursor.moveToNext()) {
                if (userName.equals(cursor.getString(cursor.getColumnIndex("user")))&&
                        gmkl.equals(cursor.getString(cursor.getColumnIndex("reSetPass")))) {//如果账号相符,则匹配改密口令,与登录类似
                        ContentValues values = new ContentValues();
                        values.put("pass", newPass);
                        db.update("user", values, "user=?", new String[]{userName});//更新密码
                        Toast.makeText(context,"密码修改成功!\n请牢记新密码并使用新密码登录",Toast.LENGTH_LONG).show();//弹出吐司提醒用户
                        isReSetPassFinish=true;//改密工作完成
                        break;
                }
            }
            //未成功匹配账号&改密口令
            if (!isReSetPassFinish){
                Toast.makeText(context,"账号不存在或改密口令错误",Toast.LENGTH_LONG).show();
            }



下面我就将这两个Activity的代码以及修改密码的代码无情的全部贴上来吧:

LoginActivity:

package com.example.application.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.example.application.Dialog.ReSetPass_Dialog;
import com.example.application.R;
import com.example.application.db.RegisterHelper;

/**
 * 登录界面
 * Created by lxb on 2016/5/13.
 */
public class Login_Activity extends Activity implements View.OnClickListener {
    private Button bt_login;
    private Button bt_cancel;
    private Button bt_register;
    private Button bt_reSetPass;

    private EditText et_Name;
    private EditText et_Pass;


    private CheckBox remember;
    private ImageView showUserName;

    private SQLiteDatabase db;


    private PopupWindow popup;

    private ArrayAdapter<String> popupAdpter;
    private ListView popupLV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login_layout);
        bt_login = (Button) findViewById(R.id.bt_login);
        bt_cancel = (Button) findViewById(R.id.bt_cancel);
        bt_register = (Button) findViewById(R.id.bt_register);
        bt_reSetPass = (Button) findViewById(R.id.bt_reSetPass);

        et_Name = (EditText) findViewById(R.id.et_loginName);
        et_Pass = (EditText) findViewById(R.id.et_loginPass);

        remember = (CheckBox) findViewById(R.id.cb_rememberName);

        showUserName = (ImageView) findViewById(R.id.iv_showName);

        showUserName.setOnClickListener(this);
        bt_login.setOnClickListener(this);
        bt_cancel.setOnClickListener(this);
        bt_register.setOnClickListener(this);
        bt_reSetPass.setOnClickListener(this);
        isRemember();
    }

    /**
     * Button监听器
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login: {
                Login();
            }
            break;
            case R.id.bt_register: {
                Intent intent = new Intent(Login_Activity.this, Register_Activity.class);
                startActivity(intent);
            }
            break;
            case R.id.iv_showName: {
                InitPopup();
            }
            break;
            case R.id.bt_reSetPass: {
                ReSetPass_Dialog dialog=new ReSetPass_Dialog(this);
                dialog.show();
            }
            break;
            case R.id.bt_cancel: {
                System.exit(0);
            }
        }
    }

    /**
     * 登录账号验证
     * 判断是否勾选记住密码
     */

    private void Login() {

        String name = et_Name.getText().toString();
        String pass = et_Pass.getText().toString();
        //判断是否输入内容
        if (name.equals("") || pass.equals("")) {
            Toast.makeText(this, "请输入账号或密码", Toast.LENGTH_SHORT).show();
        } else {//输入了账号&密码
            db = new RegisterHelper(this, "user", null, RegisterHelper.REGISTER_DB_VERSION).getReadableDatabase();
            Cursor cursor = db.query("user", new String[]{"user", "pass"}, null, null, null, null, null);
            boolean login = false;//账号密码是否匹配
            //从数据库中匹配账号密码
            while (cursor.moveToNext()) {
                if (name.equals(cursor.getString(cursor.getColumnIndex("user")))
                        && pass.equals(cursor.getString(cursor.getColumnIndex("pass")))) {
                    login = true;
                    break;
                }
            }
            //如果匹配成功,判断是否勾选记住账号,并进行账号信息存储
            if (login) {
                SharedPreferences.Editor editor = getSharedPreferences("remember", MODE_PRIVATE).edit();
                if (remember.isChecked()) {
                    editor.putBoolean("remember", true);
                    editor.putString("name", name);
                    editor.putString("pass", pass);
                    editor.commit();
                } else {
                    editor.clear();
                }
                editor.commit();
                Intent intent = new Intent(this, Main_Activity.class);
                startActivity(intent);
            } else {
                //账号密码在数据库中匹配不成功
                Toast.makeText(this, "账号与密码不匹配", Toast.LENGTH_SHORT).show();
            }
        }

    }


    private void InitPopup() {

    }

    /**
     * 判断是否是否保存过密码
     */
    public void isRemember() {
        SharedPreferences prefer = getSharedPreferences("remember", MODE_PRIVATE);
        boolean isRemember = prefer.getBoolean("remember", false);
        if (isRemember) {
            et_Name.setText(prefer.getString("name", ""));
            et_Pass.setText(prefer.getString("pass", ""));
            remember.setChecked(true);
        }
    }
}


RegisterActivity:

package com.example.application.activity;

import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.application.R;
import com.example.application.db.RegisterHelper;

/**
 * Created by lxb on 2016/5/14.
 */
public class Register_Activity extends Activity implements View.OnClickListener {
    private Button register_go;
    private Button register_cancel;
    private EditText register_user_name;
    private EditText register_user_pass1;
    private EditText register_user_pass2;
    private EditText register_name;
    private EditText register_gmkl;
    private RegisterHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_layout);
        register_user_name = (EditText) findViewById(R.id.register_user_name);
        register_user_pass1 = (EditText) findViewById(R.id.register_pass1);
        register_user_pass2 = (EditText) findViewById(R.id.register_pass2);
        register_name = (EditText) findViewById(R.id.register_name);
        register_gmkl = (EditText) findViewById(R.id.register_gmkl);
        register_go = (Button) findViewById(R.id.register_go);
        register_cancel = (Button) findViewById(R.id.register_cancel);
        register_go.setOnClickListener(this);
        register_cancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register_go: {
                RegisterSave();
            }
            break;
            case R.id.register_cancel: {
                finish();
            }
        }
    }

    private void RegisterSave() {
        String user_name = register_user_name.getText().toString();
        String pass1 = register_user_pass1.getText().toString();
        String pass2 = register_user_pass2.getText().toString();
        String name = register_name.getText().toString();
        String gmkl = register_gmkl.getText().toString();
        boolean creatUser = true;
        if (user_name.equals("") || pass1.equals("") || pass2.equals("") || name.equals("") || gmkl.equals("")) {
            Toast.makeText(this, "请完整输入各项注册内容", Toast.LENGTH_SHORT).show();
        } else if (!pass1.equals(pass2)) {
            Toast.makeText(this, "两次输入密码不一致,请重新输入", Toast.LENGTH_SHORT).show();
        } else if (pass1.length() < 6) {
            Toast.makeText(this, "密码小于六位数,请重新输入", Toast.LENGTH_SHORT).show();
        } else {
            dbHelper = new RegisterHelper(Register_Activity.this, "user", null, 1);
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            Cursor cursor = db.query("user", new String[]{"user"}, null, null, null, null, null);
            while (cursor.moveToNext()) {
                if (user_name.equals(cursor.getString(cursor.getColumnIndex("user")))) {
                    Toast.makeText(Register_Activity.this, "该账户已存在", Toast.LENGTH_SHORT).show();
                    creatUser = false;
                }
            }
            if (creatUser) {
                ContentValues values = new ContentValues();
                values.put("user", user_name);
                values.put("pass", pass1);
                values.put("name", name);
                values.put("reSetPass", gmkl);
                db.insert("user", null, values);
                AlertDialog.Builder dialog = new AlertDialog.Builder(Register_Activity.this);
                dialog.setTitle("注册成功");
                dialog.setMessage("您已成功注册账户,请返回登录界面");
                dialog.setPositiveButton("返回登录界面", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                dialog.setNegativeButton("留在注册界面", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                dialog.show();
            }

        }

    }
}

ReSetPass_Dialog:

package com.example.application.Dialog;

import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.application.R;
import com.example.application.db.RegisterHelper;

/**
 * 修改密码的Dialog
 * Created by lxb on 2016/5/15.
 */
public class ReSetPass_Dialog extends Dialog implements View.OnClickListener{
    private Context context;
    private EditText et_reSetUserName;
    private EditText et_reSetGmkl;
    private EditText et_reSetNewPass;

    private Button bt_reSetGo;
    private Button bt_reSetCancel;

    private SQLiteDatabase db;

    public ReSetPass_Dialog(Context context) {
        super(context);
        this.context=context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.resetpass_dialog);
        et_reSetGmkl = (EditText) findViewById(R.id.et_reSetGmkl);
        et_reSetUserName = (EditText) findViewById(R.id.et_reSetUserName);
        et_reSetNewPass = (EditText) findViewById(R.id.et_reSetNewPass);
        bt_reSetGo= (Button) findViewById(R.id.bt_reSetGo);
        bt_reSetCancel= (Button) findViewById(R.id.bt_reSetCancel);
        bt_reSetGo.setOnClickListener(this);
        bt_reSetCancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_reSetGo:{
                if (isReSetPass()){
                    dismiss();
                }
            }
            break;
            case R.id.bt_reSetCancel:{
                cancel();
            }
            break;
        }
    }

    /**
     *
     * 账号与改密口令验证
     * 修改密码
     *
     * @return 是否完成完成改密工作
     */

    private boolean isReSetPass() {
        boolean isReSetPassFinish=false;
        String userName = et_reSetUserName.getText().toString();
        String gmkl = et_reSetGmkl.getText().toString();
        String newPass = et_reSetNewPass.getText().toString();
        //是否完整输入各项内容
        if (userName.equals("") || gmkl.equals("") || newPass.equals("")) {
            Toast.makeText(context, "请输入改密所需的每项内容", Toast.LENGTH_SHORT).show();
        } else {//完整输入了各项所需内容
            db = new RegisterHelper(context, "user", null, RegisterHelper.REGISTER_DB_VERSION).getReadableDatabase();
            Cursor cursor = db.query("user", new String[]{"user", "reSetPass"}, null, null, null, null, null);
            //验证账号与改密口令是否相符
            while (cursor.moveToNext()) {
                if (userName.equals(cursor.getString(cursor.getColumnIndex("user")))&&
                        gmkl.equals(cursor.getString(cursor.getColumnIndex("reSetPass")))) {
                        ContentValues values = new ContentValues();
                        values.put("pass", newPass);
                        db.update("user", values, "user=?", new String[]{userName});
                        Toast.makeText(context,"密码修改成功!\n请牢记新密码并使用新密码登录",Toast.LENGTH_LONG).show();
                        isReSetPassFinish=true;
                        break;
                }
            }
            //未成功匹配账号&改密口令
            if (!isReSetPassFinish){
                Toast.makeText(context,"账号不存在或改密口令错误",Toast.LENGTH_LONG).show();
            }
        }
        return isReSetPassFinish;
    }
}


应该很清楚了

阅读更多

没有更多推荐了,返回首页