心理咨询咨询师安卓端
package com.example.psychological_counselor.activity;
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_counselor.R;
import com.example.psychological_counselor.adapter.CounselorAppointmentAdapter;
import com.example.psychological_counselor.api.RetrofitClient;
import com.example.psychological_counselor.model.Appointment;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CounselorAppointmentActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private CounselorAppointmentAdapter adapter;
private List<Appointment> appointmentList;
private ProgressBar progressBar;
private Long counselorId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counselor_appointments);
initViews();
loadCounselorAppointments();
}
private void initViews() {
recyclerView = findViewById(R.id.recycler_view);
progressBar = findViewById(R.id.progress_bar);
// 获取咨询师ID
counselorId = getSharedPreferences("counselor_prefs", MODE_PRIVATE)
.getLong("counselor_id", -1);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("预约管理");
}
appointmentList = new ArrayList<>();
adapter = new CounselorAppointmentAdapter(appointmentList, this::onAppointmentAction);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
private void loadCounselorAppointments() {
if (counselorId == -1) {
Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
finish();
return;
}
progressBar.setVisibility(ProgressBar.VISIBLE);
Log.d("CounselorAppointment", "Loading appointments for counselor: " + counselorId);
Log.d("CounselorAppointment", "Using header: Counselor-Id=" + counselorId);
// 使用修改后的API调用
Call<List<Appointment>> call = RetrofitClient.getApiService().getCounselorAppointments(counselorId);
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) {
appointmentList.clear();
appointmentList.addAll(response.body());
adapter.notifyDataSetChanged();
Log.d("CounselorAppointment", "成功加载 " + appointmentList.size() + " 个预约");
if (appointmentList.isEmpty()) {
Toast.makeText(CounselorAppointmentActivity.this, "暂无预约", Toast.LENGTH_SHORT).show();
}
} else {
try {
String errorBody = response.errorBody() != null ? response.errorBody().string() : "No error body";
Log.e("CounselorAppointment", "Error response: " + response.code() + " - " + errorBody);
} catch (IOException e) {
Log.e("CounselorAppointment", "Error reading error body", e);
}
Toast.makeText(CounselorAppointmentActivity.this, "加载失败: " + response.code(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<List<Appointment>> call, Throwable t) {
progressBar.setVisibility(ProgressBar.GONE);
Toast.makeText(CounselorAppointmentActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("CounselorAppointment", "Network error: ", t);
}
});
}
// 处理预约操作(确认/拒绝/完成)
private void onAppointmentAction(Appointment appointment, String action) {
Call<Appointment> call;
switch (action) {
case "CONFIRMED":
call = RetrofitClient.getApiService().confirmAppointment(appointment.getId(), counselorId);
break;
case "REJECTED":
call = RetrofitClient.getApiService().rejectAppointment(appointment.getId(), counselorId);
break;
case "COMPLETED":
call = RetrofitClient.getApiService().completeAppointment(appointment.getId(), counselorId);
break;
default:
Toast.makeText(this, "无效操作", Toast.LENGTH_SHORT).show();
return;
}
call.enqueue(new Callback<Appointment>() {
@Override
public void onResponse(Call<Appointment> call, Response<Appointment> response) {
if (response.isSuccessful() && response.body() != null) {
String message = "";
switch (action) {
case "CONFIRMED":
message = "预约已确认";
break;
case "REJECTED":
message = "预约已拒绝";
break;
case "COMPLETED":
message = "预约已完成";
break;
}
Toast.makeText(CounselorAppointmentActivity.this, message, Toast.LENGTH_SHORT).show();
loadCounselorAppointments(); // 刷新列表
} else {
Toast.makeText(CounselorAppointmentActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
Log.e("AppointmentAction", "Response error: " + response.code());
}
}
@Override
public void onFailure(Call<Appointment> call, Throwable t) {
Toast.makeText(CounselorAppointmentActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
Log.e("AppointmentAction", "Network error: ", t);
}
});
}
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
package com.example.psychological_counselor.activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.psychological_counselor.R;
import com.example.psychological_counselor.adapter.ChatAdapter;
import com.example.psychological_counselor.api.RetrofitClient;
import com.example.psychological_counselor.model.Message;
import com.example.psychological_counselor.websocket.WebSocketClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CounselorChatActivity extends AppCompatActivity implements WebSocketClient.MessageListener {
private RecyclerView recyclerView;
private EditText etMessage;
private ImageButton btnSend;
private ChatAdapter adapter;
private List<Message> messageList;
private Long userId;
private String userName;
private Long counselorId;
private WebSocketClient webSocketClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat); // 使用相同的布局文件
initData();
initViews();
loadConversationHistory();
setupWebSocket();
}
private void initData() {
userId = getIntent().getLongExtra("user_id", -1);
userName = getIntent().getStringExtra("user_name");
counselorId = getSharedPreferences("counselor_prefs", MODE_PRIVATE).getLong("counselor_id", -1);
if (userId == -1 || counselorId == -1) {
Toast.makeText(this, "参数错误", Toast.LENGTH_SHORT).show();
finish();
return;
}
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(userName);
}
}
private void initViews() {
recyclerView = findViewById(R.id.recyclerView);
etMessage = findViewById(R.id.etMessage);
btnSend = findViewById(R.id.btnSend);
messageList = new ArrayList<>();
adapter = new ChatAdapter(messageList, counselorId);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
btnSend.setOnClickListener(v -> sendMessage());
}
private void setupWebSocket() {
webSocketClient = WebSocketClient.getInstance();
webSocketClient.setMessageListener(this);
webSocketClient.connect(counselorId.toString());
}
private void loadConversationHistory() {
Call<List<Message>> call = RetrofitClient.getApiService().getConversation(userId, counselorId);
call.enqueue(new Callback<List<Message>>() {
@Override
public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
if (response.isSuccessful() && response.body() != null) {
messageList.clear();
messageList.addAll(response.body());
adapter.notifyDataSetChanged();
if (!messageList.isEmpty()) {
recyclerView.scrollToPosition(messageList.size() - 1);
}
markAllAsRead();
}
}
@Override
public void onFailure(Call<List<Message>> call, Throwable t) {
Toast.makeText(CounselorChatActivity.this, "加载对话失败", Toast.LENGTH_SHORT).show();
}
});
}
private void sendMessage() {
String content = etMessage.getText().toString().trim();
Log.d("CounselorChat", "咨询师准备发送消息: " + content);
if (TextUtils.isEmpty(content)) {
return;
}
try {
JSONObject jsonMessage = new JSONObject();
jsonMessage.put("senderId", counselorId);
jsonMessage.put("receiverId", userId);
jsonMessage.put("content", content);
jsonMessage.put("messageType", "TEXT");
jsonMessage.put("senderName", "我"); // 咨询师自己发送的消息显示"我"
Log.d("CounselorChat", "咨询师调用sendMessage: " + jsonMessage.toString());
webSocketClient.sendMessage(jsonMessage.toString());
// 添加到列表
Message message = new Message();
message.setSenderId(counselorId);
message.setReceiverId(userId);
message.setContent(content);
message.setMessageType("TEXT");
message.setSenderName("我");
messageList.add(message);
adapter.notifyItemInserted(messageList.size() - 1);
recyclerView.scrollToPosition(messageList.size() - 1);
etMessage.setText("");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "发送失败", Toast.LENGTH_SHORT).show();
}
}
private void markAllAsRead() {
Call<Void> call = RetrofitClient.getApiService().markAllAsRead(userId, counselorId);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
// 标记成功
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
// 标记失败
}
});
}
@Override
public void onMessageReceived(String message) {
runOnUiThread(() -> {
try {
JSONObject json = new JSONObject(message);
Message chatMessage = new Message();
chatMessage.setId(json.has("id") ? json.getLong("id") : null);
chatMessage.setSenderId(json.getLong("senderId"));
chatMessage.setReceiverId(json.getLong("receiverId"));
chatMessage.setContent(json.getString("content"));
chatMessage.setMessageType(json.getString("messageType"));
chatMessage.setSenderName(json.has("senderName") ? json.getString("senderName") : userName);
if (chatMessage.getSenderId().equals(userId) ||
chatMessage.getReceiverId().equals(userId)) {
messageList.add(chatMessage);
adapter.notifyItemInserted(messageList.size() - 1);
recyclerView.scrollToPosition(messageList.size() - 1);
}
} catch (JSONException e) {
e.printStackTrace();
}
});
}
// 实现缺失的方法
@Override
public void onConnectionStatusChanged(boolean connected) {
runOnUiThread(() -> {
if (connected) {
Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "连接断开", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (webSocketClient != null) {
webSocketClient.disconnect();
}
}
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
package com.example.psychological_counselor.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_counselor.R;
import com.example.psychological_counselor.adapter.CounselorChatListAdapter;
import com.example.psychological_counselor.api.RetrofitClient;
import com.example.psychological_counselor.model.Message;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CounselorChatListActivity extends AppCompatActivity implements CounselorChatListAdapter.OnChatItemClickListener {
private RecyclerView recyclerView;
private CounselorChatListAdapter adapter;
private List<Message> conversationList; // 直接使用 Message 列表
private ProgressBar progressBar;
private Long counselorId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counselor_chat_list);
initViews();
loadCounselorId();
loadConversations();
}
private void initViews() {
recyclerView = findViewById(R.id.recyclerView);
progressBar = findViewById(R.id.progressBar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("在线咨询");
}
conversationList = new ArrayList<>();
adapter = new CounselorChatListAdapter(conversationList);
adapter.setOnChatItemClickListener(this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
private void loadCounselorId() {
counselorId = getSharedPreferences("counselor_prefs", MODE_PRIVATE).getLong("counselor_id", -1);
if (counselorId == -1) {
Toast.makeText(this, "请重新登录", Toast.LENGTH_SHORT).show();
finish();
}
}
private void loadConversations() {
progressBar.setVisibility(ProgressBar.VISIBLE);
// 获取咨询师收到的所有消息
Call<List<Message>> call = RetrofitClient.getApiService().getMyMessages(counselorId);
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) {
processMessages(response.body());
} else {
Toast.makeText(CounselorChatListActivity.this, "加载对话失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<List<Message>> call, Throwable t) {
progressBar.setVisibility(ProgressBar.GONE);
Toast.makeText(CounselorChatListActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void processMessages(List<Message> messages) {
// 按用户分组,只保留每个用户的最后一条消息作为对话项
Map<Long, Message> lastMessageMap = new HashMap<>();
for (Message message : messages) {
Long userId = message.getSenderId();
// 如果还没有这个用户的消息,或者这条消息时间更晚,就更新
if (!lastMessageMap.containsKey(userId)) {
lastMessageMap.put(userId, message);
} else {
// 这里可以添加时间比较逻辑,选择最新的消息
lastMessageMap.put(userId, message);
}
}
conversationList.clear();
conversationList.addAll(lastMessageMap.values());
adapter.notifyDataSetChanged();
if (conversationList.isEmpty()) {
Toast.makeText(this, "暂无对话", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onChatItemClick(Message message) {
// 点击对话项,进入聊天页面
Intent intent = new Intent(this, CounselorChatActivity.class);
intent.putExtra("user_id", message.getSenderId());
intent.putExtra("user_name", message.getSenderName());
startActivity(intent);
}
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
package com.example.psychological_counselor.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.psychological_counselor.R;
import com.example.psychological_counselor.api.RetrofitClient;
import com.example.psychological_counselor.model.Counselor;
import com.example.psychological_counselor.model.User;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CounselorLoginActivity extends AppCompatActivity {
private EditText etUsername, etPassword;
private Button btnLogin;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counselor_login);
initViews();
setupClickListeners();
checkAutoLogin();
}
private void initViews() {
etUsername = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_password);
btnLogin = findViewById(R.id.btn_login);
progressBar = findViewById(R.id.progress_bar);
}
private void setupClickListeners() {
btnLogin.setOnClickListener(v -> login());
}
private void checkAutoLogin() {
Long counselorId = getSharedPreferences("counselor_prefs", MODE_PRIVATE)
.getLong("counselor_id", -1);
if (counselorId != -1) {
startActivity(new Intent(this, CounselorMainActivity.class));
finish();
}
}
private void login() {
String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();
if (username.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(ProgressBar.VISIBLE);
btnLogin.setEnabled(false);
User loginUser = new User();
loginUser.setUsername(username);
loginUser.setPassword(password);
Log.d("CounselorLogin", "发送登录请求: " + username);
Call<User> call = RetrofitClient.getApiService().loginUser(loginUser);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful() && response.body() != null) {
User user = response.body();
Log.d("CounselorLogin", "用户登录成功: " + user.getUsername() + ", 用户ID: " + user.getId());
// 传递用户对象
getCounselorByUserId(user.getId(), user);
} else {
progressBar.setVisibility(ProgressBar.GONE);
btnLogin.setEnabled(true);
Toast.makeText(CounselorLoginActivity.this, "登录失败: " + response.code(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
progressBar.setVisibility(ProgressBar.GONE);
btnLogin.setEnabled(true);
Toast.makeText(CounselorLoginActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void getCounselorByUserId(Long userId, User user) { // 添加User参数
Log.d("CounselorLogin", "根据用户ID获取咨询师信息: " + userId);
Call<Counselor> call = RetrofitClient.getApiService().getCounselorByUserId(userId);
call.enqueue(new Callback<Counselor>() {
@Override
public void onResponse(Call<Counselor> call, Response<Counselor> response) {
progressBar.setVisibility(ProgressBar.GONE);
btnLogin.setEnabled(true);
if (response.isSuccessful() && response.body() != null) {
Counselor counselor = response.body();
Log.d("CounselorLogin", "获取到咨询师信息: " + counselor.getRealName() + ", ID: " + counselor.getId());
// 传递用户对象
saveCounselorInfo(counselor, user);
Toast.makeText(CounselorLoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
startActivity(new Intent(CounselorLoginActivity.this, CounselorMainActivity.class));
finish();
} else {
Toast.makeText(CounselorLoginActivity.this, "未找到咨询师信息", Toast.LENGTH_SHORT).show();
Log.e("CounselorLogin", "未找到咨询师信息,响应码: " + response.code());
}
}
@Override
public void onFailure(Call<Counselor> call, Throwable t) {
progressBar.setVisibility(ProgressBar.GONE);
btnLogin.setEnabled(true);
Toast.makeText(CounselorLoginActivity.this, "获取咨询师信息失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void saveCounselorInfo(Counselor counselor, User user) {
SharedPreferences prefs = getSharedPreferences("counselor_prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
// 保存咨询师专业信息
editor.putLong("counselor_id", counselor.getId());
editor.putString("real_name", counselor.getRealName());
editor.putInt("experience_years", counselor.getExperienceYears());
if (counselor.getPricePerHour() != null) {
editor.putFloat("price_per_hour", counselor.getPricePerHour().floatValue());
}
if (counselor.getRating() != null) {
editor.putFloat("rating", counselor.getRating().floatValue());
}
if (counselor.getIntroduction() != null) {
editor.putString("introduction", counselor.getIntroduction());
}
if (counselor.getAvatarUrl() != null) {
editor.putString("avatar_url", counselor.getAvatarUrl());
}
// 保存用户基本信息(重要!)
if (user != null) {
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());
if (user.getAvatarUrl() != null) editor.putString("user_avatar_url", user.getAvatarUrl());
}
editor.apply();
Log.d("CounselorLogin", "咨询师信息已缓存: " + counselor.getRealName() +
", 咨询师ID: " + counselor.getId());
if (user != null) {
Log.d("CounselorLogin", "用户信息已缓存: " + user.getUsername());
}
}
}
package com.example.psychological_counselor.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.example.psychological_counselor.R;
public class CounselorMainActivity extends AppCompatActivity {
private TextView tvWelcome;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counselor_main);
// 关键代码:设置Toolbar为ActionBar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initViews();
loadCounselorInfo();
}
private void initViews() {
tvWelcome = findViewById(R.id.tv_welcome);
}
private void loadCounselorInfo() {
String username = getSharedPreferences("counselor_prefs", MODE_PRIVATE)
.getString("username", "咨询师");
tvWelcome.setText("欢迎回来," + username + "!");
}
// 点击事件方法
public void onAppointmentClick(View view) {
startActivity(new Intent(this, CounselorAppointmentActivity.class));
}
public void onChatClick(View view) {
// 跳转到对话列表页面
startActivity(new Intent(this, CounselorChatListActivity.class));
}
public void onScheduleClick(View view) {
android.widget.Toast.makeText(this, "日程安排功能开发中", android.widget.Toast.LENGTH_SHORT).show();
}
public void onProfileClick(View view) {
// 跳转到个人资料页面
startActivity(new Intent(this, ProfileActivity.class));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_counselor_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_logout) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
// 清除登录信息
SharedPreferences prefs = getSharedPreferences("counselor_prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
// 显示退出提示
android.widget.Toast.makeText(this, "已退出登录", android.widget.Toast.LENGTH_SHORT).show();
// 跳转到登录页面并清除返回栈
Intent intent = new Intent(this, CounselorLoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
// 添加查看评价的点击事件
public void onRatingClick(View view) {
startActivity(new Intent(this, CounselorRatingActivity.class));
}
public void onRecordClick(View view) {
Intent intent = new Intent(this, StudentRecordActivity.class);
startActivity(intent);
}
public void onCreateRecordClick(View view) {
// 直接进入新建档案页面
Intent intent = new Intent(this, StudentRecordEditActivity.class);
startActivity(intent);
}
}
package com.example.psychological_counselor.activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.psychological_counselor.R;
import com.example.psychological_counselor.adapter.CounselorRatingAdapter;
import com.example.psychological_counselor.api.RetrofitClient;
import com.example.psychological_counselor.model.ConsultationRatingResponse;
import com.google.android.material.card.MaterialCardView;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CounselorRatingActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private CounselorRatingAdapter adapter;
private List<ConsultationRatingResponse> ratingList;
private ProgressBar progressBar;
private Long counselorId;
// 统计视图
private TextView tvTotalRatings, tvAverageRating;
private TextView tvFiveStar, tvFourStar, tvThreeStar, tvTwoStar, tvOneStar;
private MaterialCardView cardStatistics;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counselor_ratings);
initViews();
loadCounselorRatingStatistics();
loadCounselorRatings();
}
private void initViews() {
recyclerView = findViewById(R.id.recycler_view);
progressBar = findViewById(R.id.progress_bar);
cardStatistics = findViewById(R.id.card_statistics);
// 统计视图初始化
tvTotalRatings = findViewById(R.id.tv_total_ratings);
tvAverageRating = findViewById(R.id.tv_average_rating);
tvFiveStar = findViewById(R.id.tv_five_star);
tvFourStar = findViewById(R.id.tv_four_star);
tvThreeStar = findViewById(R.id.tv_three_star);
tvTwoStar = findViewById(R.id.tv_two_star);
tvOneStar = findViewById(R.id.tv_one_star);
// 获取咨询师ID
counselorId = getSharedPreferences("counselor_prefs", MODE_PRIVATE)
.getLong("counselor_id", -1);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("用户评价");
}
ratingList = new ArrayList<>();
adapter = new CounselorRatingAdapter(ratingList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
/**
* 加载评价统计
*/
private void loadCounselorRatingStatistics() {
if (counselorId == -1) {
cardStatistics.setVisibility(android.view.View.GONE);
return;
}
Call<Map<String, Object>> call = RetrofitClient.getApiService().getCounselorRatingStatistics(counselorId);
call.enqueue(new Callback<Map<String, Object>>() {
@Override
public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
if (response.isSuccessful() && response.body() != null) {
Map<String, Object> result = response.body();
String status = (String) result.get("status");
if ("success".equals(status)) {
Map<String, Object> data = (Map<String, Object>) result.get("data");
updateStatisticsUI(data);
}
}
}
@Override
public void onFailure(Call<Map<String, Object>> call, Throwable t) {
Log.e("CounselorRating", "加载统计失败", t);
}
});
}
/**
* 更新统计UI
*/
private void updateStatisticsUI(Map<String, Object> statistics) {
try {
Integer total = (Integer) statistics.get("totalRatings");
Double average = (Double) statistics.get("averageRating");
tvTotalRatings.setText("总评价数: " + (total != null ? total : 0));
tvAverageRating.setText("平均评分: " + (average != null ? String.format("%.1f", average) : "0.0"));
// 更新星级分布
if (statistics.containsKey("fiveStarCount")) {
Integer fiveStar = (Integer) statistics.get("fiveStarCount");
Integer fourStar = (Integer) statistics.get("fourStarCount");
Integer threeStar = (Integer) statistics.get("threeStarCount");
Integer twoStar = (Integer) statistics.get("twoStarCount");
Integer oneStar = (Integer) statistics.get("oneStarCount");
tvFiveStar.setText("五星: " + (fiveStar != null ? fiveStar : 0));
tvFourStar.setText("四星: " + (fourStar != null ? fourStar : 0));
tvThreeStar.setText("三星: " + (threeStar != null ? threeStar : 0));
tvTwoStar.setText("二星: " + (twoStar != null ? twoStar : 0));
tvOneStar.setText("一星: " + (oneStar != null ? oneStar : 0));
}
} catch (Exception e) {
Log.e("CounselorRating", "更新统计UI失败", e);
}
}
/**
* 加载评价列表
*/
private void loadCounselorRatings() {
if (counselorId == -1) {
Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
finish();
return;
}
progressBar.setVisibility(android.view.View.VISIBLE);
Call<Map<String, Object>> call = RetrofitClient.getApiService().getCounselorRatings(counselorId);
call.enqueue(new Callback<Map<String, Object>>() {
@Override
public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
progressBar.setVisibility(android.view.View.GONE);
if (response.isSuccessful() && response.body() != null) {
Map<String, Object> result = response.body();
String status = (String) result.get("status");
if ("success".equals(status)) {
List<Map<String, Object>> data = (List<Map<String, Object>>) result.get("data");
ratingList.clear();
if (data != null) {
for (Map<String, Object> item : data) {
ConsultationRatingResponse rating = new ConsultationRatingResponse();
rating.setId(((Number) item.get("id")).longValue());
rating.setAppointmentId(((Number) item.get("appointmentId")).longValue());
rating.setRating(((Number) item.get("rating")).intValue());
rating.setReview((String) item.get("review"));
rating.setCreatedAt((String) item.get("createdAt"));
ratingList.add(rating);
}
}
adapter.notifyDataSetChanged();
if (ratingList.isEmpty()) {
Toast.makeText(CounselorRatingActivity.this, "暂无评价", Toast.LENGTH_SHORT).show();
}
} else {
String errorMessage = (String) result.get("message");
Toast.makeText(CounselorRatingActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(CounselorRatingActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Map<String, Object>> call, Throwable t) {
progressBar.setVisibility(android.view.View.GONE);
Toast.makeText(CounselorRatingActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
Log.e("CounselorRating", "加载评价失败", t);
}
});
}
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
package com.example.psychological_counselor.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.psychological_counselor.R;
public class ProfileActivity extends AppCompatActivity {
private TextView tvUsername, tvEmail, tvPhone, tvGender, tvAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
initViews();
loadProfileData();
}
private void initViews() {
tvUsername = findViewById(R.id.tv_username);
tvEmail = findViewById(R.id.tv_email);
tvPhone = findViewById(R.id.tv_phone);
tvGender = findViewById(R.id.tv_gender);
tvAge = findViewById(R.id.tv_age);
}
private void loadProfileData() {
SharedPreferences prefs = getSharedPreferences("counselor_prefs", MODE_PRIVATE);
// 优先显示咨询师真实姓名,如果没有则显示用户名
String realName = prefs.getString("real_name", null);
if (realName != null && !realName.isEmpty()) {
tvUsername.setText(realName);
} else {
tvUsername.setText(prefs.getString("username", "未知用户"));
}
tvEmail.setText(prefs.getString("email", "未设置"));
tvPhone.setText(prefs.getString("phone", "未设置"));
// 处理性别显示
String gender = prefs.getString("gender", "未设置");
if ("MALE".equals(gender)) {
tvGender.setText("男");
} else if ("FEMALE".equals(gender)) {
tvGender.setText("女");
} else if ("OTHER".equals(gender)) {
tvGender.setText("其他");
} else {
tvGender.setText("未设置");
}
int age = prefs.getInt("age", 0);
tvAge.setText(age > 0 ? String.valueOf(age) : "未设置");
// 可以添加显示咨询师专业信息
int experienceYears = prefs.getInt("experience_years", 0);
if (experienceYears > 0) {
// 可以在界面上添加显示从业年限的TextView
// tvExperience.setText("从业" + experienceYears + "年");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_profile, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_logout) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
// 清除登录信息
SharedPreferences prefs = getSharedPreferences("counselor_prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
android.widget.Toast.makeText(this, "已退出登录", android.widget.Toast.LENGTH_SHORT).show();
// 跳转到登录页面并清除返回栈
Intent intent = new Intent(this, CounselorLoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
package com.example.psychological_counselor.activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.psychological_counselor.R;
import com.example.psychological_counselor.adapter.StudentRecordAdapter;
import com.example.psychological_counselor.api.ApiService;
import com.example.psychological_counselor.model.StudentRecord;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import java.util.List;
public class StudentRecordActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private StudentRecordAdapter adapter;
private FloatingActionButton fabAdd;
private ApiService apiService;
private Long counselorId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_record);
initViews();
loadRecords();
}
private void initViews() {
// 设置ActionBar
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("电子档案管理");
recyclerView = findViewById(R.id.recyclerView);
fabAdd = findViewById(R.id.fabAdd);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new StudentRecordAdapter(record -> {
Intent intent = new Intent(StudentRecordActivity.this,
StudentRecordDetailActivity.class);
intent.putExtra("record_id", record.getId());
startActivity(intent);
});
recyclerView.setAdapter(adapter);
fabAdd.setOnClickListener(v -> {
Intent intent = new Intent(StudentRecordActivity.this,
StudentRecordEditActivity.class);
startActivity(intent);
});
// 获取咨询师ID(实际项目中应从登录信息获取)
counselorId = getSharedPreferences("counselor_prefs", MODE_PRIVATE)
.getLong("counselor_id", -1L); // 修改为 -1,这样没有登录就会失败
apiService = ApiService.getInstance();
}
private void loadRecords() {
apiService.getStudentRecords(counselorId).enqueue(new Callback<List<StudentRecord>>() {
@Override
public void onResponse(Call<List<StudentRecord>> call,
Response<List<StudentRecord>> response) {
if (response.isSuccessful() && response.body() != null) {
adapter.setRecords(response.body());
}
}
@Override
public void onFailure(Call<List<StudentRecord>> call, Throwable t) {
t.printStackTrace();
}
});
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
package com.example.psychological_counselor.activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.example.psychological_counselor.R;
import com.example.psychological_counselor.api.ApiService;
import com.example.psychological_counselor.model.StudentRecord;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.textview.MaterialTextView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class StudentRecordDetailActivity extends AppCompatActivity {
private MaterialTextView tvName, tvAge, tvGrade, tvSchool;
private MaterialTextView tvParentContact, tvRealSituation;
private MaterialTextView tvInterpersonalRelations, tvLearningSituation;
private MaterialTextView tvCounselorNotes, tvCreateDate;
private MaterialButton btnEdit, btnDelete;
private MaterialCardView cardRealSituation, cardInterpersonal, cardLearning;
private ApiService apiService;
private Long recordId;
private StudentRecord currentRecord;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_record_detail);
initViews();
loadRecordDetail();
}
private void initViews() {
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("档案详情");
// 基本信息
tvName = findViewById(R.id.tvName);
tvAge = findViewById(R.id.tvAge);
tvGrade = findViewById(R.id.tvGrade);
tvSchool = findViewById(R.id.tvSchool);
tvParentContact = findViewById(R.id.tvParentContact);
tvCreateDate = findViewById(R.id.tvCreateDate);
// 三个档案部分
tvRealSituation = findViewById(R.id.tvRealSituation);
tvInterpersonalRelations = findViewById(R.id.tvInterpersonalRelations);
tvLearningSituation = findViewById(R.id.tvLearningSituation);
tvCounselorNotes = findViewById(R.id.tvCounselorNotes);
// 卡片容器
cardRealSituation = findViewById(R.id.cardRealSituation);
cardInterpersonal = findViewById(R.id.cardInterpersonal);
cardLearning = findViewById(R.id.cardLearning);
// 按钮
btnEdit = findViewById(R.id.btnEdit);
btnDelete = findViewById(R.id.btnDelete);
apiService = ApiService.getInstance();
recordId = getIntent().getLongExtra("record_id", -1);
btnEdit.setOnClickListener(v -> {
if (currentRecord != null) {
Intent intent = new Intent(this, StudentRecordEditActivity.class);
intent.putExtra("record_id", currentRecord.getId());
startActivity(intent);
}
});
btnDelete.setOnClickListener(v -> {
if (currentRecord != null) {
deleteRecord();
}
});
}
private void loadRecordDetail() {
if (recordId == -1) {
finish();
return;
}
apiService.getStudentRecordById(recordId).enqueue(new Callback<StudentRecord>() {
@Override
public void onResponse(Call<StudentRecord> call, Response<StudentRecord> response) {
if (response.isSuccessful() && response.body() != null) {
currentRecord = response.body();
populateData();
}
}
@Override
public void onFailure(Call<StudentRecord> call, Throwable t) {
t.printStackTrace();
}
});
}
private void populateData() {
if (currentRecord == null) return;
tvName.setText(currentRecord.getStudentName());
tvAge.setText(String.valueOf(currentRecord.getAge()));
tvGrade.setText(currentRecord.getGrade());
tvSchool.setText(currentRecord.getSchool());
tvParentContact.setText(currentRecord.getParentContact());
tvCreateDate.setText(currentRecord.getFormattedDate());
// 处理三个主要部分
if (currentRecord.getRealSituation() != null &&
!currentRecord.getRealSituation().isEmpty()) {
tvRealSituation.setText(currentRecord.getRealSituation());
cardRealSituation.setVisibility(android.view.View.VISIBLE);
} else {
cardRealSituation.setVisibility(android.view.View.GONE);
}
if (currentRecord.getInterpersonalRelations() != null &&
!currentRecord.getInterpersonalRelations().isEmpty()) {
tvInterpersonalRelations.setText(currentRecord.getInterpersonalRelations());
cardInterpersonal.setVisibility(android.view.View.VISIBLE);
} else {
cardInterpersonal.setVisibility(android.view.View.GONE);
}
if (currentRecord.getLearningSituation() != null &&
!currentRecord.getLearningSituation().isEmpty()) {
tvLearningSituation.setText(currentRecord.getLearningSituation());
cardLearning.setVisibility(android.view.View.VISIBLE);
} else {
cardLearning.setVisibility(android.view.View.GONE);
}
if (currentRecord.getCounselorNotes() != null &&
!currentRecord.getCounselorNotes().isEmpty()) {
tvCounselorNotes.setText(currentRecord.getCounselorNotes());
} else {
tvCounselorNotes.setText("暂无备注");
}
}
private void deleteRecord() {
new android.app.AlertDialog.Builder(this)
.setTitle("确认删除")
.setMessage("确定要删除此档案吗?此操作不可撤销。")
.setPositiveButton("删除", (dialog, which) -> {
apiService.deleteStudentRecord(recordId).enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
if (response.isSuccessful()) {
setResult(RESULT_OK);
finish();
}
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
t.printStackTrace();
}
});
})
.setNegativeButton("取消", null)
.show();
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
package com.example.psychological_counselor.activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.example.psychological_counselor.R;
import com.example.psychological_counselor.api.ApiService;
import com.example.psychological_counselor.dto.StudentRecordRequest;
import com.example.psychological_counselor.model.StudentRecord;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class StudentRecordEditActivity extends AppCompatActivity {
private TextInputEditText etStudentName, etAge, etGrade, etSchool;
private TextInputEditText etParentContact, etRealSituation;
private TextInputEditText etInterpersonalRelations, etLearningSituation;
private TextInputEditText etCounselorNotes;
private MaterialButton btnSave;
private ApiService apiService;
private Long counselorId;
private Long recordId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_record_edit);
initViews();
loadRecordIfEditing();
}
private void initViews() {
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
// 先检查 toolbar 是否找到
if (toolbar != null) {
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
etStudentName = findViewById(R.id.etStudentName);
etAge = findViewById(R.id.etAge);
etGrade = findViewById(R.id.etGrade);
etSchool = findViewById(R.id.etSchool);
etParentContact = findViewById(R.id.etParentContact);
etRealSituation = findViewById(R.id.etRealSituation);
etInterpersonalRelations = findViewById(R.id.etInterpersonalRelations);
etLearningSituation = findViewById(R.id.etLearningSituation);
etCounselorNotes = findViewById(R.id.etCounselorNotes);
btnSave = findViewById(R.id.btnSave);
// 修改这里 ↓↓↓
SharedPreferences prefs = getSharedPreferences("counselor_prefs", MODE_PRIVATE);
counselorId = prefs.getLong("counselor_id", -1L);
if (counselorId == -1L) {
// 如果没找到,使用默认值
counselorId = 1L;
// 可选:提示用户
// Toast.makeText(this, "使用测试ID: 1", Toast.LENGTH_SHORT).show();
}
apiService = ApiService.getInstance();
recordId = getIntent().getLongExtra("record_id", -1);
// 设置标题
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(recordId == -1 ? "新建档案" : "编辑档案");
}
btnSave.setOnClickListener(v -> saveRecord());
}
private void loadRecordIfEditing() {
if (recordId != -1) {
apiService.getStudentRecordById(recordId).enqueue(new Callback<StudentRecord>() {
@Override
public void onResponse(Call<StudentRecord> call, Response<StudentRecord> response) {
if (response.isSuccessful() && response.body() != null) {
StudentRecord record = response.body();
populateForm(record);
}
}
@Override
public void onFailure(Call<StudentRecord> call, Throwable t) {
t.printStackTrace();
}
});
}
}
private void populateForm(StudentRecord record) {
etStudentName.setText(record.getStudentName());
etAge.setText(String.valueOf(record.getAge()));
etGrade.setText(record.getGrade());
etSchool.setText(record.getSchool());
etParentContact.setText(record.getParentContact());
etRealSituation.setText(record.getRealSituation());
etInterpersonalRelations.setText(record.getInterpersonalRelations());
etLearningSituation.setText(record.getLearningSituation());
etCounselorNotes.setText(record.getCounselorNotes());
}
private void saveRecord() {
StudentRecordRequest request = new StudentRecordRequest();
request.setStudentName(etStudentName.getText().toString());
// 处理年龄为空的情况
String ageText = etAge.getText().toString();
if (!ageText.isEmpty()) {
try {
request.setAge(Integer.parseInt(ageText));
} catch (NumberFormatException e) {
request.setAge(null);
}
} else {
request.setAge(null);
}
request.setGrade(etGrade.getText().toString());
request.setSchool(etSchool.getText().toString());
request.setParentContact(etParentContact.getText().toString());
request.setRealSituation(etRealSituation.getText().toString());
request.setInterpersonalRelations(etInterpersonalRelations.getText().toString());
request.setLearningSituation(etLearningSituation.getText().toString());
request.setCounselorNotes(etCounselorNotes.getText().toString());
if (recordId == -1) {
// 新建
apiService.createStudentRecord(counselorId, request).enqueue(new Callback<StudentRecord>() {
@Override
public void onResponse(Call<StudentRecord> call, Response<StudentRecord> response) {
if (response.isSuccessful()) {
finish();
}
}
@Override
public void onFailure(Call<StudentRecord> call, Throwable t) {
t.printStackTrace();
}
});
} else {
// 编辑
apiService.updateStudentRecord(recordId, request).enqueue(new Callback<StudentRecord>() {
@Override
public void onResponse(Call<StudentRecord> call, Response<StudentRecord> response) {
if (response.isSuccessful()) {
finish();
}
}
@Override
public void onFailure(Call<StudentRecord> call, Throwable t) {
t.printStackTrace();
}
});
}
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}

浙公网安备 33010602011771号