首页 > 解决方案 > 从 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 响应。请指导我该怎么办?

标签: phpandroidretrofit2

解决方案


您需要创建一个响应类。例如,服务响应。你的班级应该是这样的:

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>() {...}

使用该代码,您将能够在您的活动中显示您的响应。

因此,在简历中,您必须始终根据您的服务对您的响应来创建响应类。


推荐阅读