2018-01-23
原CSDN博客已弃用,文章会逐渐迁移过来。
activity_main.xml
<?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:orientation="vertical"
tools:context="com.administrator.testapp.MainActivity">
<Button
android:id="@+id/login_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"
/>
<Button
android:id="@+id/regist_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="注册"
/>
</LinearLayout>
Api.java
package com.administrator.testapp;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
/**
* Created by Administrator on 2018/5/18.
*/
public interface Api {
@POST
@FormUrlEncoded
Call<String> get(@Field("111") String name);
//用户注册
@POST("account/register")
@FormUrlEncoded
Call<String> postRegister(@Field("phone") String phone,@Field("password") String password);
//用户登录
@POST("account/login")
@FormUrlEncoded
Call<UserInfo> postLogin(@Field("phone") String phone,@Field("password") String password);
}
MyCallBack.java
package com.administrator.testapp;
import android.app.Activity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by Administrator on 2018/5/18.
*/
public abstract class MyCallBack<T> implements Callback<T> {
private Activity mActivity;
public MyCallBack(Activity activity){
mActivity = activity;
}
@Override
public void onResponse(final Call<T> call, final Response<T> response) {
/**
* 运行在主线程
*/
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
onSuccess(call,response);
}
});
}
@Override
public void onFailure(final Call<T> call, final Throwable t) {
/**
* 运行在主线程
*/
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
onFailure(call,t);
}
});
}
protected abstract void onSuccess(Call<T> call, Response<T> response);
protected void onFailed(Call<T> call, Throwable t){}
}
UserInfo.java
package com.administrator.testapp;
import com.google.gson.annotations.SerializedName;
/**
* Created by Administrator on 2018/5/18.
*/
public class UserInfo {
/**
* code : 200
* data : {"id":11,"userId":"708c81de-e771-4023-a1e1-e4e1c25ef4db","phone":"13800000000","password":"f059cb6d44add2376f3859059383bbbe","enable":0,"createDate":1526631243000,"updateDate":1526631243000}
* info : 登录成功
*/
@SerializedName("code")
private int code;
@SerializedName("data")
private DataBean data;
@SerializedName("info")
private String info;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public static class DataBean {
/**
* id : 11
* userId : 708c81de-e771-4023-a1e1-e4e1c25ef4db
* phone : 13800000000
* password : f059cb6d44add2376f3859059383bbbe
* enable : 0
* createDate : 1526631243000
* updateDate : 1526631243000
*/
@SerializedName("id")
private int id;
@SerializedName("userId")
private String userId;
@SerializedName("phone")
private String phone;
@SerializedName("password")
private String password;
@SerializedName("enable")
private int enable;
@SerializedName("createDate")
private long createDate;
@SerializedName("updateDate")
private long updateDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getEnable() {
return enable;
}
public void setEnable(int enable) {
this.enable = enable;
}
public long getCreateDate() {
return createDate;
}
public void setCreateDate(long createDate) {
this.createDate = createDate;
}
public long getUpdateDate() {
return updateDate;
}
public void setUpdateDate(long updateDate) {
this.updateDate = updateDate;
}
}
}
RetrofitUtil.java
package com.administrator.testapp;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
/**
* Created by Administrator on 2018/5/18.
*/
public class RetrofitUtil {
private static Retrofit sRetrofit;
private static OkHttpClient mOkHttpClient;
private RetrofitUtil(){}
public static class Hide{
static RetrofitUtil sRetrofitUtil = new RetrofitUtil();
}
public static RetrofitUtil getInstance() {
return Hide.sRetrofitUtil;
}
public Api build(){
if(mOkHttpClient == null){
mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build();
}
if(sRetrofit == null){
sRetrofit = new Retrofit.Builder()
.baseUrl("http://116.196.111.10:8050/")
.client(mOkHttpClient)
.addConverterFactory(ScalarsConverterFactory.create()) //数据转换器
.addConverterFactory(GsonConverterFactory.create())//数据转换器
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//rxjava转换器
.build();
}
return sRetrofit.create(Api.class);
}
}
MainActivity.java
package com.administrator.testapp;
import android.app.DownloadManager;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.Gson;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public UserInfo mUserInfo;
private static final String TAG = "MainActivity";
private Button btnLogin;
private Button btnRegister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogin = findViewById(R.id.login_btn);
btnRegister = findViewById(R.id.regist_btn);
btnLogin.setOnClickListener(this);
btnRegister.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login_btn:
RetrofitUtil.getInstance().build()
.postLogin("13800000000","a13800000000")
.enqueue(new Callback<UserInfo>() {
@Override
public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
UserInfo data = response.body();
//跨页面传值
// startActivity(new Intent(MainActivity.this,xxx.class).putExtra("data",new Gson().toJson(data)));
// SpUtil mSpUtil = new SpUtil(MainActivity.this,new Gson().toJson(data));
// UserInfo mUserInfo = response.body();
// Log.e(TAG,String.valueOf(mUserInfo.getData().getId()));
//// ----------------------------
// /**
// * 存
// */
// MyApplication.sSpUtil.putString("userInfo",new Gson().toJson(data));
// /**
// * 取
// */
// String userInfo = MyApplication.sSpUtil.getString("userInfo");
//// UserInfo u = new Gson().fromJson(userInfo,UserInfo.class);//把new Gson()封住进MyApplication类
// UserInfo u = MyApplication.sGson.fromJson(userInfo,UserInfo.class);
//
//// ------------------------------
/**
* 存用户信息
*/
MyApplication.setUserInfo(data);
/**
* 取用户信息
*/
UserInfo mUserInfo = MyApplication.getUserInfo();
mUserInfo.getData().getId();
}
@Override
public void onFailure(Call<UserInfo> call, Throwable t) {
}
});
break;
case R.id.regist_btn:
RetrofitUtil.getInstance().build()
.postRegister("13800000000","a13800000000")
.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.e(TAG,"onSuccess:" +response.body());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.e(TAG,"onFailure:" +t.toString());
// t.printStackTrace();
}
});
// Log.e(TAG,"注册");
break;
}
}
}
SpUtil.java
package com.administrator.testapp;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Map;
public class SpUtil {
private SharedPreferences sp;
private SharedPreferences.Editor editor;
/**
* SPUtils构造函数
* <p>在Application中初始化</p>
*
* @param context 上下文
* @param spName spName
*/
public SpUtil(Context context, String spName) {
sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
editor = sp.edit();
editor.apply();
}
/**
* SP中写入String类型value
*
* @param key 键
* @param value 值
*/
public void putString(String key, String value) {
editor.putString(key, value).apply();
}
/**
* SP中读取String
*
* @param key 键
* @return 存在返回对应值,不存在返回默认值{@code null}
*/
public String getString(String key) {
return getString(key, null);
}
/**
* SP中读取String
*
* @param key 键
* @param defaultValue 默认值
* @return 存在返回对应值,不存在返回默认值{@code defaultValue}
*/
public String getString(String key, String defaultValue) {
return sp.getString(key, defaultValue);
}
/**
* SP中写入int类型value
*
* @param key 键
* @param value 值
*/
public void putInt(String key, int value) {
editor.putInt(key, value).apply();
}
/**
* SP中读取int
*
* @param key 键
* @return 存在返回对应值,不存在返回默认值-1
*/
public int getInt(String key) {
return getInt(key, -1);
}
/**
* SP中读取int
*
* @param key 键
* @param defaultValue 默认值
* @return 存在返回对应值,不存在返回默认值{@code defaultValue}
*/
public int getInt(String key, int defaultValue) {
return sp.getInt(key, defaultValue);
}
/**
* SP中写入long类型value
*
* @param key 键
* @param value 值
*/
public void putLong(String key, long value) {
editor.putLong(key, value).apply();
}
/**
* SP中读取long
*
* @param key 键
* @return 存在返回对应值,不存在返回默认值-1
*/
public long getLong(String key) {
return getLong(key, -1L);
}
/**
* SP中读取long
*
* @param key 键
* @param defaultValue 默认值
* @return 存在返回对应值,不存在返回默认值{@code defaultValue}
*/
public long getLong(String key, long defaultValue) {
return sp.getLong(key, defaultValue);
}
/**
* SP中写入float类型value
*
* @param key 键
* @param value 值
*/
public void putFloat(String key, float value) {
editor.putFloat(key, value).apply();
}
/**
* SP中读取float
*
* @param key 键
* @return 存在返回对应值,不存在返回默认值-1
*/
public float getFloat(String key) {
return getFloat(key, -1f);
}
/**
* SP中读取float
*
* @param key 键
* @param defaultValue 默认值
* @return 存在返回对应值,不存在返回默认值{@code defaultValue}
*/
public float getFloat(String key, float defaultValue) {
return sp.getFloat(key, defaultValue);
}
/**
* SP中写入boolean类型value
*
* @param key 键
* @param value 值
*/
public void putBoolean(String key, boolean value) {
editor.putBoolean(key, value).apply();
}
/**
* SP中读取boolean
*
* @param key 键
* @return 存在返回对应值,不存在返回默认值{@code false}
*/
public boolean getBoolean(String key) {
return getBoolean(key, false);
}
/**
* SP中读取boolean
*
* @param key 键
* @param defaultValue 默认值
* @return 存在返回对应值,不存在返回默认值{@code defaultValue}
*/
public boolean getBoolean(String key, boolean defaultValue) {
return sp.getBoolean(key, defaultValue);
}
/**
* SP中获取所有键值对
*
* @return Map对象
*/
public Map<String, ?> getAll() {
return sp.getAll();
}
/**
* SP中移除该key
*
* @param key 键
*/
public void remove(String key) {
editor.remove(key).apply();
}
/**
* SP中是否存在该key
*
* @param key 键
* @return {@code true}: 存在<br>{@code false}: 不存在
*/
public boolean contains(String key) {
return sp.contains(key);
}
/**
* SP中清除所有数据
*/
public void clear() {
editor.clear().apply();
}
}
Constant.java
package com.administrator.testapp;
/**
* Created by Administrator on 2018/5/18.
*/
public class Constant {
public static final String USERINFO = "userInfo";
}
MyApplication.java
package com.administrator.testapp;
import android.app.Application;
import com.google.gson.Gson;
/**
* Created by Administrator on 2018/5/18.
* 这个类随着App的启动而启动随着App的销毁而销毁,不受Activity影响
* 里面的成员变量也不会随Activity销毁而销毁
*/
public class MyApplication extends Application {
public static SpUtil sSpUtil;
public static Gson sGson;
@Override
public void onCreate() {
super.onCreate();
sSpUtil = new SpUtil(this,"config");
sGson = new Gson();
}
public static void setUserInfo(UserInfo userInfo){
sSpUtil.putString(Constant.USERINFO,sGson.toJson(userInfo));
}
public static UserInfo getUserInfo(){
String userInfo = sSpUtil.getString(Constant.USERINFO);
UserInfo u = sGson.fromJson(userInfo,UserInfo.class);
return u;
}
}
别忘了调用MyApplication继承Application类的时候,为了MyApplication类能生效,在AndroidManifest.xml的application标签的name属性处设置值为name=”.MyApplication”,如图:
A页面跳B页面传值
定义一个类,继承Application,这个类在App启动时启动,结束时结束
如果把body放在MyApplication里,则app销毁之前都在
该类内的值要确保不会有空指针,外部调用
其他类用
数据存取的方法
进一步提取公共部分
提取后调用发生了变化
如果十几个类都调用了userInfo,修改时候非常麻烦,提取公共部分,写个类Constant.java,修饰成静态的final
外部调用
这样就写活了
那我每次都要
String userInfo = MyApplication.sSpUtil.getString(Constant.USERINFO);
User u = MyApplication.sGson.fromJson(userInfo,User.class);
这样写非常麻烦
我们可以吧这个方法写在application里
用的时候
万一你还要存 银行卡信息 或者别的信息
项目Demo: