登录、注册

添加依赖
    //    gson
    implementation 'com.google.code.gson:gson:2.2.4'

    //okhttp
    implementation 'com.squareup.okhttp3:okhttp:3.12.0'

    //retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'//转换器,请求结果转换成Model
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'//配合Rxjava 使用

    //Rxjava
    implementation 'io.reactivex.rxjava2:rxjava:2.2.4'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'

    //EventBus
    implementation 'org.greenrobot:eventbus:3.1.1'
登录、注册_第1张图片
个人中心.jpg



    

        

        

    

    

        

    

    
package com.example.login;

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

import com.example.login.bean.User;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private RelativeLayout item;
    private Button logout;
    private TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        initView();
        initData();
    }

    private void initView() {
        item = (RelativeLayout) findViewById(R.id.item);
        logout = (Button) findViewById(R.id.logout);
        text = (TextView) findViewById(R.id.text);

        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });

        logout.setOnClickListener(this);

    }

    private void initData() {
        SharedPreferences sp = getSharedPreferences("login", MODE_PRIVATE);
        boolean b = sp.getBoolean("remember", false);
        String username = sp.getString("name", "");
        String psw = sp.getString("password", "");

        if (username.equals("")) {
            text.setText("未登录");

            // 让注销按钮处于隐藏状态
            logout.setVisibility(View.GONE);
        }else {
            text.setText(username);

            // 让注销按钮处于显示状态
            logout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.logout:
                logout();
                break;
        }
    }
    // 点击注销按钮让用户名和密码清空
    private void logout() {
        SharedPreferences sp = getSharedPreferences("login", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putBoolean("remember", false);
        edit.putString("name", "");
        edit.putString("password", "");
        edit.commit();
        initData();
    }

    // 登录页面返回的数据
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getData(User user){
        if (user!=null){
            String name1 = user.getName();
            String psw1 = user.getPassword();

            // 显示用户名
            text.setText(name1);
            // 让注销按钮处于显示状态
            logout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
登录、注册_第2张图片
登录.jpg



    

    

    

    

        
package com.example.login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.example.login.bean.LoginBean;
import com.example.login.bean.User;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "LoginActivity";

    private EditText name;
    private EditText password;
    private CheckBox remember;
    private Button login;
    private Button register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        name = (EditText) findViewById(R.id.name);
        password = (EditText) findViewById(R.id.password);
        remember = (CheckBox) findViewById(R.id.remember);
        login = (Button) findViewById(R.id.login);
        register = (Button) findViewById(R.id.register);

        SharedPreferences sp = getSharedPreferences("login", MODE_PRIVATE);
        boolean b = sp.getBoolean("remember", false);
        String username = sp.getString("name", "");
        String psw = sp.getString("password", "");
        remember.setChecked(b);
        if (b){
            name.setText(username);
            password.setText(psw);
        }

        login.setOnClickListener(this);
        register.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                submit();
                break;
            case R.id.register:
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void submit() {
        // validate
        String nameString = name.getText().toString().trim();
        if (TextUtils.isEmpty(nameString)) {
            Toast.makeText(this, "用户名", Toast.LENGTH_SHORT).show();
            return;
        }

        String passwordString = password.getText().toString().trim();
        if (TextUtils.isEmpty(passwordString)) {
            Toast.makeText(this, "密码", Toast.LENGTH_SHORT).show();
            return;
        }

        // TODO validate success, do something

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HttpService.loginUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        HttpService httpService = retrofit.create(HttpService.class);

        FormBody formBody = new FormBody.Builder()
                .add("username", nameString)
                .add("password", passwordString)
                .build();

        httpService.login(formBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        int code = loginBean.getCode();
                        if (code == 200) {
                            LoginBean.DataBean dataBean = loginBean.getData().get(0);

                            SharedPreferences sp = getSharedPreferences("login", MODE_PRIVATE);
                            SharedPreferences.Editor edit = sp.edit();
                            boolean checked = remember.isChecked();
                            edit.putBoolean("remember", checked);
                            edit.putString("name", dataBean.getName());
                            edit.putString("password", dataBean.getPassword());
                            edit.commit();

                            EventBus.getDefault().post(new User(dataBean.getName(),dataBean.getPassword()));
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    // 注册页面返回的数据
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getData(HashMap map){
        if (map!=null){
            String nameString = map.get("name");
            String pswString = map.get("password");

            name.setText(nameString);
            password.setText(pswString);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }
}
登录、注册_第3张图片
注册.jpg



    

    

        

        
package com.example.login;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.login.bean.CodeBean;
import com.example.login.bean.RegisterBean;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText phone;
    private EditText code;
    private Button getcode;
    private EditText name;
    private EditText password;
    private EditText confirm_password;
    private Button register;

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

    private void initView() {
        phone = (EditText) findViewById(R.id.phone);
        code = (EditText) findViewById(R.id.code);
        getcode = (Button) findViewById(R.id.getcode);
        name = (EditText) findViewById(R.id.name);
        password = (EditText) findViewById(R.id.password);
        confirm_password = (EditText) findViewById(R.id.confirm_password);
        register = (Button) findViewById(R.id.register);

        getcode.setOnClickListener(this);
        register.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.getcode:
                getCode();
                break;
            case R.id.register:
                submit();
                break;
        }
    }
    // 获取验证码
    private void getCode() {
        String phoneString = phone.getText().toString().trim();
        if (TextUtils.isEmpty(phoneString)) {
            Toast.makeText(this, "手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HttpService.codeUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        HttpService httpService = retrofit.create(HttpService.class);

        httpService.getCode()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CodeBean codeBean) {
                        String data = codeBean.getData();
                        Toast.makeText(RegisterActivity.this, data, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void submit() {
        // validate
        String phoneString = phone.getText().toString().trim();
        if (TextUtils.isEmpty(phoneString)) {
            Toast.makeText(this, "手机号", Toast.LENGTH_SHORT).show();
            return;
        }

        String codeString = code.getText().toString().trim();
        if (TextUtils.isEmpty(codeString)) {
            Toast.makeText(this, "验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        final String nameString = name.getText().toString().trim();
        if (TextUtils.isEmpty(nameString)) {
            Toast.makeText(this, "用户名", Toast.LENGTH_SHORT).show();
            return;
        }

        final String passwordString = password.getText().toString().trim();
        if (TextUtils.isEmpty(passwordString)) {
            Toast.makeText(this, "密码", Toast.LENGTH_SHORT).show();
            return;
        }

        String password = confirm_password.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "确认密码", Toast.LENGTH_SHORT).show();
            return;
        }

        // TODO validate success, do something
        if (!passwordString.equals(password)){
            Toast.makeText(this, "密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HttpService.registerUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        HttpService httpService = retrofit.create(HttpService.class);

        FormBody formBody = new FormBody.Builder()
                .add("username", nameString)
                .add("password", passwordString)
                .add("phone", phoneString)
                .add("verify", codeString)
                .build();

        httpService.register(formBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(RegisterBean registerBean) {
                        int code = registerBean.getCode();
                        String ret = registerBean.getRet();
                        Toast.makeText(RegisterActivity.this, ret, Toast.LENGTH_SHORT).show();

                        if (code==200){
                            HashMap map1 = new HashMap<>();
                            map1.put("name",nameString);
                            map1.put("password",passwordString);

                            EventBus.getDefault().post(map1);
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }
}

HttpService接口

package com.example.login;

import com.example.login.bean.CodeBean;
import com.example.login.bean.LoginBean;
import com.example.login.bean.RegisterBean;

import io.reactivex.Observable;
import okhttp3.RequestBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;

public interface HttpService {
    String loginUrl="http://yun918.cn/study/public/";
    @POST("login")
    Observable login(@Body RequestBody requestBody);

    String codeUrl="http://yun918.cn/study/public/";
    @GET("verify")
    Observable getCode();

    String registerUrl="http://yun918.cn/study/public/";
    @POST("register")
    Observable register(@Body RequestBody requestBody);
}

三个实体类

package com.example.login.bean;

public class CodeBean {

    /**
     * code : 200
     * ret : success
     * data : icpz
     */

    private int code;
    private String ret;
    private String data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getRet() {
        return ret;
    }

    public void setRet(String ret) {
        this.ret = ret;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

package com.example.login.bean;

import java.util.List;

public class LoginBean {

    /**
     * code : 200
     * ret : 登录成功
     * data : [{"id":65,"uid":"62","name":"qwe","password":"123","age":18,"sex":1,"phone":"13555555555","header":null}]
     */

    private int code;
    private String ret;
    private List data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getRet() {
        return ret;
    }

    public void setRet(String ret) {
        this.ret = ret;
    }

    public List getData() {
        return data;
    }

    public void setData(List data) {
        this.data = data;
    }

    public static class DataBean {
        /**
         * id : 65
         * uid : 62
         * name : qwe
         * password : 123
         * age : 18
         * sex : 1
         * phone : 13555555555
         * header : null
         */

        private int id;
        private String uid;
        private String name;
        private String password;
        private int age;
        private int sex;
        private String phone;
        private Object header;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getUid() {
            return uid;
        }

        public void setUid(String uid) {
            this.uid = uid;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public int getSex() {
            return sex;
        }

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

        public String getPhone() {
            return phone;
        }

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

        public Object getHeader() {
            return header;
        }

        public void setHeader(Object header) {
            this.header = header;
        }
    }
}

package com.example.login.bean;

public class RegisterBean {

    /**
     * code : 200
     * ret : 注册成功
     * data :
     */

    private int code;
    private String ret;
    private String data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getRet() {
        return ret;
    }

    public void setRet(String ret) {
        this.ret = ret;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

EventBus传数据用到的实体类

package com.example.login.bean;

public class User {
    String name;
    String password;

    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

你可能感兴趣的:(登录、注册)