本篇实现效果:

使用Okhttp3进行联网请求,通过post方法把用户名和密码发送到服务进行校验,如果账户已存在则提示,注册成功后,使用Gson解析返回的json数据提示用户,如下:

(额,这里要说一下:提示逻辑处理有点问题,这里代码已经修改好了,但是gif中还没有,由于时间不是很多就不再录制一遍了,见谅~)

aia android简单小项目实例 android开发项目app实例_android



逻辑功能实现:

RegisterActivity.class:

package com.example.myapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapp.R;
import com.example.myapp.bean.ResultBean;
import com.example.myapp.utils.APIConfig;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_name;
    private EditText et_nicke;
    private EditText et_phonr;
    private EditText et_password;
    private RadioButton rb_man;
    private RadioButton rb_woman;
    private RadioGroup rg_sex;
    private Button btn_register;
    private Button btn_login;

    private OkHttpClient client = new OkHttpClient();
    private Intent intent = null;

    String sex = "";
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==0) {
                String resultStr = (String) msg.obj;
                Log.i("获取返回的信息:",resultStr);
                final ResultBean resultBean = new Gson().fromJson(resultStr,ResultBean.class);
                int resultCode = resultBean.getCode();
                if (resultCode==200){
                    Toast.makeText(getApplicationContext(),"注册成功:"+resultStr,Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),"注册失败:"+resultStr,Toast.LENGTH_LONG).show();
                }

            }
        }
    };

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

    private void initView() {
        et_name = (EditText) findViewById(R.id.et_name);
        et_nicke = (EditText) findViewById(R.id.et_nicke);
        et_phonr = (EditText) findViewById(R.id.et_phone);
        et_password = (EditText) findViewById(R.id.et_password);
        rb_man = (RadioButton) findViewById(R.id.rb_man);
        rb_woman = (RadioButton) findViewById(R.id.rb_woman);
        rg_sex = (RadioGroup) findViewById(R.id.rg_sex);
        btn_register = (Button) findViewById(R.id.btn_register);
        btn_login = (Button) findViewById(R.id.btn_login);

        btn_register.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId==rb_man.getId()) {
                    sex="1";
                }else {
                    sex="0";
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register:
                Register();
                break;
            case R.id.btn_login:
                intent = new Intent(getApplicationContext(),LoginActivity.class);
                startActivity(intent);
                break;
        }
    }

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

        String nicke = et_nicke.getText().toString().trim();
        if (TextUtils.isEmpty(nicke)) {
            Toast.makeText(this, "请输入昵称", Toast.LENGTH_SHORT).show();
            return;
        }

        String phone = et_phonr.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入你的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }

        String password = et_password.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "password不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userName",name);
            jsonObject.put("nickName",nicke);
            jsonObject.put("phonenumber",phone);
            jsonObject.put("sex",sex);
            jsonObject.put("password",password);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        final RequestBody requestBody =RequestBody.create(mediaType,jsonObject.toString());
        Request request = new Request.Builder()
                .post(requestBody)
                .url(APIConfig.URL_BASE+"/user/register")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("onFailure", "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                Message msg = new Message();
                msg.what=0;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        });
    }



}

activity_rgister:

<?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:background="#ECECEC"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="用户注册"
        android:layout_marginTop="50dp"
        android:textSize="30sp"
        android:textStyle="bold"
        android:layout_marginBottom="50dp"
        android:textColor="#202020"/>

    <LinearLayout
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:background="@drawable/shape_login_form">
        <LinearLayout
            android:layout_marginTop="12dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="用 户 名:"
                android:layout_marginTop="10dp"
                android:textSize="18sp"
                android:textColor="#000000"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/et_name"
                android:textSize="16sp"
                android:background="@null"
                android:layout_margin="5dp"
                android:hint="请输入用户名"/>
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="10dp"
            android:background="#DADADA"/>
        <LinearLayout
            android:layout_marginTop="12dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="你的昵称: "
                android:layout_marginTop="10dp"
                android:textSize="18sp"
                android:textColor="#000000"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/et_nicke"
                android:textSize="16sp"
                android:background="@null"
                android:layout_margin="5dp"
                android:hint="请输入昵称"/>
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="10dp"
            android:background="#DADADA"/>
        <LinearLayout
            android:layout_marginTop="12dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="手机号码: "
                android:layout_marginTop="10dp"
                android:textSize="18sp"
                android:textColor="#000000"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/et_phone"
                android:textSize="16sp"
                android:background="@null"
                android:layout_margin="5dp"
                android:hint="请输入你的手机号码"/>
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="10dp"
            android:background="#DADADA"/>
        <LinearLayout
            android:layout_marginTop="12dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="  密     码:"
                android:layout_marginTop="10dp"
                android:textSize="18sp"
                android:textColor="#000000"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/et_password"
                android:textSize="16sp"
                android:background="@null"
                android:inputType="numberPassword"
                android:hint="请输入密码"
                android:layout_margin="5dp" />
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="10dp"
            android:background="#DADADA"/>
        <LinearLayout
            android:layout_marginTop="12dp"
            android:layout_width="match_parent"
            android:layout_marginBottom="10dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="你的性别: "
                android:layout_marginTop="10dp"
                android:textSize="18sp"
                android:textColor="#000000"/>
            <RadioGroup
                android:id="@+id/rg_sex"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:orientation="horizontal">
                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="男"
                    android:layout_marginRight="40dp"
                    android:id="@+id/rb_man"/>
                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="女"
                    android:id="@+id/rb_woman"/>
            </RadioGroup>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <Button
            android:layout_marginTop="30dp"
            android:id="@+id/btn_login"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_alignParentLeft="true"
            android:text="登录"
            android:textColor="#ffffff"

            android:background="@drawable/shape_login_btn"
            android:textSize="20sp" />
        <Button
            android:id="@+id/btn_register"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="20dp"

            android:background="@drawable/shape_register_btn"
            android:layout_alignParentRight="true"
            android:text="注册"
            android:textColor="#136BC8"
            android:textSize="20sp" />
    </LinearLayout>
</LinearLayout>

ResultBean

package com.example.myapp.bean;

import java.util.List;

public class ResultBean {

    /**
     * total : 0
     * rows : []
     * code : 200
     * msg : 查询成功
     */

    private int total;
    private int code;
    private String msg;
    private List<?> rows;

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<?> getRows() {
        return rows;
    }

    public void setRows(List<?> rows) {
        this.rows = rows;
    }
}

工具类 utils

新建APIConfig.class ,放请求服务器的根网址

package com.example.myapp.utils;

/**
 * @ProjectName: MyApp
 * @Package: com.example.myapp.utils
 * @ClassName: APIConfig
 * @Description:
 * @Author: liyingxia
 * @CreateDate: 2021/4/13 17:46
 */
public class APIConfig {
    public final static String URL_BASE = "http://192.168.196.45:8080";
}