问题
I need to get the details from the API and display them in textviews.
Here's my API in JSON format : https://imgur.com/a/WI98ymx
I need to get the data like username, user image, user phone number etc in Strings and display them in textviews. How do i request all the fields and show the list in different textviews?
Here's my Login interface
package com.example.hb.loginapi;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
interface Login {
@POST("user_login_v1")
Call<ResObj> loginInfo(@Query("password") String password,
@Query("email") String email);
@GET("user_login_v1")
Call<List> getUserDetails();
}
Here's my ResObj class
package com.example.hb.loginapi;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class ResObj {
@SerializedName("settings")
private Settings settings;
@SerializedName("data")
private List<DataItem> data;
public void setSettings(Settings settings){
this.settings = settings;
}
public Settings getSettings(){
return settings;
}
public void setData(List<DataItem> data){
this.data = data;
}
public List<DataItem> getData(){
return data;
}
public class Settings {
@SerializedName("success")
private String success;
@SerializedName("message")
private String message;
@SerializedName("fields")
private List<String> fields;
public void setSuccess(String success) {
this.success = success;
}
public String getSuccess() {
return success;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
public List<String> getFields() {
return fields;
}
}
public class DataItem{
@SerializedName("user_name")
private String userName;
@SerializedName("search_report_count")
private String searchReportCount;
@SerializedName("access_token")
private String accessToken;
@SerializedName("profile_image")
private String profileImage;
@SerializedName("is_social")
private String isSocial;
@SerializedName("is_notification_enabled")
private String isNotificationEnabled;
@SerializedName("user_id")
private String userId;
@SerializedName("phone")
private String phone;
@SerializedName("plate_number")
private String plateNumber;
@SerializedName("state_id")
private String stateId;
@SerializedName("state")
private String state;
@SerializedName("email")
private String email;
@SerializedName("status")
private String status;
public void setUserName(String userName){
this.userName = userName;
}
public String getUserName(){
return userName;
}
public void setSearchReportCount(String searchReportCount){
this.searchReportCount = searchReportCount;
}
public String getSearchReportCount(){
return searchReportCount;
}
public void setAccessToken(String accessToken){
this.accessToken = accessToken;
}
public String getAccessToken(){
return accessToken;
}
public void setProfileImage(String profileImage){
this.profileImage = profileImage;
}
public String getProfileImage(){
return profileImage;
}
public void setIsSocial(String isSocial){
this.isSocial = isSocial;
}
public String getIsSocial(){
return isSocial;
}
public void setIsNotificationEnabled(String isNotificationEnabled){
this.isNotificationEnabled = isNotificationEnabled;
}
public String getIsNotificationEnabled(){
return isNotificationEnabled;
}
public void setUserId(String userId){
this.userId = userId;
}
public String getUserId(){
return userId;
}
public void setPhone(String phone){
this.phone = phone;
}
public String getPhone(){
return phone;
}
public void setPlateNumber(String plateNumber){
this.plateNumber = plateNumber;
}
public String getPlateNumber(){
return plateNumber;
}
public void setStateId(String stateId){
this.stateId = stateId;
}
public String getStateId(){
return stateId;
}
public void setState(String state){
this.state = state;
}
public String getState(){
return state;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return email;
}
public void setStatus(String status){
this.status = status;
}
public String getStatus(){
return status;
}
}
}
My Layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="#e9edf6"
android:scrollbars="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="@+id/userProfilePic"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:layout_width="150dp"
android:layout_height="150dp"
/>
<TextView
android:id="@+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/fnavyblue"
android:textSize="20sp"
android:text="DummyNameText"
android:layout_marginTop="50dp"
/>
<TextView
android:id="@+id/userID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/fnavyblue"
android:textSize="20sp"
android:text="DummyUserIDText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="@+id/emailID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/fnavyblue"
android:textSize="20sp"
android:text="DummyEmailText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="@+id/userStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/fnavyblue"
android:textSize="20sp"
android:text="DummyStatusText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="@+id/userPlateNum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/fnavyblue"
android:textSize="20sp"
android:text="DummyPlateNumText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="@+id/userStateName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/fnavyblue"
android:textSize="20sp"
android:text="DummyStateNameText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="@+id/userStateID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/fnavyblue"
android:textSize="20sp"
android:text="DummyStateIDText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="@+id/userSearchReportCount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/fnavyblue"
android:textSize="20sp"
android:text="DummySearchReportCountText"
android:layout_marginTop="20dp"
/>
</LinearLayout>
</ScrollView>
My MainActivity.java
public class MainActivity extends AppCompatActivity {
List emList=new ArrayList();
List dataList=new ArrayList();
List userDets=new ArrayList();
ImageView proImg;
TextView userName;
TextView userID;
TextView userEmail;
TextView userStatus;
TextView userPlateNum;
TextView userStateName;
TextView userStateID;
TextView userSearchReportCount;
String img;
String name;
String idUser;
String emailID;
String status;
String plateNum;
String stateName;
String stateID;
String searchReportCount;
String email;
Login login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emList.add(email);
userName=findViewById(R.id.userName);
email=getIntent().getStringExtra("email");
login=ApiUtils.getLoginClass();
getUserData();
}
private void getUserData(){
Call<List> call=login.getUserDetails();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if(response.isSuccessful()){
List resObj=(List)response.body();
for(int i=0;i<resObj.size();i++){
Log.e("data",resObj.get(i).toString());
}
}
}
@Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
I don't know what to write in the onResponse() method.
回答1:
change the for loop.
List<DataItem> items = resObj.getData();
for(int i=0;i<items.size();i++){
Log.e("data",items.get(i).getUserName()); // like this you can access other values in the items list
}
回答2:
Update api interface method
@GET("user_login_v1")
Call<ResObj> getUserDetails();
Update your getUserData() method
private void getUserData(){
Call<ResObj> call=login.getUserDetails();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if(response.isSuccessful()){
ResObj resObj=(ResObj)response.body();
DataItem user=reObj.getData().get(0);
//set value on yout text views
userName.setText(user.getUserName())
userID.setText(user.getUserId())
//....
}
}
@Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
回答3:
Create ResObj.class using Android studio plugin "GsonFormat" It will create a perfect POJO class for your APICall, just past the API GET response from Postman. It will create a suitable POJO class, from which you can simply call
private void callApi() {
Log.e(TAG, "callApi: inside apiCall");
Call<List> call =
login.getUserDetails();
call.enqueue(new Callback<List>() {
@Override
public void onResponse(Call<List> call, @NonNull Response<List>response) {
List items = response.body();
items = list.data;
String user_id = items.getUserID();
}
@Override
public void onFailure(Call<LiveMatches> call, Throwable t) {
}
call callApi() method where you want to get data; This method and method will not work if you copy and paste it you need to alter it according to your POJO class but this will provide help Also add your layout and activity code to give us context
来源:https://stackoverflow.com/questions/56320880/get-data-from-api-using-retrofit