package cn.kingvcn.smartcity.activity;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import cn.kingvcn.smartcity.R;
import cn.kingvcn.smartcity.base.Response;
import cn.kingvcn.smartcity.base.UploadResponse;
import cn.kingvcn.smartcity.base.User;
import cn.kingvcn.smartcity.base.UserResponse;
import cn.kingvcn.smartcity.http.RetrofitHelper;
import cn.kingvcn.smartcity.utils.SpUtil;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
public class PersonalInfoActivity extends AppCompatActivity {
private static final int PICTURE = 2;
private ImageView imgBack;
private ImageView imgAvatar;
private EditText editNickName;
private RadioButton rbSexMan;
private RadioButton rbSexWomen;
private EditText editIdCard;
private EditText editPhone;
private Button btnChange;
private User user;
private EditText editAccount;
private EditText editEmail;
private String avatarPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_info);
initView();
loadUser();
}
private void initView() {
imgBack = findViewById(R.id.img_back);
imgAvatar = findViewById(R.id.img_avatar);
editNickName = findViewById(R.id.edit_nick_name);
rbSexMan = findViewById(R.id.rb_sex_man);
rbSexWomen = findViewById(R.id.rb_sex_women);
editIdCard = findViewById(R.id.edit_id_card);
editPhone = findViewById(R.id.edit_phone);
btnChange = findViewById(R.id.btn_change);
editAccount = findViewById(R.id.edit_account);
editEmail = findViewById(R.id.edit_email);
imgBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
imgAvatar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAndroidPermission();
}
});
btnChange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
changeUserInfo();
}
});
}
private void loadUser() {
user = SpUtil.getUser(this);
editNickName.setText(user.getNickName());
if (user.getIdCard() != null && !user.getIdCard().equals("")){
String idCardNumber = user.getIdCard().substring(0, 2) + "************" + user.getIdCard().substring(14);
editIdCard.setText(idCardNumber);
}
editPhone.setText(user.getPhoneNumber());
editAccount.setText(user.getUserName());
editEmail.setText(user.getEmail());
if ("0".equals(user.getSex())) {
rbSexMan.setChecked(true);
} else {
rbSexWomen.setChecked(true);
}
Glide.with(this)
.load(RetrofitHelper.getServerAddress() + "/prod-api" + user.getAvatar())
.error(R.mipmap.ic_launcher)
.into(imgAvatar);
}
private void uploadAvatar(String filePath){
String token = SpUtil.getToken(this);
File avatarFile = new File(filePath);
RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"),
avatarFile);
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", avatarFile.getName(), fileBody);
RetrofitHelper.getAppApi().uploadFile("Bearer " + token, body)
.enqueue(new Callback<UploadResponse>() {
@Override
public void onResponse(Call<UploadResponse> call, retrofit2.Response<UploadResponse> response) {
avatarPath = null;
if (!response.isSuccessful()){
return;
}
UploadResponse uploadResponse = response.body();
if (!"200".equals(uploadResponse.code)){
Toast.makeText(PersonalInfoActivity.this,
"上传失败:" + uploadResponse.msg, Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(PersonalInfoActivity.this, "上传头像成功", Toast.LENGTH_SHORT).show();
avatarPath = uploadResponse.fileName;
}
@Override
public void onFailure(Call<UploadResponse> call, Throwable throwable) {
avatarPath = null;
Toast.makeText(PersonalInfoActivity.this,
"上传失败:" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void changeUserInfo() {
String nickName = editNickName.getText().toString();
if (nickName.length() == 0) {
Toast.makeText(this, "请输入昵称!", Toast.LENGTH_SHORT).show();
return;
}
String phone = editPhone.getText().toString();
if (phone.length() == 0) {
Toast.makeText(this, "请输入联系电话!", Toast.LENGTH_SHORT).show();
return;
}
String sex = rbSexMan.isChecked() ? "0" : "1";
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("nickName", nickName);
jsonObject.addProperty("email", editEmail.getText().toString());
jsonObject.addProperty("phonenumber", phone);
jsonObject.addProperty("sex", sex);
if (avatarPath != null){
jsonObject.addProperty("avatar", avatarPath);
}
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),
jsonObject.toString());
String token = SpUtil.getToken(this);
RetrofitHelper.getAppApi().changeUserInfo("Bearer " + token, requestBody)
.enqueue(new Callback<Response>() {
@Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
if (!response.isSuccessful()) {
return;
}
Response r = response.body();
if (!"200".equals(r.code)) {
Toast.makeText(PersonalInfoActivity.this,
"修改失败:" + r.msg, Toast.LENGTH_SHORT).show();
return;
}
loadUser(token);
Toast.makeText(PersonalInfoActivity.this,
"修改成功!", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<Response> call, Throwable throwable) {
Toast.makeText(PersonalInfoActivity.this,
"修改失败:" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void loadUser(String token) {
RetrofitHelper.getAppApi().getUserInfo("Bearer " + token)
.enqueue(new Callback<UserResponse>() {
@Override
public void onResponse(Call<UserResponse> call, retrofit2.Response<UserResponse> response) {
if (!response.isSuccessful()) {
Toast.makeText(PersonalInfoActivity.this, "http错误", Toast.LENGTH_SHORT).show();
return;
}
UserResponse userResponse = response.body();
if (!"200".equals(userResponse.code)) {
Toast.makeText(PersonalInfoActivity.this, "获取用户信息失败:" + userResponse.msg, Toast.LENGTH_SHORT).show();
return;
}
SpUtil.saveUser(PersonalInfoActivity.this, userResponse.user, token);
}
@Override
public void onFailure(Call<UserResponse> call, Throwable throwable) {
Toast.makeText(PersonalInfoActivity.this,
"获取用户信息失败:" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void checkAndroidPermission() {
List<String> permissionLists = new ArrayList<>();
// if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// permissionLists.add(Manifest.permission.CAMERA);
// }
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
permissionLists.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
// if (!permissionLists.isEmpty()) {//说明肯定有拒绝的权限
// ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), 0);
// } else {
// openAlbum();
// }
if (permissionLists.isEmpty()) {//说明肯定有拒绝的权限
openAlbum();
} else {
ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), 0);
}
}
private void openAlbum() {
Intent picture = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(picture, PICTURE);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0) {
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "权限被拒绝,无法调用摄像头或相册", Toast.LENGTH_SHORT).show();
return;
}
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICTURE && resultCode == Activity.RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePathColumns[0]);
String picturePath = c.getString(columnIndex);
c.close();
uploadAvatar(picturePath);
//获取图片并显示
Glide.with(this).load(Uri.fromFile(new File(picturePath))).into(imgAvatar);
}
}
}
<?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=".activity.PersonalInfoActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal"
android:background="@color/main">
<ImageView
android:id="@+id/img_back"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_marginStart="16dp"
android:src="@mipmap/back_white"/>
<TextView
android:id="@+id/tv_title"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:maxLines="1"
android:background="@color/main"
android:textColor="@color/white"
android:textSize="18sp"
android:text="个人信息"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="10dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="头像"
android:textColor="@color/black"/>
<ImageView
android:id="@+id/img_avatar"
android:layout_width="60dp"
android:layout_height="60dp" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/personal_line"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户账号"
android:textColor="@color/black"/>
<EditText
android:id="@+id/edit_account"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:textColor="@color/black"
android:background="@null"
android:text="007"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/personal_line"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="昵称"
android:textColor="@color/black"/>
<EditText
android:id="@+id/edit_nick_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:textColor="@color/black"
android:background="@null"
android:text="007"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/personal_line"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="邮件"
android:textColor="@color/black"/>
<EditText
android:id="@+id/edit_email"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:textColor="@color/black"
android:background="@null"
android:text="007"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/personal_line"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="10dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="性别"
android:textColor="@color/black"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="20dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_sex_man"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男"/>
<RadioButton
android:id="@+id/rb_sex_women"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"/>
</RadioGroup>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/personal_line"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="证件号"
android:textColor="@color/black"/>
<EditText
android:id="@+id/edit_id_card"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:textColor="@color/black"
android:background="@null"
android:enabled="false"
android:text="007"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/personal_line"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="联系电话"
android:textColor="@color/black"/>
<EditText
android:id="@+id/edit_phone"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:textColor="@color/black"
android:background="@null"
android:text="007"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/personal_line"/>
<Button
android:id="@+id/btn_change"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:text="修改"/>
</LinearLayout>