心理咨询用户安卓端2

package com.example.psychological.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.psychological.R;
import com.example.psychological.adapter.MessageAdapter;
import com.example.psychological.api.RetrofitClient;
import com.example.psychological.model.Message;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MessagesActivity extends AppCompatActivity implements MessageAdapter.OnMessageActionListener { // 实现接口

private RecyclerView recyclerView;
private MessageAdapter adapter;
private List<Message> messageList;
private ProgressBar progressBar;

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

    initViews();
    loadMessages();
}

private void initViews() {
    recyclerView = findViewById(R.id.recycler_view);
    progressBar = findViewById(R.id.progress_bar);

    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("我的消息");
    }

    messageList = new ArrayList<>();
    adapter = new MessageAdapter(messageList);
    adapter.setOnMessageActionListener(this); // 设置监听器
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);
}

private void loadMessages() {
    Long userId = getCurrentUserId();
    if (userId == -1) {
        Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(this, LoginActivity.class));
        finish();
        return;
    }

    progressBar.setVisibility(ProgressBar.VISIBLE);

    Call<List<Message>> call = RetrofitClient.getApiService().getMyMessages(userId);
    call.enqueue(new Callback<List<Message>>() {
        @Override
        public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
            progressBar.setVisibility(ProgressBar.GONE);

            if (response.isSuccessful() && response.body() != null) {
                messageList.clear();
                messageList.addAll(response.body());
                adapter.notifyDataSetChanged();

                if (messageList.isEmpty()) {
                    Toast.makeText(MessagesActivity.this, "暂无消息", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(MessagesActivity.this, "加载消息失败", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<List<Message>> call, Throwable t) {
            progressBar.setVisibility(ProgressBar.GONE);
            Toast.makeText(MessagesActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

private Long getCurrentUserId() {
    return getSharedPreferences("user_prefs", MODE_PRIVATE).getLong("user_id", -1);
}

@Override
public boolean onSupportNavigateUp() {
    finish();
    return true;
}

// 实现接口方法
@Override
public void onStartChat(Message message) {
    Intent intent = new Intent(this, ChatActivity.class);
    intent.putExtra("counselor_id", message.getCounselorId());
    intent.putExtra("counselor_name", message.getCounselorName());
    startActivity(intent);
    Toast.makeText(this, "开始与" + message.getCounselorName() + "对话", Toast.LENGTH_SHORT).show();
}

@Override
public void onBookAppointment(Message message) {
    Intent intent = new Intent(this, BookAppointmentActivity.class);
    intent.putExtra("counselor_id", message.getCounselorId());
    startActivity(intent);
    Toast.makeText(this, "预约" + message.getCounselorName() + "的咨询", Toast.LENGTH_SHORT).show();
}

}
package com.example.psychological.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.psychological.R;
import com.example.psychological.adapter.AppointmentAdapter;
import com.example.psychological.api.RetrofitClient;
import com.example.psychological.model.Appointment;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyAppointmentsActivity extends AppCompatActivity {

private static final int RATING_REQUEST_CODE = 1001; // 添加这行常量定义

private RecyclerView recyclerView;
private AppointmentAdapter adapter;
private List<Appointment> appointmentList;
private ProgressBar progressBar;

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

    initViews();
    loadMyAppointments();
    setupRatingClickListener();
}

private void initViews() {
    recyclerView = findViewById(R.id.recycler_view);
    progressBar = findViewById(R.id.progress_bar);

    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("我的预约");
    }

    appointmentList = new ArrayList<>();
    adapter = new AppointmentAdapter(appointmentList);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);
}

private void setupRatingClickListener() {
    adapter.setOnRatingClickListener(new AppointmentAdapter.OnRatingClickListener() {
        @Override
        public void onRateClick(Appointment appointment) {
            // 跳转到评价页面
            Intent intent = new Intent(MyAppointmentsActivity.this, RatingActivity.class);
            intent.putExtra("appointment_id", appointment.getId());
            intent.putExtra("counselor_name", appointment.getCounselorName());
            startActivityForResult(intent, RATING_REQUEST_CODE);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RATING_REQUEST_CODE && resultCode == RESULT_OK) {
        // 刷新列表
        loadMyAppointments();
        Toast.makeText(this, "评价完成,感谢您的反馈!", Toast.LENGTH_SHORT).show();
    }
}

private void loadMyAppointments() {
    Long userId = getCurrentUserId();
    if (userId == -1) {
        Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra("from_booking", true);
        startActivity(intent);
        finish();
        return;
    }

    progressBar.setVisibility(ProgressBar.VISIBLE);

    Call<List<Appointment>> call = RetrofitClient.getApiService().getMyAppointments(userId);
    call.enqueue(new Callback<List<Appointment>>() {
        @Override
        public void onResponse(Call<List<Appointment>> call, Response<List<Appointment>> response) {
            progressBar.setVisibility(ProgressBar.GONE);

            if (response.isSuccessful() && response.body() != null) {
                List<Appointment> appointments = response.body();

                // 添加调试日志
                Log.d("AppointmentDebug", "获取到 " + appointments.size() + " 条预约记录");
                for (Appointment appointment : appointments) {
                    Log.d("AppointmentDebug",
                            "ID: " + appointment.getId() +
                                    ", CounselorName: " + appointment.getCounselorName() +
                                    ", CounselorId: " + appointment.getCounselorId() +
                                    ", Type: " + appointment.getConsultationType() +
                                    ", Time: " + appointment.getScheduledTime());
                }

                // 打印完整的JSON响应用于调试
                String jsonResponse = new Gson().toJson(appointments);
                Log.d("AppointmentDebug", "完整响应: " + jsonResponse);

                appointmentList.clear();
                appointmentList.addAll(appointments);
                adapter.notifyDataSetChanged();

                if (appointments.isEmpty()) {
                    Toast.makeText(MyAppointmentsActivity.this, "暂无预约记录", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(MyAppointmentsActivity.this, "加载失败: " + response.code(), Toast.LENGTH_SHORT).show();
                Log.e("AppointmentError", "响应码: " + response.code());
                if (response.errorBody() != null) {
                    try {
                        String errorBody = response.errorBody().string();
                        Log.e("AppointmentError", "错误信息: " + errorBody);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        @Override
        public void onFailure(Call<List<Appointment>> call, Throwable t) {
            progressBar.setVisibility(ProgressBar.GONE);
            Toast.makeText(MyAppointmentsActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e("AppointmentError", "网络请求失败", t);
        }
    });
}

private Long getCurrentUserId() {
    return getSharedPreferences("user_prefs", MODE_PRIVATE).getLong("user_id", -1);
}

@Override
public boolean onSupportNavigateUp() {
    finish();
    return true;
}

}
package com.example.psychological.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.example.psychological.R;
import com.example.psychological.api.RetrofitClient;
import com.example.psychological.model.ConsultationRequest;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class QuickConsultationActivity extends AppCompatActivity {

private EditText etProblemDescription;
private Spinner spProblemDuration;
private CheckBox cbVoice, cbVideo, cbText;
private Button btnSubmit;
private ProgressBar progressBar;

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

    initViews();
    setupSpinner();
    setupSubmitButton();
}

private void initViews() {
    etProblemDescription = findViewById(R.id.et_problem_description);
    spProblemDuration = findViewById(R.id.sp_problem_duration);
    cbVoice = findViewById(R.id.cb_voice);
    cbVideo = findViewById(R.id.cb_video);
    cbText = findViewById(R.id.cb_text);
    btnSubmit = findViewById(R.id.btn_submit);
    progressBar = findViewById(R.id.progress_bar);

    // 设置返回按钮
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("快速咨询");
    }
}

private void setupSpinner() {
    String[] durations = {"请选择持续时间", "1个月以内", "1-3个月", "3-6个月", "6-12个月", "1年以上"};
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, durations);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spProblemDuration.setAdapter(adapter);
}

private void setupSubmitButton() {
    btnSubmit.setOnClickListener(v -> {
        if (validateInput()) {
            submitConsultationRequest();
        }
    });
}

private boolean validateInput() {
    String problemDescription = etProblemDescription.getText().toString().trim();
    String duration = spProblemDuration.getSelectedItem().toString();

    if (problemDescription.isEmpty()) {
        Toast.makeText(this, "请输入问题描述", Toast.LENGTH_SHORT).show();
        return false;
    }

    if (duration.equals("请选择持续时间")) {
        Toast.makeText(this, "请选择问题持续时间", Toast.LENGTH_SHORT).show();
        return false;
    }

    if (!cbVoice.isChecked() && !cbVideo.isChecked() && !cbText.isChecked()) {
        Toast.makeText(this, "请至少选择一种咨询方式", Toast.LENGTH_SHORT).show();
        return false;
    }

    return true;
}

private void submitConsultationRequest() {
    progressBar.setVisibility(ProgressBar.VISIBLE);
    btnSubmit.setEnabled(false);

    String problemDescription = etProblemDescription.getText().toString().trim();
    String duration = spProblemDuration.getSelectedItem().toString();

    ConsultationRequest request = new ConsultationRequest();
    request.setProblemDescription(problemDescription);
    request.setProblemDuration(duration);

    // 设置偏好的咨询方式
    java.util.ArrayList<String> methods = new java.util.ArrayList<>();
    if (cbVoice.isChecked()) methods.add("语音");
    if (cbVideo.isChecked()) methods.add("视频");
    if (cbText.isChecked()) methods.add("文字");
    request.setPreferredMethods(methods);



     // 使用示例:
    Long userId = getCurrentUserId();
    if (userId == -1) {
        // 未登录,跳转到登录页
        startActivity(new Intent(this, LoginActivity.class));
        return;
    }

    Call<ConsultationRequest> call = RetrofitClient.getApiService().createConsultationRequest(request, userId);
    call.enqueue(new Callback<ConsultationRequest>() {
        @Override
        public void onResponse(Call<ConsultationRequest> call, Response<ConsultationRequest> response) {
            progressBar.setVisibility(ProgressBar.GONE);
            btnSubmit.setEnabled(true);

            if (response.isSuccessful() && response.body() != null) {
                Toast.makeText(QuickConsultationActivity.this,
                        "咨询申请提交成功!系统将为您智能匹配咨询师,请关注消息通知",
                        Toast.LENGTH_LONG).show();

               // 可选:自动跳转到消息页面
                startActivity(new Intent(QuickConsultationActivity.this, MessagesActivity.class));
                finish();
            } else {
                Toast.makeText(QuickConsultationActivity.this, "提交失败: " + response.code(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ConsultationRequest> call, Throwable t) {
            progressBar.setVisibility(ProgressBar.GONE);
            btnSubmit.setEnabled(true);
            Toast.makeText(QuickConsultationActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

private Long getCurrentUserId() {
    SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
    return prefs.getLong("user_id", -1);
}

@Override
public boolean onSupportNavigateUp() {
    finish();
    return true;
}

}
package com.example.psychological.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.example.psychological.R;
import com.example.psychological.api.RetrofitClient;
import com.example.psychological.model.ConsultationRatingRequest;

import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RatingActivity extends AppCompatActivity {

private RatingBar ratingBar;
private EditText etReview;
private Button btnSubmit;
private ProgressBar progressBar;
private TextView tvRatingText;
private TextView tvCounselorName;

private Long appointmentId;
private String counselorName;

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

    // 获取传递的数据
    appointmentId = getIntent().getLongExtra("appointment_id", -1);
    counselorName = getIntent().getStringExtra("counselor_name");

    if (appointmentId == -1) {
        Toast.makeText(this, "预约信息错误", Toast.LENGTH_SHORT).show();
        finish();
        return;
    }

    initViews();
    setupToolbar();
    setupRatingBar();
}

private void initViews() {
    ratingBar = findViewById(R.id.rating_bar);
    etReview = findViewById(R.id.et_review);
    btnSubmit = findViewById(R.id.btn_submit);
    progressBar = findViewById(R.id.progress_bar);
    tvRatingText = findViewById(R.id.tv_rating_text);
    tvCounselorName = findViewById(R.id.tv_counselor_name);

    // 设置标题显示咨询师姓名
    tvCounselorName.setText("为 " + counselorName + " 咨询师评价");

    btnSubmit.setOnClickListener(v -> submitRating());
}

private void setupToolbar() {
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("咨询评价");
    }
}

private void setupRatingBar() {
    ratingBar.setOnRatingBarChangeListener((ratingBar, rating, fromUser) -> {
        String[] ratingTexts = {"请选择评分", "很不满意", "不满意", "一般", "满意", "非常满意"};
        int index = (int) rating;
        if (index >= 0 && index < ratingTexts.length) {
            tvRatingText.setText(ratingTexts[index]);
        }
    });
}

private void submitRating() {
    int rating = (int) ratingBar.getRating();
    String review = etReview.getText().toString().trim();

    if (rating == 0) {
        Toast.makeText(this, "请选择评分", Toast.LENGTH_SHORT).show();
        return;
    }

    progressBar.setVisibility(ProgressBar.VISIBLE);
    btnSubmit.setEnabled(false);

    // 获取当前用户ID
    Long userId = getCurrentUserId();
    if (userId == -1) {
        Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
        progressBar.setVisibility(ProgressBar.GONE);
        btnSubmit.setEnabled(true);

        // 跳转到登录页面
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
        return;
    }

    // 创建评价请求 - 使用正确的字段名
    ConsultationRatingRequest ratingRequest = new ConsultationRatingRequest();
    ratingRequest.setAppointmentId(appointmentId);
    ratingRequest.setUserRating(rating);  // 使用userRating
    ratingRequest.setUserReview(review);  // 使用userReview

    // 调用API
    Call<Map<String, Object>> call = RetrofitClient.getApiService().submitConsultationRating(ratingRequest, userId);
    call.enqueue(new Callback<Map<String, Object>>() {
        @Override
        public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
            progressBar.setVisibility(ProgressBar.GONE);
            btnSubmit.setEnabled(true);

            if (response.isSuccessful() && response.body() != null) {
                Map<String, Object> result = response.body();
                String status = (String) result.get("status");

                if ("success".equals(status)) {
                    Toast.makeText(RatingActivity.this, "评价提交成功", Toast.LENGTH_SHORT).show();

                    // 返回并刷新预约列表
                    setResult(RESULT_OK);
                    finish();
                } else {
                    String errorMessage = (String) result.get("message");
                    Toast.makeText(RatingActivity.this, errorMessage != null ? errorMessage : "评价提交失败", Toast.LENGTH_SHORT).show();
                }
            } else {
                String errorMessage = "评价提交失败";
                if (response.code() == 401) {
                    errorMessage = "用户未登录或认证失败";
                } else if (response.code() == 400) {
                    try {
                        String errorBody = response.errorBody().string();
                        // 解析错误信息
                        if (errorBody.contains("已完成评价")) {
                            errorMessage = "该预约已完成评价";
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                Toast.makeText(RatingActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<Map<String, Object>> call, Throwable t) {
            progressBar.setVisibility(ProgressBar.GONE);
            btnSubmit.setEnabled(true);
            Toast.makeText(RatingActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e("RatingError", "网络请求失败", t);
        }
    });
}

@Override
public boolean onSupportNavigateUp() {
    finish();
    return true;
}
private Long getCurrentUserId() {
    SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
    return prefs.getLong("user_id", -1);
}

}
package com.example.psychological.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.example.psychological.R;
import com.example.psychological.api.RetrofitClient;
import com.example.psychological.model.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterActivity extends AppCompatActivity {

private EditText etUsername, etPassword, etConfirmPassword, etEmail, etPhone, etAge;
private Spinner spGender;
private Button btnRegister;
private ProgressBar progressBar;

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

    initViews();
    setupSpinner();
    setupClickListeners();
}

private void initViews() {
    etUsername = findViewById(R.id.et_username);
    etPassword = findViewById(R.id.et_password);
    etConfirmPassword = findViewById(R.id.et_confirm_password);
    etEmail = findViewById(R.id.et_email);
    etPhone = findViewById(R.id.et_phone);
    etAge = findViewById(R.id.et_age);
    spGender = findViewById(R.id.sp_gender);
    btnRegister = findViewById(R.id.btn_register);
    progressBar = findViewById(R.id.progress_bar);
}

private void setupSpinner() {
    String[] genders = {"请选择性别", "男", "女"};
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
            android.R.layout.simple_spinner_item, genders);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spGender.setAdapter(adapter);
}

private void setupClickListeners() {
    btnRegister.setOnClickListener(v -> register());
}

private void register() {
    String username = etUsername.getText().toString().trim();
    String password = etPassword.getText().toString().trim();
    String confirmPassword = etConfirmPassword.getText().toString().trim();
    String email = etEmail.getText().toString().trim();
    String phone = etPhone.getText().toString().trim();
    String ageStr = etAge.getText().toString().trim();
    String selectedGender = spGender.getSelectedItem().toString();

    // 验证所有字段
    if (username.isEmpty()) {
        showError("请输入用户名");
        return;
    }

    if (password.isEmpty()) {
        showError("请输入密码");
        return;
    }

    if (!password.equals(confirmPassword)) {
        showError("密码不一致");
        return;
    }

    if (email.isEmpty()) {
        showError("请输入邮箱");
        return;
    }

    if (phone.isEmpty()) {
        showError("请输入手机号");
        return;
    }

    if (ageStr.isEmpty()) {
        showError("请输入年龄");
        return;
    }

    if (selectedGender.equals("请选择性别")) {
        showError("请选择性别");
        return;
    }

    int age;
    try {
        age = Integer.parseInt(ageStr);
        if (age < 1 || age > 120) {
            showError("请输入有效的年龄(1-120)");
            return;
        }
    } catch (NumberFormatException e) {
        showError("请输入有效的年龄");
        return;
    }

    // 转换性别为后端格式
    String gender = selectedGender.equals("男") ? "MALE" : "FEMALE";

    progressBar.setVisibility(ProgressBar.VISIBLE);
    btnRegister.setEnabled(false);

    User newUser = new User();
    newUser.setUsername(username);
    newUser.setPassword(password);
    newUser.setEmail(email);
    newUser.setPhone(phone);
    newUser.setGender(gender);
    newUser.setAge(age);

    Call<User> call = RetrofitClient.getApiService().registerUser(newUser);
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            progressBar.setVisibility(ProgressBar.GONE);
            btnRegister.setEnabled(true);

            if (response.isSuccessful() && response.body() != null) {
                User user = response.body();

                // 缓存用户信息
                SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putLong("user_id", user.getId());
                editor.putString("username", user.getUsername());
                if (user.getEmail() != null) editor.putString("email", user.getEmail());
                if (user.getPhone() != null) editor.putString("phone", user.getPhone());
                if (user.getGender() != null) editor.putString("gender", user.getGender());
                if (user.getAge() != null) editor.putInt("age", user.getAge());
                editor.apply();

                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                finish(); // 返回登录页面
            } else {
                String errorMsg = "注册失败";
                if (response.errorBody() != null) {
                    try {
                        String errorBody = response.errorBody().string();
                        if (errorBody.contains("用户名已存在")) {
                            errorMsg = "用户名已存在";
                        } else if (errorBody.contains("邮箱已存在")) {
                            errorMsg = "邮箱已存在";
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                Toast.makeText(RegisterActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            progressBar.setVisibility(ProgressBar.GONE);
            btnRegister.setEnabled(true);
            Toast.makeText(RegisterActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

private void showError(String message) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}

}
package com.example.psychological.activity;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.psychological.R;
import com.example.psychological.model.Video;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.PlaybackException;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import com.google.android.exoplayer2.util.MimeTypes;

public class VideoPlayerActivity extends AppCompatActivity {

private ExoPlayer player;
private StyledPlayerView playerView;
private ImageButton btnPlayPause, btnBack;
private Button btnSpeed;
private SeekBar seekBar;
private TextView tvCurrentTime, tvTotalTime, tvVideoTitle;
private float[] playbackSpeeds = {0.5f, 0.75f, 1.0f, 1.25f, 1.5f, 2.0f};
private int currentSpeedIndex = 2; // 默认1.0倍速

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 设置全屏或隐藏ActionBar
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_video_player);

    // 添加调试日志
    Log.d("VideoPlayerActivity", "Activity创建");

    Video video = (Video) getIntent().getSerializableExtra("video");
    if (video != null) {
        Log.d("VideoPlayerActivity", "接收到的视频: " + video.getTitle());
        Log.d("VideoPlayerActivity", "原始视频URL: " + video.getVideoUrl());
    } else {
        Log.e("VideoPlayerActivity", "未收到视频数据!");
    }

    initViews();
    setupPlayer();
    setupListeners();
}

private void initViews() {
    playerView = findViewById(R.id.player_view);
    btnPlayPause = findViewById(R.id.btn_play_pause);
    btnSpeed = findViewById(R.id.btn_speed);
    btnBack = findViewById(R.id.btn_back);
    seekBar = findViewById(R.id.seek_bar);
    tvCurrentTime = findViewById(R.id.tv_current_time);
    tvTotalTime = findViewById(R.id.tv_total_time);
    tvVideoTitle = findViewById(R.id.tv_video_title);

    // 获取传递的视频数据
    Video video = (Video) getIntent().getSerializableExtra("video");
    if (video != null) {
        tvVideoTitle.setText(video.getTitle());
    }
}

private void setupPlayer() {
    // 创建 ExoPlayer 实例
    player = new ExoPlayer.Builder(this).build();
    playerView.setPlayer(player);

    // 获取视频URL
    Video video = (Video) getIntent().getSerializableExtra("video");
    if (video != null && video.getVideoUrl() != null) {
        // ✅ 关键修复:将localhost替换为10.0.2.2
        String videoUrl = video.getVideoUrl();
        if (videoUrl.contains("localhost")) {
            videoUrl = videoUrl.replace("localhost", "10.0.2.2");
        }

        Log.d("VideoPlayerActivity", "播放视频URL: " + videoUrl);

        MediaItem mediaItem = MediaItem.fromUri(videoUrl);
        player.setMediaItem(mediaItem);
        player.prepare();

        // 先暂停,等待用户点击播放
        player.pause();

        // 更新播放按钮状态
        updatePlayButton();
    }

    // 监听播放状态
    player.addListener(new Player.Listener() {
        @Override
        public void onPlaybackStateChanged(int playbackState) {
            Log.d("VideoPlayerActivity", "播放状态: " + playbackState);

            if (playbackState == Player.STATE_READY) {
                Log.d("VideoPlayerActivity", "视频准备就绪,时长: " + player.getDuration());

                // 设置进度条最大值
                seekBar.setMax((int) player.getDuration());
                // 显示总时长
                tvTotalTime.setText(formatTime(player.getDuration()));
                updatePlayButton();
            } else if (playbackState == Player.STATE_ENDED) {
                btnPlayPause.setImageResource(R.drawable.ic_replay);
            } else if (playbackState == Player.STATE_BUFFERING) {
                Log.d("VideoPlayerActivity", "正在缓冲...");
            } else if (playbackState == Player.STATE_IDLE) {
                Log.d("VideoPlayerActivity", "播放器空闲");
            }
        }

        @Override
        public void onIsPlayingChanged(boolean isPlaying) {
            Log.d("VideoPlayerActivity", "播放状态改变: " + isPlaying);
            updatePlayButton();
        }

        @Override
        public void onPlayerError(PlaybackException error) {
            // 处理播放错误
            Log.e("VideoPlayerActivity", "播放错误: " + error.getMessage());
            error.printStackTrace();

            // 显示错误信息
            runOnUiThread(() -> {
                tvVideoTitle.setText("播放失败: " + error.getMessage());
            });
        }
    });
}

private void setupListeners() {
    // 播放/暂停按钮
    btnPlayPause.setOnClickListener(v -> {
        if (player.isPlaying()) {
            player.pause();
        } else {
            player.play();
        }
        updatePlayButton();
    });

    // 倍速按钮
    btnSpeed.setOnClickListener(v -> {
        currentSpeedIndex = (currentSpeedIndex + 1) % playbackSpeeds.length;
        float speed = playbackSpeeds[currentSpeedIndex];
        player.setPlaybackSpeed(speed);
        btnSpeed.setText(String.format("%.2fx", speed));
    });

    // 返回按钮
    btnBack.setOnClickListener(v -> finish());

    // 进度条监听 - 使用Handler代替Thread
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser && player != null) {
                player.seekTo(progress);
                tvCurrentTime.setText(formatTime(progress));
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {}

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {}
    });

    // ✅ 使用Handler定时更新进度条
    Handler handler = new Handler();
    Runnable updateProgressRunnable = new Runnable() {
        @Override
        public void run() {
            if (player != null && player.isPlaying()) {
                long position = player.getCurrentPosition();
                seekBar.setProgress((int) position);
                tvCurrentTime.setText(formatTime(position));
            }
            handler.postDelayed(this, 1000);
        }
    };

    handler.post(updateProgressRunnable);
}

private void updatePlayButton() {
    if (player.isPlaying()) {
        btnPlayPause.setImageResource(R.drawable.ic_pause);
    } else {
        btnPlayPause.setImageResource(R.drawable.ic_play);
    }
}

private String formatTime(long milliseconds) {
    int seconds = (int) (milliseconds / 1000);
    int minutes = seconds / 60;
    seconds = seconds % 60;
    return String.format("%02d:%02d", minutes, seconds);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (player != null) {
        player.release();
        player = null;
    }
}

}

posted @ 2026-01-08 22:55  ytr123  阅读(6)  评论(0)    收藏  举报