Retrofit Android : How To Get JSON Data With Retrofit MVP

206 views Asked by At

Please Guys I'm confused about how to retrieve data using retrofit with MVP architecture, I already try other steps but not worked for me, can you help me? I'm still learning to use retrofit with MVP architecture

Here's my JSON data :`

{
"status": 200,
  "success": true,
  "data": {
    "token": {
      "token_type": "Bearer",
      "expires_in": 1296000,
      "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI5MmU4YWVmMC1jMzMzLTQxYjItODNlOC1lMGU4NTRmMWZhNDIiLCJqdGkiOiJmZDdiM2ViMTI1NWMxNzdkYTQ3MjMxNGQ5MDk0MzFhMGE2MmQzZDY3MTZhNmMyMzI0MGY1YmE4ZDAzYzI4NDJiZmE5ZDJhNzdlYTE3NDA4YyIsImlhdCI6MTYxOTA2MTk4NC44Nzc1NzksIm5iZiI6MTYxOTA2MTk4NC44Nzc1ODIsImV4cCI6MTYyMDM1Nzk4NC44NTA2NzMsInN1YiI6IjI4Iiwic2NvcGVzIjpbXX0.K3QWMKTB3XPz8YGAfizKkeaB6JySjnT5hS4o_sKt11-VxX7S45IN39TJeqaxCeytuy_23rerfyTI_8KF4J3GulStOy3vnfgZ-l5G653bLJH2m46PYgjhHQlxy9cdbhV8HG7eO9A4-MwbKYQsv8teo1lupd3dQ4gEgwEme-SbMgxtMWJMPOubqLWAQlHsjOyPNgB1v_OEgtqs6ZmZdi5BkHNHiiPoTtBeeXof_bE4l45IkET3nAlujomu1kXEXe_LSIYQooPUa34eobJzHPzpfgomvykK--SsrI5A1-8phG16qUVhbROUM3dqwFuIJN4vR1vGKgl_xpUk8z8Gh_ABsURxJLK2JhIG5mYYovx7NyrkyDBEUb3NCt_85yB0hUIbKaKIZ1xY_s694ZjSZNoYsqtPPyGm0nreU2qUBbS5Tf1XOdyfT5sHR9e0bhkZIuW9lNTg64zpC9hCkTmggHLmQ8j25HlgpaBfAZrQnkZTqVt2LRcF-vAi1O9DvND2hD6OC09NBH7oBS_hElEMvBWjdpos4Q1Ij21uxFXEDmFttyxBnYAA_uKZ7GQMXAWc6wfWCMVKeGayJinLLRic5B1fX-iotsrKjr1LSLiPUF9d7RhCu-pZekvYmzAKvFF16_yWJnCLQZ0zxjM0zLrHZk336gpLnNf4ifw-K8OmN6kh838",
      "refresh_token": "def50200dfd479e0e36f182e2eb6c36b488297a73452f2ddb89f5bfdf13ad9f70a588d8403eac74a2f589d9fc27199265276aaff9ef5597dcb4b2b4d28e3185ad2ca22c15e0413854866b0b024c31f722784dcaf52287e131d3ae1e099dfe9c67cb9ecce14162d79e4810edca8a1b775a66bf7526951d12a7fcc6660a9de0bc67926fbdae2e331987c906dc1beefeacf91e6ed60ee4e46fe57176fb5e6a39a9c9cd3187be45567e89bb24b12f2d880a39e9bb09947aa6dcd83c8b0a5f3516e9bba96da79caf3d0f5408ea4fd4b77568968fdb9bf6d30daa9d6682fbddb70cd07d620e8503853c3ecd1b9f00ddbeb62755a0e816be8d281293f287113a1b0f3e2117eed855873a54bf06e2052c15f31a5e4ad2a1167e72012fe9452c8cd9a84a7a31dc2e847562e1b5bf9aade9afab8080e6255e4d688c34e71387a9ac6c387d02caac9c2b2c5a9cf433e1d36368a0084180c2ee06d69f8c3b2bf820f4e9c6748964e7c5d1b1b78205429f2663895db8f6b90ae7ea47a6d2cdfb297ef4648fc211bf11bc33e"
    },
    "user": {
      "id": 28,
      "name": "xxxx",
      "email": "xxxx",
      "email_verified_at": "2021-03-15T10:20:46.000000Z",
      "current_team_id": 28,
      "created_at": "2021-03-15T10:19:38.000000Z",
      "updated_at": "2021-03-15T10:20:46.000000Z",
      "deleted_at": null,
      "current_team": {
        "id": 28,
        "owner_id": 28,
        "name": "xxx",
        "logo": "team/logos/zlxKwZmrmkwd6b9nisQMAsNIS32UQfOqo2u2d4FW.png",
        "address": "Jl...",
        "callback_url": "https://callback.ppndev.xyz",
        "bank_id": "1",
        "account_number": "23312312",
        "status": "verified",
        "created_at": "2021-03-15T10:19:38.000000Z",
        "updated_at": "2021-03-29T02:11:48.000000Z",
        "meta": null
      }
    },
    "team": {
      "id": 28,
      "owner_id": 28,
      "name": "xxx",
      "logo": "team/logos/zlxKwZmrmkwd6b9nisQMAsNIS32UQfOqo2u2d4FW.png",
      "address": "Jl...",
      "callback_url": "https://callback.ppndev.xyz",
      "bank_id": "1",
      "account_number": "23312312",
      "status": "verified",
      "created_at": "2021-03-15T10:19:38.000000Z",
      "updated_at": "2021-03-29T02:11:48.000000Z",
      "meta": null
    }
  }
}

And here's my response :

public class Connector implements Serializable {

@SerializedName("status")
@Expose
private String status;

@SerializedName("success")
@Expose
private String success;

@SerializedName("data")
@Expose
private List<Data> data;

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public String getSuccess() {
    return success;
}

public void setSuccess(String success) {
    this.success = success;
}

public List<Data> getData() {
    return data;
}

public void setData(List<Data> data) {
    this.data = data;
}

@Override
public String toString() {
    return "Connector{" +
            "status='" + status + '\'' +
            ", success='" + success + '\'' +
            ", data=" + data +
            '}';
}

My view interfaces :

    public interface DataView {
    void onConnected(Connector response);
    void onErrorResponse(String errorResponse);
}

My PresenterImpl :

    public interface DataPresenterImpl {
    void connected(String status, String success, Connector connector);
}

My Presenter :

    public class DataPresenter implements DataPresenterImpl {

    DataView view;
    Context context;

    public DataPresenter(Context context, DataView view) {
        this.view = view;
        this.context = context;
    }

    @Override
    public void connected(String status, String success, Connector connector) {
        final Observable<Connector> connectorApi = NetworkClient.getNetworkClient(context)
                .getConnector().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());

        DisposableObserver<Connector> con =  connectorApi.subscribeWith(new DisposableObserver<Connector>() {
            @Override
            public void onNext(@NonNull Connector connector) {
                view.onConnected(connector);
            }

            @Override
            public void onError(@NonNull Throwable e) {
                view.onErrorResponse(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }
}

My NetworkClient :

public class NetworkClient extends Application {

    public static NetworkAPI getNetworkClient(Context context){
        Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().setLenient().create();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .client(getClient())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();

        return retrofit.create(NetworkAPI.class);
    }

    public static OkHttpClient getClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.MINUTES)
                .readTimeout(1, TimeUnit.MINUTES)
                .writeTimeout(1, TimeUnit.MINUTES)
                .addInterceptor(getLoggingInterceptor())
                .build();
    }


    public static HttpLoggingInterceptor.Level getInterceptorLevel(){
        if (BuildConfig.DEBUG)
            return HttpLoggingInterceptor.Level.BODY;
        else
            return HttpLoggingInterceptor.Level.NONE;
    }

    public static HttpLoggingInterceptor getLoggingInterceptor() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(getInterceptorLevel());
        return httpLoggingInterceptor;
    }
}

My API interfaces :

public interface NetworkAPI {

    @FormUrlEncoded
    @POST("xxxx")
    Observable<LoginResponse> login(@Field("username") String username,
                                    @Field("password") String password,
                                    @Field("serial_number") String serial_number);

    @GET("xxx")
    Observable<Connector> getConnector();

}
1

There are 1 answers

0
Anand On

Issue:

You are parsing the key data into the list but it is a JSONObject containing child objects: token, user, and team.

@SerializedName("data")
@Expose
private List<Data> data;

This code is expecting JSONArray but your response has JSONObject.

Solution:

First, create POJO classes for each object for the child objects inside the data key. Declare the variable for these classes inside the Data class for serialization. Finally, change the above declaration private List<Data> data to private Data data,