一.存儲方式分類:SharedPreferences存儲
二.SharedPreferences存儲
1.特點
①存儲單一數據,例如數值,字符串,布爾
②文件:/date/date/包名/shared_prefs/xxx.xml:
③以鍵值對的形式存儲
④可以設置不被其他應用操作
2.API
(1)SharedPreferences
①獲取實例context.getSharedPreferences():
1)name 存儲文件名; 2)mode 操作模式:MODE_PRIVATE不能被別的應用訪問,覆蓋模式;MODE_APPEND不能被別的應用訪問,追加模式;
②啓動編輯器:edit():返回Editor
③讀取Value:1)getString(key,defValue 缺省值) 2)getAll( ) 返回所有鍵值對的 Map集合
(2)Editor
①存放數據:1)putString(key,value) 2)putLong(key,value) 3)putInt 4)putFloat 5)putBoolean 6)putStringSet
②提交存儲
③clear() 清除
④remove(String key) 移除指令key的鍵值對
下面請允許我盜一張圖
下面開始我的表演
看樣子中午還是要休息一下,打疲勞戰隊身體沒好處,而且寫的代碼質量也不高!
場景一
首先我要實現的功能就是簡單的註銷用戶,當然方法有很多,你可以通過EventBus或者RXBus註冊訂閱者然後發佈一個事件出去,另外一種就是通過後臺移除session,清除當前的sesssionid 因爲相信大家都知道,客戶端只有一個Cookie,Cookie對應服務端Session的key,首先登錄的時候服務端返回一個sessionid給我然後我通過sp把拿到的SessionId保存起來,然後在點擊退出當前用戶的時候把之前登錄的SessionId提交過去與服務端那邊對比,如果對比一致說明我已經登錄過了,然後這時候服務端移除session,返回給我,提示成功退出!
聽起來好像思路有點清晰,下面開始我的表演Action
因爲我這邊提交的都是json格式的數據下面是點擊到登錄按鈕提交的json數據這時候服務器給我返回sid
Gson gson = new Gson();
final HashMap<String, String> params = new HashMap<>();
params.put("username", "18388483434");
params.put("pass", "123456");
final String strEntity = gson.toJson(params);
RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), strEntity);
AccountService account = RetrofitApiManager.getInstance().getService(AccountService.class);
Call<LoginResponse> call = account.login(body);
final String sessionId=null;
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (response.isSuccessful()) {
if (sp == null) {
sp = getSharedPreferences("exitsid",MODE_PRIVATE);
}
SharedPreferences.Editor editor = sp.edit();
//sessionid
editor.putString("sid", sessionId);
//異步提交
Toast.makeText(LoginActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
// Log.i(TAG, "onResponse: " + response.body().getCode() + response.body().getMessage());
startActivity(new Intent(LoginActivity.this, MainActivity.class));
editor.apply();
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
登錄抓包信息如下Fiddler
請求的接口地址因爲這裏提交的是json數據所以這裏添加一個請求頭信息,如果你自己覺得太死板,請自定義攔截器,這個沒有問題,根據自己的需求來。
@Headers("Content-type:application/json;charset=UTF-8")
@POST("xxx/login")
Call<LoginResponse> login(@Body RequestBody body);
下面是我的響應bean我這裏直接GsonFormat生成
package com.visoport.medicine.http.api.response;
/**
* 登錄服務器返回LoginResponse
*/
public class LoginResponse {
private int code;
private DataBean data;
private String message;
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 getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public static class DataBean {
private String sid;
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
}
}
下面是註銷用戶
請求接口loginout
//退出當前用戶
@Headers("Content-type:application/json;charset=UTF-8")
@POST("xxx/login/logout")
Call<ExitUserResponse> logout(@Body RequestBody body);
服務端響應的bean跟上面的LoginResponse一致同樣是GsonFormat生成
/**
* 退出登錄
*/
public class ExitUserResponse {
/**
* code : 1200
* data : {"sid":"67b4edd5346c447afe7b9cd0ef"}
* message : 成功退出
*/
private int code;
private DataBean data;
private String message;
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 getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public static class DataBean {
private String sid;
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
}
}
然後點擊退出按鈕 代碼很亂後期整理
final String sessionId;
if (sp == null) {
sp = getSharedPreferences("exitsid",MODE_PRIVATE);
}
//後面是默認值defaultvalue
sessionId = sp.getString("sid", "");
Gson gson = new Gson();
final HashMap<String, String> params = new HashMap<>();
params.put("sid", sessionId);
Log.i(TAG, "onClick: "+sessionId);
String strEntity = gson.toJson(params);
RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), strEntity);
AccountService account = RetrofitApiManager.getInstance().getService(AccountService.class);
Call<ExitUserResponse> call = account.logout(body);
call.enqueue(new Callback<ExitUserResponse>() {
@Override
public void onResponse(Call<ExitUserResponse> call, Response<ExitUserResponse> response) {
if(response.isSuccessful())
{
Toast.makeText(SettingActivity.this,response.body().getMessage(),Toast.LENGTH_SHORT).show();
startActivity(new Intent(SettingActivity.this,LoginActivity.class));
}
}
@Override
public void onFailure(Call<ExitUserResponse> call, Throwable t) {
Toast.makeText(SettingActivity.this,t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
我去,什麼鬼,缺少參數,什麼參數,爲什麼會這樣,不就是一個sessionid嗎?好吧我承認我菜,那斷點試試,工欲善其事,必先利其器,那就debug走起不好意思debug今天出了點問題,哈哈!
其實就是自己不小心把那句代碼註釋掉了手賤!
String sessionId = response.body().getData().getSid();
因爲之前的sessionId初始化就是null你怎麼可能拿得到嗎?後面的讀取時沒有問題的!狠狠的給自己一巴掌!
final String sessionId=null;
下面直接看最後的表演圖
總結:
1、 還是基本功好紮實,首先了解sp簡單用法包括存儲 寫入文件 以及讀取文件等
2、出現問題學會debug慢慢調試 看程序的走勢進一步找出問題所在
3、必要的時候使用抓包神器Fildder那麼問題迎刃而解