美文网首页
登录、注册

登录、注册

作者: 沈溺_16e5 | 来源:发表于2019-03-25 19:40 被阅读0次
    添加依赖
        //    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'
    
    个人中心.jpg
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity"
        android:orientation="vertical">
    
        <RelativeLayout
            android:id="@+id/item"
            android:layout_width="match_parent"
            android:layout_height="70dp">
    
            <ImageView
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:background="@mipmap/ic_launcher_round"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"/>
    
            <TextView
                android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="未登录"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="20dp"/>
    
        </RelativeLayout>
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:background="#50979696">
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="个人中心"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:textSize="20sp"/>
    
        </RelativeLayout>
    
        <Button
            android:id="@+id/logout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="注销"/>
    
    </LinearLayout>
    
    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);
        }
    }
    
    登录.jpg
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".LoginActivity"
        android:orientation="vertical"
        android:gravity="center">
    
        <EditText
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="用户名"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp"
            android:layout_marginBottom="10dp"/>
    
        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="密码"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp"
            android:layout_marginBottom="10dp"
            android:password="true"/>
    
        <CheckBox
            android:id="@+id/remember"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="记住密码"
            android:layout_marginBottom="10dp"/>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">
    
            <Button
                android:id="@+id/login"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="登录"/>
    
            <Button
                android:id="@+id/register"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="注册"/>
    
        </LinearLayout>
    
    </LinearLayout>
    
    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<LoginBean>() {
                        @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<String,String> 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);
        }
    }
    
    注册.jpg
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        tools:context=".RegisterActivity">
    
        <EditText
            android:id="@+id/phone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp"
            android:hint="手机号" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp">
    
            <EditText
                android:id="@+id/code"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:hint="验证码" />
    
            <Button
                android:id="@+id/getcode"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="验证码" />
    
        </LinearLayout>
    
        <EditText
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp"
            android:hint="用户名" />
    
        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp"
            android:hint="密码"
            android:password="true"/>
    
        <EditText
            android:id="@+id/confirm_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp"
            android:hint="确认密码"
            android:password="true"/>
    
        <Button
            android:id="@+id/register"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="注册" />
    
    </LinearLayout>
    
    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<CodeBean>() {
                        @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<RegisterBean>() {
                        @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<String,String> 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<LoginBean> login(@Body RequestBody requestBody);
    
        String codeUrl="http://yun918.cn/study/public/";
        @GET("verify")
        Observable<CodeBean> getCode();
    
        String registerUrl="http://yun918.cn/study/public/";
        @POST("register")
        Observable<RegisterBean> 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<DataBean> 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<DataBean> getData() {
            return data;
        }
    
        public void setData(List<DataBean> 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 + '\'' +
                    '}';
        }
    }
    
    

    相关文章

      网友评论

          本文标题:登录、注册

          本文链接:https://www.haomeiwen.com/subject/luobvqtx.html