先来看看依赖 该导都导进去
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.google.code.gson:gson:2.8.1'
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
布局文件也都有直接copy就行
Activity——Login.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="20dp"
android:orientation="vertical"
>
<ImageView
android:id="@+id/touxiang"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginTop="80dp"
android:layout_centerHorizontal="true" />
<EditText
android:id="@+id/myname"
android:layout_marginTop="50dp"
android:layout_below="@+id/touxiang"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="请输入手机号"/>
<EditText
android:id="@+id/mypassword"
android:layout_below="@+id/myname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"/>
<TextView
android:id="@+id/shoujizhuce"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_below="@+id/mypassword"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:textSize="10sp"
/>
<TextView
android:id="@+id/zhuce"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/shoujizhuce"
android:layout_alignParentRight="true"
android:gravity="center_horizontal"
android:textSize="15sp"
android:text="新用户注册"/>
<TextView
android:id="@+id/login"
android:layout_below="@+id/shoujizhuce"
android:layout_marginTop="20dp"
android:layout_width="200dp"
android:layout_height="30dp"
android:text="登录"
android:gravity="center"
android:layout_centerHorizontal="true"/>
RelativeLayout>
activity_register.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
>
<ImageView
android:id="@+id/fanhui"
android:layout_marginTop="10dp"
android:layout_width="20dp"
android:layout_height="20dp"
/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="18sp"
android:text="新用户注册"/>
<EditText
android:id="@+id/zhucename"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="请输入手机号"/>
<EditText
android:id="@+id/zhucepassword"
android:layout_below="@+id/zhucename"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"/>
<Button
android:id="@+id/zhuce_but"
android:layout_marginTop="30dp"
android:layout_below="@+id/zhucepassword"
android:layout_centerHorizontal="true"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="注册"/>
RelativeLayout>
activity_main.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
android.support.constraint.ConstraintLayout>
bean包下的仔细看看
public class LoginBean {
/**
* msg : 登录成功
* code : 0
* data : {"age":null,"appkey":"b72980130446fc2b","appsecret":"5A67B75282783286784D221EF8002835","createtime":"2017-12-08T20:37:45","email":null,"fans":null,"follow":null,"gender":null,"icon":null,"latitude":null,"longitude":null,"mobile":"17610886861","money":null,"nickname":null,"password":"8F669074CAF5513351A2DE5CC22AC04C","praiseNum":null,"token":"D6E2D6FDD193E7C316CEBC950039A661","uid":3717,"userId":null,"username":"17610886861"}
*/
private String msg;
private String code;
private DataBean data;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* age : null
* appkey : b72980130446fc2b
* appsecret : 5A67B75282783286784D221EF8002835
* createtime : 2017-12-08T20:37:45
* email : null
* fans : null
* follow : null
* gender : null
* icon : null
* latitude : null
* longitude : null
* mobile : 17610886861
* money : null
* nickname : null
* password : 8F669074CAF5513351A2DE5CC22AC04C
* praiseNum : null
* token : D6E2D6FDD193E7C316CEBC950039A661
* uid : 3717
* userId : null
* username : 17610886861
*/
private String age;
private String appkey;
private String appsecret;
private String createtime;
private String email;
private String fans;
private String follow;
private String gender;
private String icon;
private String latitude;
private String longitude;
private String mobile;
private String money;
private String nickname;
private String password;
private String praiseNum;
private String token;
private int uid;
private String userId;
private String username;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAppkey() {
return appkey;
}
public void setAppkey(String appkey) {
this.appkey = appkey;
}
public String getAppsecret() {
return appsecret;
}
public void setAppsecret(String appsecret) {
this.appsecret = appsecret;
}
public String getCreatetime() {
return createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFans() {
return fans;
}
public void setFans(String fans) {
this.fans = fans;
}
public String getFollow() {
return follow;
}
public void setFollow(String follow) {
this.follow = follow;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPraiseNum() {
return praiseNum;
}
public void setPraiseNum(String praiseNum) {
this.praiseNum = praiseNum;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
}
public class RegisterBean {
/**
* msg : 天呢!用户已注册
* code : 1
* data : {}
*/
private String msg;
private String code;
private String data;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
自己封装的OkHttp
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import java.io.IOException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static android.content.ContentValues.TAG;
public class Okhttputils {
private static Okhttputils okHttpClient;
private Handler handler=new Handler();
private Okhttputils() {
}
public static Okhttputils getInstance() {
if (null==okHttpClient) {
synchronized (Okhttputils.class) {
if (okHttpClient == null) {
okHttpClient = new Okhttputils();
}
}
}
return okHttpClient;
}
public void get(String url, Map<String,String> map,final Class cls, final CallBack callBack){
if(TextUtils.isEmpty(url)){
return;
}
StringBuffer sb = new StringBuffer();
sb.append(url);
if(url.contains("?")){
if(url.indexOf("?")==url.length()-1){
}else{
sb.append("&");
}
}else{
sb.append("?");
}
if(map!=null){
for(Map.Entry<String,String> mmp : map.entrySet()){
sb.append(mmp.getKey())
.append("=")
.append(mmp.getValue())
.append("&");
}
if(sb.indexOf("&")!=-1){
sb.deleteCharAt(sb.lastIndexOf("&"));//删除最后一个&字符
}
}
OkHttpClient Client = new OkHttpClient();
Request request = new Request.Builder()
.get()
.url(sb.toString())//在此需注意传递的参数是追加好的可变字符串
.build();
Call call = Client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callBack.onFailes(e);
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String str = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
Object o= GsonUtiles.getInstance().fromJson(str,cls);
if(o==null){
Log.i(TAG, "run: 数据请求失败"); }
callBack.onSeccuss(o);
}
});
}
});
}
}
import com.google.gson.Gson;
public class GsonUtiles {
//Gson的单列模式
private static Gson instance;
private GsonUtiles() {}
public static Gson getInstance() {
if (instance == null) {
instance = new Gson();
}
return instance;
}
}
public interface CallBack {
void onSeccuss(Object o);
void onFailes(Exception o);
}
presenter包
public class LoginPresaenter {
private LoginView iv;
private String mobile;
private String password;
public void attchview(LoginView iv,String mobile,String password){
this.iv=iv;
this.mobile=mobile;
this.password=password;
}
public void getNews() {
//创建集合
HashMap<String, String> map = new HashMap<String, String>();
map.put("mobile",mobile);
map.put("password",password);
Okhttputils.getInstance().get(Api.LOGIN, map, LoginBean.class, new CallBack() {
@Override
public void onSeccuss(Object o) {
LoginBean javabean = (LoginBean) o;
if (javabean != null) {
iv.success(javabean);
}
}
@Override
public void onFailes(Exception e) {
iv.failed(e);
}
});
}
public class RegisterPresaenter {
private Registerivew iv;
private String mobile;
private String password;
public void attchview(Registerivew iv,String mobile,String password){
this.iv=iv;
this.mobile=mobile;
this.password=password;
}
public void getNews() {
//创建集合
HashMap<String, String> map = new HashMap<String, String>();
map.put("mobile",mobile);
map.put("password",password);
Okhttputils.getInstance().get(Api.REG, map, RegisterBean.class, new CallBack() {
@Override
public void onSeccuss(Object o) {
RegisterBean javabean = (RegisterBean) o;
if (javabean != null) {
iv.success(javabean);
}
}
@Override
public void onFailes(Exception e) {
iv.failed(e);
}
});
}
//防止内存泄漏
public void detachView() {
if (iv != null) {
iv = null;
}
}
}
//防止内存泄漏
public void detachView
() {
if
(
iv !=
null
) {
iv =
null;
}
}
}
view包
public interface LoginView {
void success(LoginBean news);
void failed(Exception e);
}
public interface Registerivew {
void success(RegisterBean news);
void failed(Exception e);
}
最重要的来了啊 好好看啦
API
public class Api {
public static final String LOGIN ="http://120.27.23.105/user/login";
public static final String REG ="http://120.27.23.105/user/reg";
}
LoginActivity
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class LoginActivity extends AppCompatActivity implements LoginView {
@BindView(R.id.touxiang)
ImageView touxiang;
@BindView(R.id.myname)
EditText myname;
@BindView(R.id.mypassword)
EditText mypassword;
@BindView(R.id.shoujizhuce)
TextView shoujizhuce;
@BindView(R.id.zhuce)
TextView zhuce;
@BindView(R.id.login)
TextView login;
// private LoginBean data=new LoginBean();
private String name;
private String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
Log.d("信息", "登录页面");
}
@OnClick({R.id.touxiang, R.id.zhuce, R.id.login})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.touxiang:
break;
case R.id.zhuce:
Intent intent = new Intent(this, RegisterActivity.class);
startActivity(intent);
break;
case R.id.login:
name = this.myname.getText().toString();
password = this.mypassword.getText().toString();
LoginPresaenter presaenter = new LoginPresaenter();
presaenter.attchview(this, name, password);
presaenter.getNews();
break;
}
}
@Override
public void success(LoginBean news) {
if (news != null) {
String code1 = news.getCode();
Integer integer = Integer.valueOf(code1);
String msg1 = news.getMsg();
if (integer == 0) {
Toast.makeText(this, msg1, Toast.LENGTH_SHORT).show();
SharedPreferences.Editor sp = getSharedPreferences("yhname", MODE_PRIVATE).edit();
sp.putString("name", news.getData().getMobile());
sp.putInt("code", Integer.valueOf(news.getCode()));
sp.commit();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(this, msg1, Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void failed(Exception e) {
Log.d("登录错误:", "啛啛喳喳错错");
}
}
RegisterActivity
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class RegisterActivity extends AppCompatActivity implements Registerivew {
@BindView(R.id.zhucename)
EditText zhucename;
@BindView(R.id.zhucepassword)
EditText zhucepassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
setContentView(R.layout.activity_register);
ButterKnife.bind(this);
}
@OnClick({R.id.fanhui, R.id.zhuce_but})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.fanhui:
finish();
break;
case R.id.zhuce_but:
String zhucename = this.zhucename.getText().toString();
String zhucepassword = this.zhucepassword.getText().toString();
RegisterPresaenter presaenter = new RegisterPresaenter();
presaenter.attchview(this,zhucename,zhucepassword);
presaenter.getNews();
break;
}
}
@Override
public void success(RegisterBean news) {
if(news!=null){
String code = news.getCode();
Integer integer = Integer.valueOf(code);
String msg = news.getMsg();
if(integer==0){
Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
}else{
this.zhucename.setText("");
this.zhucepassword.setText("");
Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void failed(Exception e) {
}
}
这样在出不来我看是废了!!!!
看着一步一步copy。出不来我吧脑袋给你
记得加网络权限 啊