团队作业-4

添加用户

package com.example.faceapp.ui.adduser;


import static com.example.faceapp.api.ApiUrls.ADD_USER_URL;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.faceapp.R;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddUserActivity extends AppCompatActivity {

    private EditText etUserId, etUserName, etUserPassword;
    private Button btnSubmit;
    private TextView tvErrorMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_user);

        // 初始化视图组件
        etUserId = findViewById(R.id.et_user_id);
        etUserName = findViewById(R.id.et_user_name);
        etUserPassword = findViewById(R.id.et_user_password);
        btnSubmit = findViewById(R.id.btn_submit);
        tvErrorMessage = findViewById(R.id.tv_error_message);

        // 设置提交按钮点击事件监听器
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitForm();
            }
        });
    }

    private void submitForm() {
        String userId = etUserId.getText().toString().trim();
        String userName = etUserName.getText().toString().trim();
        String userPassword = etUserPassword.getText().toString().trim();

        if (userId.isEmpty() || userName.isEmpty() || userPassword.isEmpty()) {
            tvErrorMessage.setText("请填写所有字段");
            tvErrorMessage.setVisibility(View.VISIBLE);
            return;
        }

        // 构建请求体
        Map<String, String> requestData = new HashMap<>();
        requestData.put("id", userId);
        requestData.put("name", userName);
        requestData.put("password", userPassword);

        Gson gson = new Gson();
        String json = gson.toJson(requestData);

        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);

        // 创建 OkHttp 客户端
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(ADD_USER_URL)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    tvErrorMessage.setText("添加失败:网络错误");
                    tvErrorMessage.setVisibility(View.VISIBLE);
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    runOnUiThread(() -> {
                        Toast.makeText(AddUserActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                        finish();
                    });
                } else {
                    String errorMessage = response.body().string();
                    runOnUiThread(() -> {
                        tvErrorMessage.setText("添加失败:" + errorMessage);
                        tvErrorMessage.setVisibility(View.VISIBLE);
                    });
                }
            }
        });
    }
}

修改密码

package com.example.faceapp.ui.changepassword;

import static com.example.faceapp.api.ApiUrls.CHANGE_PASSWORD_URL;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.faceapp.ui.main.MainActivity;
import com.example.faceapp.R;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChangePasswordActivity extends AppCompatActivity {

    private EditText etOldPassword, etNewPassword, etConfirmPassword;
    private Button btnSubmit;
    private TextView tvErrorMessage;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_password);

        // 初始化视图组件
        etOldPassword = findViewById(R.id.et_old_password);
        etNewPassword = findViewById(R.id.et_new_password);
        etConfirmPassword = findViewById(R.id.et_confirm_password);
        btnSubmit = findViewById(R.id.btn_submit);
        tvErrorMessage = findViewById(R.id.tv_error_message);

        // 获取 SharedPreferences 中的用户信息
        sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);

        // 设置提交按钮点击事件监听器
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitForm();
            }
        });
    }

    private void submitForm() {
        String oldPassword = etOldPassword.getText().toString().trim();
        String newPassword = etNewPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();

        if (oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
            tvErrorMessage.setText("请填写所有字段");
            tvErrorMessage.setVisibility(View.VISIBLE);
            return;
        }

        if (!newPassword.equals(confirmPassword)) {
            tvErrorMessage.setText("新密码与确认密码不一致");
            tvErrorMessage.setVisibility(View.VISIBLE);
            return;
        }

        // 获取用户 ID
        String userId = sharedPreferences.getString("id", "");

        // 构建请求体
        Map<String, String> requestData = new HashMap<>();
        requestData.put("userId", userId);
        requestData.put("oldPassword", oldPassword);
        requestData.put("newPassword", newPassword);

        Gson gson = new Gson();
        String json = gson.toJson(requestData);

        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);

        // 创建 OkHttp 客户端
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(CHANGE_PASSWORD_URL)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    tvErrorMessage.setText("修改失败:网络错误");
                    tvErrorMessage.setVisibility(View.VISIBLE);
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    runOnUiThread(() -> {
                        Toast.makeText(ChangePasswordActivity.this, "密码修改成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(ChangePasswordActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    });
                } else {
                    String errorMessage = response.body().string();
                    runOnUiThread(() -> {
                        tvErrorMessage.setText("修改失败:" + errorMessage);
                        tvErrorMessage.setVisibility(View.VISIBLE);
                    });
                }
            }
        });
    }
}

导入人脸

package com.example.faceapp.ui.importstudents;

import static com.example.faceapp.api.ApiUrls.FACE_REGISTRATION_URL;
import static com.example.faceapp.api.ApiUrls.LESSONS_URL;

import android.Manifest;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.faceapp.R;
import com.example.faceapp.model.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ImportStudentsActivity extends AppCompatActivity implements SurfaceHolder.Callback {

    private EditText etInputName;
    private Button btnClearData, btnCreateFaceFolder, btnQueryFaceData, btnConvertFormat;
    private Button btnToggleCamera, btnSaveCurrentFace, btnImportFaceData;
    private SurfaceView svCameraPreview;
    private Spinner spLessonSelector;
    private TextView tvTotalFacesCount, tvCurrentFacePhotosCount, tvProcessStatus;
    private TextView tvSuccessCount, tvErrorHeader;
    private ListView lvErrorItems;
    private LinearLayout llImportResult, llErrorList;

    private Camera camera;
    private SurfaceHolder surfaceHolder;
    private boolean isCameraActive = false;
    private String currentFaceDir = "";
    private int totalFacesCount = 0;
    private int currentFacePhotosCount = 0;
    private List<String> lessonIds = new ArrayList<>();
    private List<String> lessonNames = new ArrayList<>();
    private String selectedLessonId = "";

    private OkHttpClient client = new OkHttpClient();
    private Handler handler = new Handler(Looper.getMainLooper());

    private static final int CAMERA_PERMISSION_REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_import_students);

        // 初始化视图
        etInputName = findViewById(R.id.et_input_name);
        btnClearData = findViewById(R.id.btn_clear_data);
        btnCreateFaceFolder = findViewById(R.id.btn_create_face_folder);
        btnQueryFaceData = findViewById(R.id.btn_query_face_data);
        btnConvertFormat = findViewById(R.id.btn_convert_format);
        btnToggleCamera = findViewById(R.id.btn_toggle_camera);
        btnSaveCurrentFace = findViewById(R.id.btn_save_current_face);
        btnImportFaceData = findViewById(R.id.btn_import_face_data);
        svCameraPreview = findViewById(R.id.sv_camera_preview);
        spLessonSelector = findViewById(R.id.sp_lesson_selector);
        tvTotalFacesCount = findViewById(R.id.tv_total_faces_count);
        tvCurrentFacePhotosCount = findViewById(R.id.tv_current_face_photos_count);
        tvProcessStatus = findViewById(R.id.tv_process_status);
        tvSuccessCount = findViewById(R.id.tv_success_count);
        tvErrorHeader = findViewById(R.id.tv_error_header);
        lvErrorItems = findViewById(R.id.lv_error_items);
        llImportResult = findViewById(R.id.ll_import_result);
        llErrorList = findViewById(R.id.ll_error_list);

        // 初始化摄像头预览
        surfaceHolder = svCameraPreview.getHolder();
        surfaceHolder.addCallback(this);

        // 检查相机权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    CAMERA_PERMISSION_REQUEST_CODE);
        }

        // 加载课程列表
        fetchLessons();

        // 更新人脸计数
        updateFaceCount();

        // 设置按钮点击事件
        btnClearData.setOnClickListener(v -> clearData());
        btnCreateFaceFolder.setOnClickListener(v -> createFaceFolder());
        btnQueryFaceData.setOnClickListener(v -> queryFaceData());
        btnConvertFormat.setOnClickListener(v -> convertFormat());
        btnToggleCamera.setOnClickListener(v -> toggleCamera());
        btnSaveCurrentFace.setOnClickListener(v -> saveCurrentFace());
        btnImportFaceData.setOnClickListener(v -> importFaceData());

        // 设置课程选择器监听器
        spLessonSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedLessonId = lessonIds.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                selectedLessonId = "";
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予,可进行相机操作
            } else {
                // 权限被拒绝,提示用户
                Toast.makeText(this, "未授予相机权限,无法使用相机", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            try {
                camera = Camera.open();
                camera.setPreviewDisplay(holder);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (surfaceHolder.getSurface() == null) {
            return;
        }

        try {
            camera.stopPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            try {
                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    private void fetchLessons() {
        tvProcessStatus.setText("正在加载课程列表...");
        OkHttpClient client = new OkHttpClient();
        // 获取用户信息
        String userJson = getSharedPreferences("user_info", MODE_PRIVATE).getString("user", "");
        User user = new Gson().fromJson(userJson, User.class);
        Request request = new Request.Builder()
                .url(LESSONS_URL + "?name=" + user.getName())
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> {
                    tvProcessStatus.setText("加载课程失败");
                    Log.e("ImportStudents", "加载课程失败: " + e.getMessage());
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String jsonData = response.body().string();
                    Type listType = new TypeToken<ArrayList<Lesson>>() {}.getType();
                    List<Lesson> lessons = new Gson().fromJson(jsonData, listType);

                    handler.post(() -> {
                        List<String> lessonNames = new ArrayList<>();
                        lessonIds.clear();
                        for (Lesson lesson : lessons) {
                            lessonIds.add(lesson.getId());
                            lessonNames.add(lesson.getClassName());
                        }

                        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                                ImportStudentsActivity.this,
                                android.R.layout.simple_spinner_item,
                                lessonNames
                        );
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spLessonSelector.setAdapter(adapter);
                        tvProcessStatus.setText("");
                    });
                } else {
                    handler.post(() -> {
                        tvProcessStatus.setText("加载课程失败");
                        Log.e("ImportStudents", "加载课程失败,响应码: " + response.code());
                    });
                }
            }
        });
    }

    private void updateFaceCount() {
        tvProcessStatus.setText("正在更新人脸计数...");
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), "{\"action\": \"check_count\"}");
        Request request = new Request.Builder()
                .url(FACE_REGISTRATION_URL)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> {
                    tvProcessStatus.setText("更新人脸计数失败");
                    Log.e("ImportStudents", "更新人脸计数失败: " + e.getMessage());
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        totalFacesCount = jsonObject.getInt("total_faces");
                        currentFacePhotosCount = jsonObject.getInt("current_face_photos");

                        handler.post(() -> {
                            tvTotalFacesCount.setText(String.valueOf(totalFacesCount));
                            tvCurrentFacePhotosCount.setText("当前人脸已保存: " + currentFacePhotosCount + "张");
                            tvProcessStatus.setText("");
                        });
                    } catch (org.json.JSONException e) {
                        e.printStackTrace();
                        handler.post(() -> {
                            tvProcessStatus.setText("解析人脸计数数据失败");
                        });
                    }
                } else {
                    handler.post(() -> {
                        tvProcessStatus.setText("更新人脸计数失败");
                    });
                }
            }
        });
    }

    private void clearData() {
        tvProcessStatus.setText("正在删除全部数据...");
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), "{\"action\": \"clear\"}");
        Request request = new Request.Builder()
                .url(FACE_REGISTRATION_URL)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> {
                    tvProcessStatus.setText("删除数据失败");
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    handler.post(() -> {
                        tvProcessStatus.setText("删除数据成功");
                        updateFaceCount();
                    });
                } else {
                    handler.post(() -> {
                        tvProcessStatus.setText("删除数据失败");
                    });
                }
            }
        });
    }

    // 修改 createFaceFolder 方法中的请求处理
    private void createFaceFolder() {
        String name = etInputName.getText().toString().trim();
        if (name.isEmpty()) {
            Toast.makeText(this, "请输入姓名", Toast.LENGTH_SHORT).show();
            return;
        }

        tvProcessStatus.setText("正在创建人脸文件夹...");

        // 创建正确的 JSON 请求体
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("action", "create_folder");
            jsonBody.put("name", name);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(
                MediaType.parse("application/json"),
                jsonBody.toString()
        );

        Request request = new Request.Builder()
                .url(FACE_REGISTRATION_URL)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> {
                    tvProcessStatus.setText("创建人脸文件夹失败: " + e.getMessage());
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        String status = jsonObject.getString("status");

                        if ("success".equals(status)) {
                            // 使用正确的字段名 "folder_path"
                            currentFaceDir = jsonObject.getString("folder_path");

                            handler.post(() -> {
                                tvProcessStatus.setText("创建人脸文件夹成功");
                                updateFaceCount(); // 更新计数
                            });
                        } else {
                            String message = jsonObject.optString("message", "未知错误");
                            handler.post(() -> {
                                tvProcessStatus.setText("创建失败: " + message);
                            });
                        }
                    } catch (JSONException e) {
                        handler.post(() -> {
                            tvProcessStatus.setText("解析响应失败");
                        });
                    }
                } else {
                    handler.post(() -> {
                        tvProcessStatus.setText("服务器错误: " + response.code());
                    });
                }
            }
        });
    }

    private void queryFaceData() {
        tvProcessStatus.setText("正在查询人脸数据...");
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), "{\"action\": \"query_data\"}");
        Request request = new Request.Builder()
                .url(FACE_REGISTRATION_URL)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> {
                    tvProcessStatus.setText("查询人脸数据失败");
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        JSONArray data = jsonObject.getJSONArray("data");
                        handler.post(() -> {
                            tvProcessStatus.setText("查询人脸数据成功,共 " + data.length() + " 条记录");
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                        handler.post(() -> {
                            tvProcessStatus.setText("解析查询人脸数据响应失败");
                        });
                    }
                } else {
                    handler.post(() -> {
                        tvProcessStatus.setText("查询人脸数据失败");
                    });
                }
            }
        });
    }

    private void convertFormat() {
        tvProcessStatus.setText("正在进行格式转换...");
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), "{\"action\": \"convert_format\"}");
        Request request = new Request.Builder()
                .url(FACE_REGISTRATION_URL)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> {
                    tvProcessStatus.setText("格式转换失败");
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        boolean success = jsonObject.getBoolean("success");
                        if (success) {
                            handler.post(() -> {
                                tvProcessStatus.setText("格式转换成功");
                            });
                        } else {
                            handler.post(() -> {
                                tvProcessStatus.setText("格式转换失败");
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        handler.post(() -> {
                            tvProcessStatus.setText("解析格式转换响应失败");
                        });
                    }
                } else {
                    handler.post(() -> {
                        tvProcessStatus.setText("格式转换失败");
                    });
                }
            }
        });
    }

    private void toggleCamera() {
        if (isCameraActive) {
            if (camera != null) {
                camera.stopPreview();
                camera.release();
                camera = null;
            }
            isCameraActive = false;
            btnToggleCamera.setText("录入人脸数据");
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CAMERA},
                        CAMERA_PERMISSION_REQUEST_CODE);
            } else {
                try {
                    camera = Camera.open();
                    camera.setPreviewDisplay(surfaceHolder);
                    camera.startPreview();
                    isCameraActive = true;
                    btnToggleCamera.setText("停止录入人脸数据");
                } catch (IOException e) {
                    e.printStackTrace();
                    tvProcessStatus.setText("启动摄像头失败");
                }
            }
        }
    }

    private void saveCurrentFace() {
        if (!isCameraActive) {
            Toast.makeText(this, "请先开启摄像头", Toast.LENGTH_SHORT).show();
            return;
        }
        tvProcessStatus.setText("正在保存当前人脸...");
        camera.takePicture(null, null, (data, camera) -> {
            RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), data);
            Request request = new Request.Builder()
                    .url(FACE_REGISTRATION_URL + "/save_face?dir=" + currentFaceDir)
                    .post(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    handler.post(() -> {
                        tvProcessStatus.setText("保存当前人脸失败");
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        handler.post(() -> {
                            tvProcessStatus.setText("保存当前人脸成功");
                            updateFaceCount();
                        });
                    } else {
                        handler.post(() -> {
                            tvProcessStatus.setText("保存当前人脸失败");
                        });
                    }
                }
            });
        });
    }

    private void importFaceData() {
        if (selectedLessonId.isEmpty()) {
            Toast.makeText(this, "请选择课程", Toast.LENGTH_SHORT).show();
            return;
        }
        tvProcessStatus.setText("正在导入人脸数据...");
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), "{\"action\": \"import_data\", \"lessonId\": \"" + selectedLessonId + "\"}");
        Request request = new Request.Builder()
                .url(FACE_REGISTRATION_URL)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> {
                    tvProcessStatus.setText("导入人脸数据失败");
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        int successCount = jsonObject.getInt("success_count");
                        JSONArray errorList = jsonObject.getJSONArray("error_list");

                        handler.post(() -> {
                            tvSuccessCount.setText("✅ 成功导入 " + successCount + " 条数据");
                            if (errorList.length() > 0) {
                                tvErrorHeader.setText("❌ 失败 " + errorList.length() + " 条:");
                                ArrayAdapter<String> adapter = new ArrayAdapter<>(
                                        ImportStudentsActivity.this,
                                        android.R.layout.simple_list_item_1,
                                        new ArrayList<String>() {{
                                            for (int i = 0; i < errorList.length(); i++) {
                                                try {
                                                    add(errorList.getString(i));
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }}
                                );
                                lvErrorItems.setAdapter(adapter);
                                llErrorList.setVisibility(View.VISIBLE);
                            } else {
                                llErrorList.setVisibility(View.GONE);
                            }
                            llImportResult.setVisibility(View.VISIBLE);
                            tvProcessStatus.setText("导入人脸数据完成");
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                        handler.post(() -> {
                            tvProcessStatus.setText("解析导入人脸数据响应失败");
                        });
                    }
                } else {
                    handler.post(() -> {
                        tvProcessStatus.setText("导入人脸数据失败");
                    });
                }
            }
        });
    }

    // 课程实体类
    static class Lesson {
        private String id;
        private String className;

        public String getId() {
            return id;
        }

        public String getClassName() {
            return className;
        }
    }

}
posted @ 2025-05-18 23:07  sword_kong  阅读(5)  评论(0)    收藏  举报