Retrofit ile veri çekme

Android için programlar ve programlar için yardımlar
Cevapla
abdulkadirlevent
Site Admin
Mesajlar: 18
Kayıt: Pzr Oca 19, 2020 4:27 pm

Retrofit ile veri çekme

Mesaj gönderen abdulkadirlevent »

Example of expected JSON object:

Kod: Tümünü seç

{
    "deviceId": "56V56C14SF5B4SF",
    "name": "Steven",
    "eventCount": 0
}
Example of JSON array:

Kod: Tümünü seç

[
    {
        "deviceId": "56V56C14SF5B4SF",
        "name": "Steven",
        "eventCount": 0
    },
    {
        "deviceId": "35A80SF3QDV7M9F",
        "name": "John",
        "eventCount": 2
    }
]
Example of corresponding model class:

Kod: Tümünü seç

public class Device
{
    @SerializedName("deviceId")
    public String id;

    @SerializedName("name")
    public String name;

    @SerializedName("eventCount")
    public int eventCount;
}
DeviceAPI

Kod: Tümünü seç

public interface DeviceAPI
{
   // Get JSON object:
    @GET("device/{deviceId}")
    Call<Device> getDevice (@Path("deviceId") String deviceID);
    
    // Get JSON array:
    @GET("devices")
    Call<List<Device>> getDevices();
}
Calling the API:
Getting a JSON object

Kod: Tümünü seç

Call<Device> callObject = api.getDevice(deviceID);
callObject.enqueue(new Callback<Response<Device>>()
{
    @Override
    public void onResponse (Call<Device> call, Response<Device> response)
    {
        IF (response.isSuccessful()) 
        {
           Device device = response.body();
        }
    }

    @Override
    public void onFailure (Call<Device> call, Throwable t)
    {
        Log.e(TAG, t.getLocalizedMessage());
    }
});
Getting a JSON array

Kod: Tümünü seç

Call<List<Device>> callArray = api.getDevices();
callArray.enqueue(new Callback<Response<List<Device>>()
{
    @Override
    public void onResponse (Call<List<Device>> call, Response<List<Device>> response)
    {
       IF (response.isSuccessful()) 
        {
           List<Device> devices = response.body();
        }
    }

    @Override
    public void onFailure (Call<List<Device>> call, Throwable t)
    {
        Log.e(TAG, t.getLocalizedMessage());
    }
});

Cevapla