Skip to content Skip to sidebar Skip to footer

Get Data From API Using Retrofit

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,

Solution 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
    }

Solution 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();
        }
    });
}

Solution 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


Post a Comment for "Get Data From API Using Retrofit"