【发布时间】:2018-09-19 14:33:10
【问题描述】:
我正在尝试将数据显示到TextViews。我是 Retrofit 的新手,希望能提供任何帮助和提示。以下是我目前所拥有的。
API 客户端:
public class ApiClient {
public static final String BASE_URL = ("http://10.1.11.11/");
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
API 服务:
public interface ApiService {
@FormUrlEncoded
@GET("/lara/getprofile.php?id=")
Call<Profile> getMyProfile(@Query("id") String id);
}
getter 和 setter:
public class Profile {
@SerializedName("PID")
@Expose
private String pid;
@SerializedName("First_Name")
@Expose
private String fname;
@SerializedName("Last_Name")
@Expose
private String lname;
@SerializedName("Team_Lead")
@Expose
private String teamlead;
public Profile(String pid, String fname, String lname, String teamlead) {
this.pid = pid;
this.fname = fname;
this.lname = lname;
this.teamlead = teamlead;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getTeamlead() {
return teamlead;
}
public void setTeamlead(String teamlead) {
this.teamlead = teamlead;
}
}
在 TextView 中显示数据:
private void getProfile(final String id){
ApiService apiService = ApiClient.getClient().create(ApiService.class);
Call<Profile> call = apiService.getMyProfile(id);
call.enqueue(new Callback<Profile>() {
@Override
public void onResponse(Call<Profile> call, Response<Profile> response) {
progressDialog.dismiss();
Profile p = response.body();
pid.setText(p.getPid());
fname.setText(p.getFname());
lname.setText(p.getLname());
teamlead.setText(p.getTeamlead());
}
@Override
public void onFailure(Call<Profile> call, Throwable t) {
//progressDialog.dismiss();
Toast.makeText(ProfilePage.this, "Failed to load." + t, Toast.LENGTH_LONG).show();
}
});
}
我尝试向 TextViews 显示的 JSON 字段:
我收到以下错误消息:
【问题讨论】:
-
将 json 发布为代码而不是图像
-
您试图将 json 响应解析为对象,其中 json 响应包含一个数组(以
[]开头和结尾)。我认为你有两个选择。 1. 将您的 json 响应更改为对象(只需删除[])。 2. 改变你的解析器来解析 json 数组而不是对象。
标签: php android json android-studio retrofit2