登陆注册(使用GreenDao)

在我们开发电商项目的过程中,我们肯定会涉及到用户的登录,注册业务,那么我们也需要一个数据库进行存储用户的个人信息.今天我们就来搞一下,本次使用的是GreenDao;
GreenDao我在简书上看到了一篇不错的文章,过程也是非常详细,在这里分享给大家:https://www.jianshu.com/p/ec37ea99ef69
接下来就开始我们的工作.
第一步:搭建环境:
导入我们需要的一些依赖,和网络权限

/*android5.0的新特性使用*/
    implementation 'com.android.support:support-v13:28.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:support-v13:28.0.0'
    /*OkHttp*/
    implementation 'com.squareup.okhttp3:okhttp:3.4.2'
    /*RecyclerView*/
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    /*XRecyclerView*/
    implementation 'com.jcodecraeer:xrecyclerview:1.5.9'
    /*Fresco的基础依赖*/
    implementation 'com.facebook.fresco:fresco:0.14.1'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    /*GreenDao*/
    implementation 'org.greenrobot:greendao:3.2.2'
    /*BottomTabBar*/
    implementation 'com.hjm:BottomTabBar:1.1.1'

    implementation 'com.gxz.pagerslidingtabstrip:library:1.3'
    implementation 'com.bigkoo:convenientbanner:2.0.5'
    /*三级联动*/
    implementation 'liji.library.dev:citypickerview:1.1.0'

网络权限:

 <uses-permission android:name="android.permission.INTERNET" />

第二步:导入GreenDao:
GreenDao使用中涉及到的注解:
(一) @Entity 定义实体
@nameInDb 在数据库中的名字,如不写则为实体中类名
@indexes 索引
@createInDb 是否创建表,默认为true,false时不创建
@schema 指定架构名称为实体
@active 无论是更新生成都刷新
(二) @Id
(三) @NotNull 不为null
(四) @Unique 唯一约束
(五) @ToMany 一对多
(六) @OrderBy 排序
(七) @ToOne 一对一
(八) @Transient 不存储在数据库中
(九) @generated 由greenDAO产生的构造函数或方法
在上面我给大家分享了一个链接,里面有比较详细的:下面我就简单分享一下,在这个项目用到的一些相关代码:
登陆注册(使用GreenDao)_第1张图片
1.导入配置依赖

apply plugin: 'org.greenrobot.greendao'

android {
..........
    greendao {
        schemaVersion 1
        daoPackage 'com.greendao.gen'
        targetGenDir 'src/main/java'
    }
}

2.定义MyApplication类:

public class MyAppliction extends Application {

    public static MyAppliction instances;
    private DaoMaster.DevOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    @Override
    public void onCreate() {
        super.onCreate();
        //Fresco
        Fresco.initialize(this);

        instances = this;
        setDatabase();
    }

    public static MyAppliction getInstances() {
        return instances;
    }

    /**
     *设置greenDAO
     */
    private void setDatabase() {// 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。
        // 可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为 greenDAO已经帮你做了。
        // 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。
        // 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。
        mHelper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
        db = mHelper.getWritableDatabase();
        // 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }
    public DaoSession getDaoSession() {
        return mDaoSession;
    }
    public SQLiteDatabase getDb() {
        return db;
    }
}

3.清单文件注册:


4.创建User实体类:

@Entity
public class UserDao {
    @Property(nameInDb = "USERID")
    private String userId;
    @Property(nameInDb = "SESSIONID")
    private String sessionId;
    @Property(nameInDb = "NIKENAME")
    private String nickName;
    @Property(nameInDb = "PHONE")
    private String phone;
    @Property(nameInDb = "HEADPIC")
    private String headPic;
    @Property(nameInDb = "SEX")
    private int sex;
    @Generated(hash = 626129925)
    public UserDao(String userId, String sessionId, String nickName, String phone,
            String headPic, int sex) {
        this.userId = userId;
        this.sessionId = sessionId;
        this.nickName = nickName;
        this.phone = phone;
        this.headPic = headPic;
        this.sex = sex;
    }
    @Generated(hash = 917059161)
    public UserDao() {
    }
    public String getUserId() {
        return this.userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getSessionId() {
        return this.sessionId;
    }
    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }
    public String getNickName() {
        return this.nickName;
    }
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
    public String getPhone() {
        return this.phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getHeadPic() {
        return this.headPic;
    }
    public void setHeadPic(String headPic) {
        this.headPic = headPic;
    }
    public int getSex() {
        return this.sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
   

}

5.编译项目(Android快捷键:Ctrl+F9),User实体类会自动编译,生成get、set方法并且会在com.greendao.gen目录下生成三个文件,并且还会在我们的包下生成DaoMaster和DaoSession。
登陆注册(使用GreenDao)_第2张图片

第三步:这里把我们用到的接口,可以单独提取出来:


    //登录
    public static final String loginPath = "http://172.17.8.100/small/user/v1/login";
    //注册
    public static final String registerPath = "http://172.17.8.100/small/user/v1/register";

第四步:具体的登录注册业务逻辑处理:
1.登录:

package com.job.heavenandearth.activity;


/**
 * --------------------登录页面------------------------------
 * 1.首先获取输入框的账号和密码
 * 2.判断输入是否为空
 * 2.1 : 如果为空,则提示用户输入不能为空
 * 2.2: 如果输入不为空则进行判断
 * 3.判断账号密码是否存在
 * 3.1 : 存在则登陆成功
 * 3.2 : 如果账号输入错误,提示用户账号并不存在,先进行注册,再登录
 * 3.2 : 如果账号输入正确,密码输入错误,则提示用户密码输入错误,请重新输入
 */
public class LoginActivity extends BaseActivity {

    private EditText login_edit_phone;
    private CheckBox login_cb_remember_pwd;
    private EditText login_edit_pwd;
    private TextView login_tv_register;
    private Button login_button_login,login_button_not_login;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor mEdit;
    private ImageView img_eye;
    private boolean isHideFirst;

    @Override
    protected int setView() {
        return R.layout.activity_login;

    }

    //初始化控件
    @Override
    protected void initViews() {
        login_edit_phone = findViewById(R.id.login_edit_phone);
        login_edit_pwd = findViewById(R.id.login_edit_pwd);
        login_cb_remember_pwd = findViewById(R.id.login_cb_remember_pwd);
        login_tv_register = findViewById(R.id.login_tv_register);
        login_button_login = findViewById(R.id.login_button_login);
        login_button_not_login = findViewById(R.id.login_button_not_login);
        img_eye = findViewById(R.id.img_eye);
        sharedPreferences = getSharedPreferences("lz", MODE_PRIVATE);
        mEdit = sharedPreferences.edit();

        //设置密码回显
        boolean ismain_check_remember = sharedPreferences.getBoolean("isjzmm", false);
        String username = sharedPreferences.getString("phone", "");
        String password = sharedPreferences.getString("pwd", "");
        if (ismain_check_remember) {
            login_cb_remember_pwd.setChecked(true);
            login_edit_phone.setText(username);
            login_edit_pwd.setText(password);
        }

    }

    @Override
    protected void initData() {

        ////////////////////////显示和隐藏密码////////////////////////////////
        img_eye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isHideFirst == true) {
                    //密文

                    HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
                    login_edit_pwd.setTransformationMethod(method1);
                    isHideFirst = false;
                    img_eye.setImageResource(R.mipmap.biyan);
                } else {
                    //密文
                    TransformationMethod method = PasswordTransformationMethod.getInstance();
                    login_edit_pwd.setTransformationMethod(method);
                    isHideFirst = true;
                    img_eye.setImageResource(R.mipmap.login_icon_eye_n);
                }
                // 光标的位置
                int index = login_edit_pwd.getText().toString().length();
                login_edit_pwd.setSelection(index);

            }

        });
        /////////////////////////////////////暂不登陆//////////////////////////////
        login_button_not_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,HomePagerActivity.class));
            }
        });
        ///////////////////////////////////////注册/////////////////////////////////
        //如果用户为新用户,需要注册后再进行登录登录
        login_tv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            }
        });

        /////////////////////////////////////////登录//////////////////////////////////////
        //点击登录,跳转到首页
        login_button_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



                //获取输入的账号和密码
                String phone = login_edit_phone.getText().toString().trim();
                String pwd = login_edit_pwd.getText().toString().trim();


                //判断是否记住密码
                if (login_cb_remember_pwd.isChecked()) {
                    mEdit.putString("phone", phone);
                    mEdit.putString("pwd", pwd);
                    mEdit.putBoolean("isjzmm", true);
                    mEdit.commit();
                } else {
                    mEdit.putString("phone", "");
                    mEdit.putString("pwd", "");
                    mEdit.putBoolean("isjzmm", false);
                    mEdit.commit();
                }

                //判断输入的是否为空
                boolean lzNull = M_Login.isNull(phone, pwd);
                if (lzNull) {
                    Toast.makeText(LoginActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    M_Login.getinstance().getHttp(phone, pwd, new P_Login() {
                        @Override
                        public void success(LoginBean loginBean) {
                            if (loginBean.getStatus().equals("0000")) {

                                UserDaoDao userDaoDao = MyAppliction.getInstances().getDaoSession().getUserDaoDao();
                                List<UserDao> userDaos = userDaoDao.loadAll();
                                if (userDaos.size() != 0) {
                                    userDaoDao.deleteAll();
                                } else {

                                }

                                UserDao userDao = new UserDao(loginBean.getResult().getUserIdWithString(), loginBean.getResult().getSessionId(),
                                        loginBean.getResult().getNickName(), loginBean.getResult().getPhone(),
                                        loginBean.getResult().getHeadPic(), loginBean.getResult().getSex());

                                long id = userDaoDao.insertOrReplace(userDao);

                                Log.i("TEST", "insert user: " + id);

                                 Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                                //更新购物车
                                ShoppingCart.getInstance().load();
                                Intent intent = new Intent(LoginActivity.this, HomePagerActivity.class);
                                intent.putExtra("userid",userDao.getUserId()+"");
                                intent.putExtra("sessid",userDao.getSessionId());
                                startActivity(intent);
                            } else {
                                Toast.makeText(LoginActivity.this, loginBean.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void defeated(Exception e) {
                            Toast.makeText(LoginActivity.this, "请进行注册!!", Toast.LENGTH_SHORT).show();
                        }

                    });
                }
            }
        });
    }
}

2.M层封装网络请求:

package com.job.heavenandearth.model;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.job.heavenandearth.bean.LoginBean;
import com.job.heavenandearth.net.Api;
import com.job.heavenandearth.persenter.P_Load;
import com.job.heavenandearth.persenter.P_Login;
import com.job.heavenandearth.util.OkHttpUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * date:2018/12/5
 * author:李壮(大壮)
 * function:-------------------OkHttp二次封装-----------------
 *          登录使用
 */
public class M_Login {

    private static M_Login mM_login;
    private M_Login(){};
    public static M_Login getinstance(){
        if (mM_login == null){
            synchronized (M_Login.class){
                if (mM_login == null){
                    mM_login = new M_Login();
                }
            }
        }
        return mM_login;
    }
    public void getHttp(String phone, String pwd, final P_Login p_login){
        Map map = new HashMap<>();
        map.put("phone",phone);
        map.put("pwd",pwd);
        OkHttpUtils.getInstance().doPost(Api.loginPath,map, new P_Load() {
            @Override
            public void success(String json) {
                LoginBean loginBean = new Gson().fromJson(json, LoginBean.class);
                if (p_login != null){
                    p_login.success(loginBean);
                }
            }

            @Override
            public void defeated(Exception e) {
                if (p_login != null){
                    p_login.defeated(e);
                }
            }

        });
    }
    //判断输入是否为空
    public static boolean isNull(String phone,String pwd){
        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(pwd)){
            return true;
        }
        return false;
    }
}

3.P层:负责V层与M层的交互

package com.job.heavenandearth.persenter;

import com.job.heavenandearth.bean.LoginBean;

/**
 * date:2018/12/5
 * author:李壮(大壮)
 * function:----------------登录的接口回调----------------
 */
public interface P_Login {
    void success(LoginBean loginBean);
    void defeated(Exception e);
}

4.OkHttp二次封装:

package com.job.heavenandearth.util;
/**
 * date:2018/12/4
 * author:李壮(大壮)
 * function:------------------OkHttp的二次封装--------------
 *  主要功能:用于网络请求
 */
public class OkHttpUtils {

    private static OkHttpUtils mOkHttpUtils;

    private Handler mHandler;
    private OkHttpClient mOkHttpClient;
    private UserDaoDao mUserDaoDao;
    private List<UserDao> mUserDaos;
    private String mSessionId;
    private String mUserId;
    private String mHeadPic;
    private String mNickName;
    private int mSex;
    private String mPhone;

    //创建一个私有的构造参数
    public OkHttpUtils(){
        //创建一个主线程handler
        mHandler = new Handler(Looper.getMainLooper());
        mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(10,TimeUnit.SECONDS)
                .connectTimeout(10,TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .build();
    }

    //单例模式
    public static OkHttpUtils getInstance(){
        if (mOkHttpUtils == null){
            synchronized (OkHttpUtils.class){
                if (mOkHttpUtils == null){
                    mOkHttpUtils = new OkHttpUtils();
                }
            }
        }
        return mOkHttpUtils;
    }

    //接口回调
    public interface onOkCallback{
        //成功
        void success(String json);
        //失败
        void failtrue(Exception e);

    }

    //封装doPost
    public void doPost(String url, Map<String,String> map, final P_Load okCallback){
        FormBody.Builder builder = new FormBody.Builder();
        if (map != null){
            for (String key : map.keySet()){
                builder.add(key,map.get(key));
            }
        }

        FormBody formBody = builder.build();

        //创建Request
        final Request request = new Request.Builder()
                .post(formBody)
                .url(url)
                .build();

        //创建call
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (okCallback != null){
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            okCallback.defeated(e);
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (response != null && response.isSuccessful()){
                        final String json = response.body().string();
                        if (okCallback != null){
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    okCallback.success(json);
                                }
                            });
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });
    }
    //封装doGet
    public void doGet(String url, final onOkCallback okCallback){
        mUserDaoDao = MyAppliction.getInstances().getDaoSession().getUserDaoDao();
        mUserDaos = mUserDaoDao.loadAll();
        for (int i = 0; i < mUserDaos.size(); i++) {
            mSessionId = mUserDaos.get(i).getSessionId();
            mUserId = mUserDaos.get(i).getUserId();
            mHeadPic = mUserDaos.get(i).getHeadPic();
            mNickName = mUserDaos.get(i).getNickName();
            mSex = mUserDaos.get(i).getSex();
            mPhone = mUserDaos.get(i).getPhone();
        }
        //创建Request
        final Request request = new Request.Builder()
                .addHeader( "userId" ,mUserId)
                .addHeader(  "sessionId",mSessionId)
                .url(url)
                .build();

        //创建call
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (okCallback != null){
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            okCallback.failtrue(e);
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (response != null && response.isSuccessful()){
                        final String json = response.body().string();
                        if (okCallback != null){
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    okCallback.success(json);
                                }
                            });
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });

    }
}

5.bean类:

package com.job.heavenandearth.bean;

/**
 * date:2018/12/5
 * author:李壮(大壮)
 * function: -------------------登录信息的Bean类-----------------
 */
public class LoginBean {

    /**
     * result : {"headPic":"http://172.17.8.100/images/small/default/user.jpg","nickName":"Qa_Y47v4","phone":"15235920684","sessionId":"154392823497892","sex":1,"userId":92}
     * message : 登录成功
     * status : 0000
     */

    private ResultBean result;
    private String message;
    private String status;

    public ResultBean getResult() {
        return result;
    }

    public void setResult(ResultBean result) {
        this.result = result;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public static class ResultBean {
        /**
         * headPic : http://172.17.8.100/images/small/default/user.jpg
         * nickName : Qa_Y47v4
         * phone : 15235920684
         * sessionId : 154392823497892
         * sex : 1
         * userId : 92
         */

        private String headPic;
        private String nickName;
        private String phone;
        private String sessionId;
        private int sex;
        private int userId;

        public String getHeadPic() {
            return headPic;
        }

        public void setHeadPic(String headPic) {
            this.headPic = headPic;
        }

        public String getNickName() {
            return nickName;
        }

        public void setNickName(String nickName) {
            this.nickName = nickName;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getSessionId() {
            return sessionId;
        }

        public void setSessionId(String sessionId) {
            this.sessionId = sessionId;
        }

        public int getSex() {
            return sex;
        }

        public void setSex(int sex) {
            this.sex = sex;
        }

        public int getUserId() {
            return userId;
        }

        public String getUserIdWithString() {
            return String.valueOf(userId);
        }

        public void setUserId(int userId) {
            this.userId = userId;
        }
    }
}


以上就是电商项目中的登录注册,希望能够给大家带来帮助

你可能感兴趣的:(Android)