php - 从 php 文件中获取并显示 api 响应,并使用 java 中的改造显示在 android 活动中
问题描述
我想显示我从 PHP 代码中得到的响应。我的 PHP 代码是:
if ($query) {
$response['message'] = "Saved";
$response['error'] = false;
} else {
$response['message'] = "Not Saved";
$response['error'] = true;
}
echo json_encode($response);
我想在活动中显示消息和错误
我的Java代码是:
Call<String> call = updateInterface.updateData(getId, studentData[0], studentData[1], studentData[2]);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
editPrg.dismiss();
Toast.makeText(getApplicationContext(), "Record updated", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<String> call, Throwable throwable) {
//hide dialog
editPrg.dismiss();
Toast.makeText(getApplicationContext(), "Error updating record", Toast.LENGTH_LONG).show();
}
});
我想在 onResponse() 方法中显示 PHP 响应。请指导我该怎么办?
解决方案
您需要创建一个响应类。例如,服务响应。你的班级应该是这样的:
class ServiceResponse{
private String message;
private Boolean error;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Boolean getError() {
return error;
}
public void setError(Boolean error) {
this.error = error;
}
}
然后,您的 Retrofit 调用应该是这样的:
Call<ServiceResponse> call = updateInterface.updateData(getId, studentData[0], studentData[1], studentData[2]);
call.enqueue(new Callback<ServiceResponse>() {...}
使用该代码,您将能够在您的活动中显示您的响应。
因此,在简历中,您必须始终根据您的服务对您的响应来创建响应类。
推荐阅读
- c++ - c++ clr 中的 windows.h 使用 Visual Studio 2019 形成应用程序
- c# - 如何使用 C# 根据批量大小拆分 Excel 工作表?
- command-line - 复制到终端 org.kde.konsole 时出现额外的空行
- java - Ambari Web 构建失败并出现错误:无法执行目标 com.github.eirslett:frontend-maven-plugin:1.4:install-node-and-yarn
- android - 来自片段中变量的数据绑定,android?
- python - 使用 BS4 循环提取 HTML 数据
- c++ - C++ 程序什么都不做,但 Valgrind 显示内存分配
- python - Python string.split() 如何忽略空格
- angular - Angular - 在基本的 HTTP POST 请求和承诺中,可观察对象对我有好处吗?
- c++ - 我可以参考模板的基类吗?