加载用户头像的过程是,首先从本地查看是否存储了用户的头像,如果有,则从本地读取后加载到ImageView中,如果没有,则去服务器下载头像保存到本地,并加载。
public void initData() {
super.initData();
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
final String u_id = pref.getString("u_id", "");
// 联网请求个人中心的数据
getDataFromServer(u_id);
}
在Fragment的onCreateView()中调用initData()方法,该方法使用用户的id去联网请求个人中心的数据。
private void getDataFromServer(String u_id) {
String address = Constant.PERSONAL_CENTER_URL;
HttpUtil.sendPostRequest(address, u_id, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (null == response.body()) {
return;
}
String responseText = URLDecoder.decode(response.body().string(), "utf-8");
// 解析数据
processData(responseText);
}
});
}
在 getDataFromServer()方法中调用了自己写的HttpUtil工具类中的方法去请求服务器数据。这个HttpUtil的方法如下(使用前需在gradle文件中引入okhttp3):
public class HttpUtil {
public static void sendPostRequest(String address, String json, okhttp3.Callback callback) {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(address).post(requestBody).build();
client.newCall(request).enqueue(callback);
}
}
下面进入解析数据的部分,取出客户端返回的数据,用Gson转换为PersonMsg对象后取出User,用这个User中的数据来更新界面。从User中取出用户id,利用id去sd卡中获取到压缩后的Bitmap位图(这里是个大坑,不压缩很容易造成内存溢出OOM的错误,填坑请看我另一篇博文:解决使用Bitmap造成OOM内存溢出的问题)。如果取出的Bitmap不为空,则表示从本地加载到了用户头像,否则就从服务器请求头像数据。
private void processData(String response) {
final PersonMsg personMsg = Utility.handlePersonMsgResponse(response);
if (null == personMsg) {
return;
}
final User user = personMsg.getUser();
// 更新界面
if (getActivity() == null) {
return;
}
final Bitmap bitmap = ImageUtils.getPhotoFromStorage(user.getU_id());
if (bitmap != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {