Метод enqueue onResponse возвращает пустой response.body () в модификации Android - PullRequest
0 голосов
/ 17 декабря 2018

когда я вызываю один из моих API, метод onRespone возвращает нулевой response.body ().Я следовал этому пути много раз и раньше, и это работает, но в этой ситуации не работает.также этот API работает в браузере.

Я проверил все: теги SerializedName, реализующие все классы из Serializable, метод API, который я использую, ....Я тоже пытался использовать синхронные звонки, но это не работает.

обратите внимание, как я получаю значение response.body () от обратного вызова: я объявляю переменную как поле класса активности и присваиваю ей response.body ().

I'mдействительно смущен.любая идея ??

это все коды, которые вам нужны:

Активность:

package com.example.amirmasoud.mgtools_2.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.example.amirmasoud.mgtools_2.GetDataService;
import com.example.amirmasoud.mgtools_2.R;
import com.example.amirmasoud.mgtools_2.RetrofitInstance;
import com.example.amirmasoud.mgtools_2.model.ToolsItem;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ToolContentActivity extends AppCompatActivity {

    private GetDataService service = RetrofitInstance.getRetrofitInstance().create(GetDataService.class);
    private ToolsItem toolItem = new ToolsItem();
    private int toolsItemId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tool_content);

        Bundle bundle = new Bundle(getIntent().getExtras());
        toolsItemId = bundle.getInt("toolItemId");

        service.getToolItemContent(toolsItemId).enqueue(new Callback<ToolsItem>() {
            @Override
            public void onResponse(Call<ToolsItem> call, Response<ToolsItem> response) {
                toolItem.mConstructor(response.body());
            }

            @Override
            public void onFailure(Call<ToolsItem> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }
}

Модель:

package com.example.amirmasoud.mgtools_2.model;

import com.google.gson.annotations.SerializedName;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by AmirMasoud on 12/9/2018.
 */

public class ToolsItem implements Serializable {

    @SerializedName("MainTypeID")
    private int mainTypeID = 0;

    @SerializedName("Name")
    private String persianName = "";

    @SerializedName("ImageURL")
    private String imageURL = "";

    @SerializedName("EnglishName")
    private String englishName = "";

    @SerializedName("OtherName")
    private String otherName = "";

    @SerializedName("CountryID")
    private int countryID = 0;

    @SerializedName("Year")
    private int year = 0;

    @SerializedName("ComplexityName")
    private String complexityName = "";

    @SerializedName("RelatedMainTypeID")
    private List<Integer> relatedMainTypeID = new ArrayList<>();

    @SerializedName("IntroductionDescription")
    private String introductionDescription = "";

    @SerializedName("Pros")
    private String pros = "";

    @SerializedName("Cons")
    private String cons = "";

    @SerializedName("RequiredTime")
    private int requiredTime = 0;

    @SerializedName("RequiredEmployee")
    private int requiredEmployee = 0;

    @SerializedName("RequiredBudget")
    private int requiredBudget = 0;

    @SerializedName("RequiredKnowledge")
    private int requiredKnowledge = 0;

    @SerializedName("Applications")
    private String applications = "";

    @SerializedName("ComplementaryContent")
    private List<CompContentToolItem> complementaryContent = new ArrayList<>();

    public ToolsItem mConstructor(ToolsItem item) {
        this.mainTypeID = item.getMainTypeID();
        this.persianName = item.getPersianName();
        this.englishName= item.getEnglishName();
        this.imageURL = item.getImageURL();
        this.otherName = item.getOtherName();
        this.countryID = item.getCountryID();
        this.year = item.getYear();
        this.complexityName = item.getComplexityName();
        this.relatedMainTypeID = item.getRelatedMainTypeID();
        this.introductionDescription = item.getIntroductionDescription();
        this.pros = item.getPros();
        this.cons = item.getCons();
        this.requiredTime = item.getRequiredTime();
        this.requiredBudget = item.getRequiredBudget();
        this.requiredEmployee = item.getRequiredEmployee();
        this.requiredKnowledge = item.getRequiredKnowledge();
        this.applications = item.getApplications();
        this.complementaryContent = item.getComplementaryContent();
        return this;
    }

    public String getEnglishName() {
        return englishName;
    }

    public void setEnglishName(String englishName) {
        this.englishName = englishName;
    }

    public String getOtherName() {
        return otherName;
    }

    public void setOtherName(String otherName) {
        this.otherName = otherName;
    }

    public int getCountryID() {
        return countryID;
    }

    public void setCountryID(int countryID) {
        this.countryID = countryID;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public String getComplexityName() {
        return complexityName;
    }

    public void setComplexityName(String complexityName) {
        this.complexityName = complexityName;
    }

    public List<Integer> getRelatedMainTypeID() {
        return relatedMainTypeID;
    }

    public void setRelatedMainTypeID(List<Integer> relatedMainTypeID) {
        this.relatedMainTypeID = relatedMainTypeID;
    }

    public String getIntroductionDescription() {
        return introductionDescription;
    }

    public void setIntroductionDescription(String introductionDescription) {
        this.introductionDescription = introductionDescription;
    }

    public String getPros() {
        return pros;
    }

    public void setPros(String pros) {
        this.pros = pros;
    }

    public String getCons() {
        return cons;
    }

    public void setCons(String cons) {
        this.cons = cons;
    }

    public int getRequiredTime() {
        return requiredTime;
    }

    public void setRequiredTime(int requiredTime) {
        this.requiredTime = requiredTime;
    }

    public int getRequiredEmployee() {
        return requiredEmployee;
    }

    public void setRequiredEmployee(int requiredEmployee) {
        this.requiredEmployee = requiredEmployee;
    }

    public int getRequiredBudget() {
        return requiredBudget;
    }

    public void setRequiredBudget(int requiredBudget) {
        this.requiredBudget = requiredBudget;
    }

    public int getRequiredKnowledge() {
        return requiredKnowledge;
    }

    public void setRequiredKnowledge(int requiredKnowledge) {
        this.requiredKnowledge = requiredKnowledge;
    }

    public String getApplications() {
        return applications;
    }

    public void setApplications(String applications) {
        this.applications = applications;
    }

    public List<CompContentToolItem> getComplementaryContent() {
        return complementaryContent;
    }

    public void setComplementaryContent(List<CompContentToolItem> complementaryContent) {
        this.complementaryContent = complementaryContent;
    }

    public int getMainTypeID() {
        return mainTypeID;
    }

    public void setMainTypeID(int mainTypeID) {
        this.mainTypeID = mainTypeID;
    }

    public String getPersianName() {
        return persianName;
    }

    public void setPersianName(String persianName) {
        this.persianName = persianName;
    }

    public String getImageURL() {
        return imageURL;
    }

    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }
}

Модель ребенка:

package com.example.amirmasoud.mgtools_2.model;

import com.google.gson.annotations.SerializedName;

import java.io.Serializable;

/**
 * Created by AmirMasoud on 12/12/2018.
 */

public class CompContentToolItem implements Serializable {

    @SerializedName("FileURL")
    private String fileURL;

    @SerializedName("Description")
    private String description;

    public String getFileURL() {
        return fileURL;
    }

    public void setFileURL(String fileURL) {
        this.fileURL = fileURL;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Служба:

public interface GetDataService {

    @GET("GetMainTypeByID")
    Call<ToolsItem> getToolItemContent(@Query("MainTypeID") int toolItemId);

}

Модифицированный экземпляр:

public class RetrofitInstance {
    private static final String BASE_URL = "https://assess.ir/service.svc/";
    private static Retrofit retrofit;

    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(UnsafeOkHttpClient.getUnsafeOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
                .build();
        }
        return retrofit;
    }
}

1 Ответ

0 голосов
/ 17 декабря 2018

Сначала вам нужно конвертировать в json, используя GSON, позвольте мне показать вам пример

 service.getToolItemContent(toolsItemId).enqueue(new Callback<ToolsItem>() {
        @Override
        public void onResponse(Call<ToolsItem> call, Response<ToolsItem> response) {
            Gson gson = new Gson();
            String data = gson.toJson(response.body)
            ToolsItem toolsItem = gson.fromJson(data,ToolsItem.class);
            toolItem.mConstructor(response.body());
        }

        @Override
        public void onFailure(Call<ToolsItem> call, Throwable t) {
            Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
        }
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...