4

As I am very new to using third-party HTTP libraries for Android like Retrofit, there are a few questions I would like to ask you who could help me.

It seems there recently has been a great change on a transition from Retrofit 1.9 to 2.0, for example the changes on APIs. So I could not find a proper documentations for using the library, even on its own webpage.

When it comes to implementing an HTTP request for registering a user on the server, it seems, according to the webpage, the first thing is to create an interface that defines the role (e.g. POST, GET, etc.). For example:

public interface GitHubService {
  @GET("/users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

And it seems I should create a Retrofit instance to connect to the server and use

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

The things I really would like to find out are,

  1. What does Repo in the above generics mean? that's the first thing I still cannot figure out.

  2. What should be written in the parenthesis followed by each annotation like @POST or @GET? Does it mean a subdirectory under the server URL? According to the example codes above, does the @GET annotation state that the listRepos method get the user value from the 'user' path or something? This is so confusing..

Please, I'm really new to this world, so I'm desperate for your helps. Thanks in advance.

MarshallLee
  • 1,290
  • 4
  • 23
  • 42
  • Watch [this talk first](https://www.youtube.com/watch?v=aEuNBk1b5OE#t=2480) (about Retrofit 1.x) and then [this talk](https://www.youtube.com/watch?v=KIAoQbAu3eA&feature=youtu.be) (about Retrofit 2.x) by Jake Wharton, one of the creators of Retrofit. – nhaarman Sep 24 '15 at 21:16
  • Refer to http://stackoverflow.com/a/41015925/3470479 – Prakhar Kulshreshtha Dec 07 '16 at 11:12

5 Answers5

4
  1. 'Repo' in this example means a repository on Github. Retrofit automatically deserializes JSON responses to Java POJOs. The example fetches information about Github repositories from the Github API, the fetched repository information is represented by a Repo class / a List of Repo objects. You'll have to provide your own class representation of the data that you're getting from your server / API.
  2. Does it mean a subdirectory under the server URL?

Basically, yeah. It's the path / Uri to the resource you're trying to access on the server specified with baseUrl.

In this case we have the baseUrl https://api.github.com. We append the path /users/{user}/repos. The method

@GET("/users/{user}/repos")
      Call<List<Repo>> listRepos(@Path("user") String user);

takes a user id as an argument and replaces {user} with that argument.

So if you call that method with the argument JakeWharton the full Uri is

https://api.github.com/users/JakeWharton/repos

You can call it from your browser to see the response. You'll have to change those Url/Uri Strings to match the API you want to access.

.

fweigl
  • 21,278
  • 20
  • 114
  • 205
0

Its Working

enter image description here package com.keshav.gmailretrofitexampleworking.network;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static final String BASE_URL = "http://api.androidhive.info/json/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
==============================================
package com.keshav.gmailretrofitexampleworking.network;

import com.keshav.gmailretrofitexampleworking.models.Message;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {
    @GET("inbox.json")
    Call<List<Message>> getInbox();
}

=============================================

call APi

private void getInbox() {
    swipeRefreshLayout.setRefreshing(true);

    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);

    Call<List<Message>> call = apiService.getInbox();
    call.enqueue(new Callback<List<Message>>() {
        @Override
        public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
            // clear the inbox
            messages.clear();

            // add all the messages
            // messages.addAll(response.body());

            // TODO - avoid looping
            // the loop was performed to add colors to each message

            Log.e("keshav","response" +response.body());

            for (Message message : response.body()) {
                // generate a random color

                // TODO keshav Generate Random Color Here
                message.setColor(getRandomMaterialColor("400"));
                messages.add(message);
            }

            mAdapter.notifyDataSetChanged();
            swipeRefreshLayout.setRefreshing(false);
        }

        @Override
        public void onFailure(Call<List<Message>> call, Throwable t) {
            Toast.makeText(getApplicationContext(), "Unable to fetch json: " + t.getMessage(), Toast.LENGTH_LONG).show();
            swipeRefreshLayout.setRefreshing(false);
        }
    });
}

compile 'com.google.code.gson:gson:2.6.2'

compile 'com.squareup.retrofit2:retrofit:2.0.2'

compile 'com.squareup.retrofit2:converter-gson:2.0.2'

Source Code

https://drive.google.com/open?id=0BzBKpZ4nzNzUVFRnVVkzc0JabUU

https://drive.google.com/open?id=0BzBKpZ4nzNzUc2FBdW00WkRfWW8

Keshav Gera
  • 10,807
  • 1
  • 75
  • 53
0

add this library

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

RetrofitClient.java

public class RetroClient {

private static final String ROOT_URL = "xyz";
private static Retrofit getRetrofitInstance() {
    return new Retrofit.Builder()
            .baseUrl(ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}
public static ApiService getApiService() {
    return getRetrofitInstance().create(ApiService.class);
}

}

ApiInterface.java

public interface ApiService {

@GET("get_exams.php")
Call<GetExamListResponse> getExamList();

@FormUrlEncoded
@POST("get_exam_details.php")
Call<GetExamListDetailResponse> getExamDetail(@Field("exam_id") String exam_id);

Response.java

@SerializedName("data")
@Expose
private ArrayList<GetCountryListModel> getCountryListModel = null;

Activity.java

 public void get_alluni() {
    ApiService api = RetroClient.getApiService();
    Call<GetAllUniversityListResponse> call = api.getAllUniversitiesList();
    call.enqueue(new Callback<GetAllUniversityListResponse>() {
        @Override
        public void onResponse(Call<GetAllUniversityListResponse> call, Response<GetAllUniversityListResponse> response) {

            if (response.isSuccessful()) {
                getAllUniversitiesModels = response.body().getGetAllUniversitiesModels();
                Log.e("EMPASASAS", getAllUniversitiesModels.toString());

                LinearLayoutManager linearLayout = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
                recyclerView1 = (RecyclerView) findViewById(R.id.recycler_view_mostpopularcoursemain);
                recyclerView1.setVisibility(View.VISIBLE);
                //recyclerView.setVisibility(View.GONE);
                recyclerView1.setLayoutManager(linearLayout);
                eAdapter1 = new AllUniversityRecyclerAdapter(MainActivity.this, getAllUniversitiesModels);
                recyclerView1.setAdapter(eAdapter1);
            }
        }

        @Override
        public void onFailure(Call<GetAllUniversityListResponse> call, Throwable t) {
            //Toast.makeText(MainActivity.this, "Fail", Toast.LENGTH_SHORT).show();

        }
    });
}

Adapter.java

public class ChooseExamRecyclerViewAdapter extends RecyclerView.Adapter<ChooseExamRecyclerViewAdapter.CustomViewHolder> {
private ArrayList<GetExamListModel> getExamListModels;
Context context;

public ChooseExamRecyclerViewAdapter(Context context, ArrayList<GetExamListModel> getExamListModels) {
    this.getExamListModels = getExamListModels;
    this.context = context;
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.choose_exam_list, parent, false);

    return new CustomViewHolder(itemView);
}

@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
    GetExamListModel getExamListModel = getExamListModels.get(position);
    holder.exam_name.setText(getExamListModel.getExam_name());
    holder.field_name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Context context = v.getContext();
            Intent intent = new Intent(context, ExamDetailsActivity.class);
            intent.putExtra("EXAMID", getExamListModel.getExam_id());
            context.startActivity(intent);
        }
    });
}

@Override
public int getItemCount() {
    return getExamListModels.size();
}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    public TextView exam_name;
    public CardView field_name;

    public CustomViewHolder(View view) {
        super(view);
        exam_name = (TextView) view.findViewById(R.id.exam_name);
        field_name = (CardView) view.findViewById(R.id.field_name);

    }
}

}

0

step 1 dependencies:

  //RETROFIT
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation "com.squareup.okhttp3:okhttp:4.7.2"
    implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2'

step 2 Utils class

public class Utils {
    private static Utils singleton;
    public Dialog dialog;

    public static Utils getInstance() {
        if (singleton == null) {
            singleton = new Utils();
        }
        return singleton;
    }

    public ApiInterfaces initializeWebServiceCall(Context context) {
        Gson gson = new GsonBuilder().setLenient().create();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(1, TimeUnit.MINUTES).readTimeout(1, TimeUnit.MINUTES).addInterceptor(interceptor).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiEndPoint.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        ApiInterfaces mRestAPI = retrofit.create(ApiInterfaces.class);
        return mRestAPI;
    }
}

step 3 interface

public interface ApiInterfaces {

 @FormUrlEncoded
    @POST(ApiEndPoint.BASE_URL + "address_list")
    Call<AddressBean> address_list(@Field("user_id") String user_id);
}

step 4 api calling

 private RecyclerView rec_address;
    private ArrayList<AddressBean.AddressData> AddressList = new ArrayList();





    Call<AddressBean> call = Utils.getInstance().initializeWebServiceCall(SelectAddressActivity.this).address_list(id);
        call.enqueue(new Callback<AddressBean>() {
            @Override
            public void onResponse(Call<AddressBean> call, Response<AddressBean> response) {
                if (response.body() != null) {
                    if (!SelectAddressActivity.this.isFinishing() && pd.isShowing())
                        pd.dismiss();
                    String status, message, id, pincode, house_no, city, area, state, user_id, name, mobile_no, alt_mobile_no;
                    String address;
                    status = response.body().getStatus();
                    message = response.body().getMessage();
                    Log.d("response12", "SUCCESS:" + status + "\n MESSAGE:" + message);
                    if (response.body().getStatus().equalsIgnoreCase("success")) {
                        pd.dismiss();
//                        Toast.makeText(AddAddressActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();
                        ArrayList<AddressBean.AddressData> list = response.body().getDataList();
                        Log.d("fugweut325ncv", list.toString() + "\n " + list.size());
                        for (int i = 0; i < list.size(); i++) {
                            id = list.get(i).getId();
                            pincode = list.get(i).getPincode();
                            house_no = list.get(i).getHouse_no();
                            city = list.get(i).getCity();
                            area = list.get(i).getArea();
                            state = list.get(i).getState();
                            name = list.get(i).getName();
                            mobile_no = list.get(i).getMobile_no();
                            alt_mobile_no = list.get(i).getAlt_mobile_no();
                            AddressBean.AddressData adata = new AddressBean.AddressData(id, pincode, house_no, city, area, state, name, mobile_no, alt_mobile_no);
                            AddressList.add(adata);
                            Log.d("dutgwihv", "PINCODE" + pincode + "\n HOUSE NO:" + house_no + "CITY:" +
                                    city + "\n AREA" + area + "\n STATE" + state + "\n name:" + name + "\n mobile:"
                                    + mobile_no + "alternate:" + alt_mobile_no);
                            if (alt_mobile_no.equals("0")) {
                                address = "Name:" + name + "\nMobile Number:" + mobile_no + "\nAddress:" + house_no + ", " + area + ", " + city + ", " + state + "- " + pincode;
                            } else {
                                address = " Name:" + name + "\n Mobile Number:" + mobile_no + "," + alt_mobile_no + "\n Address:" + house_no + ", " + area + ", " + city + ", " + state + "- " + pincode;
                            }
                        }
                        AddressAdapter adapter = new AddressAdapter(SelectAddressActivity.this, AddressList);
                        rec_address.setLayoutManager(new GridLayoutManager(SelectAddressActivity.this, 1));
                        rec_address.setItemAnimator(new DefaultItemAnimator());
                        rec_address.setAdapter(adapter);
                    } else {
                        pd.dismiss();
                        Toast.makeText(SelectAddressActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    if (!SelectAddressActivity.this.isFinishing() && pd.isShowing()) {
                        pd.dismiss();
                        Toast.makeText(SelectAddressActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<AddressBean> call, Throwable t) {
                if (!SelectAddressActivity.this.isFinishing() && pd.isShowing())
                    pd.dismiss();
                AlertDialog.Builder b1 = ApiEndPoint.getAlertDialog(SelectAddressActivity.this, "Time Out", ApiEndPoint.getMessage(), R.mipmap.ic_launcher, "Cancel");
                b1.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        sendAddressListRequest();
                    }
                });
                b1.create().show();
            }
        });

step 5 bean class

public class AddressBean implements Parcelable{
    @SerializedName("status")
    @Expose
    private String status;

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

    @SerializedName("data")
    @Expose
    private ArrayList<AddressData> DataList;

    protected AddressBean(Parcel in) {
        status = in.readString();
        message = in.readString();
        DataList = in.createTypedArrayList(AddressData.CREATOR);
    }

    public static final Creator<AddressBean> CREATOR = new Creator<AddressBean>() {
        @Override
        public AddressBean createFromParcel(Parcel in) {
            return new AddressBean(in);
        }

        @Override
        public AddressBean[] newArray(int size) {
            return new AddressBean[size];
        }
    };

    public String getStatus() {
        return status;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public ArrayList<AddressData> getDataList() {
        return DataList;
    }

    public void setDataList(ArrayList<AddressData> dataList) {
        DataList = dataList;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(status);
        parcel.writeString(message);
        parcel.writeTypedList(DataList);
    }

    public static class AddressData implements Parcelable {

            public AddressData() {
            }

            public AddressData(String id, String pincode, String house_no, String city, String area, String state, String name, String mobile_no, String alt_mobile_no) {
                this.id = id;
                this.pincode = pincode;
                this.house_no = house_no;
                this.city = city;
                this.area = area;
                this.state = state;
                this.name = name;
                this.mobile_no = mobile_no;
                this.alt_mobile_no = alt_mobile_no;
            }

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

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

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

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

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

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

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

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

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

            protected AddressData(Parcel in) {
                id = in.readString();
                pincode = in.readString();
                house_no = in.readString();
                city = in.readString();
                area = in.readString();
                state = in.readString();
                name = in.readString();
                mobile_no = in.readString();
                alt_mobile_no = in.readString();
            }

            public static final Creator<AddressData> CREATOR = new Creator<AddressData>() {
                @Override
                public AddressData createFromParcel(Parcel in) {
                    return new AddressData(in);
                }

                @Override
                public AddressData[] newArray(int size) {
                    return new AddressData[size];
                }
            };

            public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getPincode() {
            return pincode;
        }

        public void setPincode(String pincode) {
            this.pincode = pincode;
        }

        public String getHouse_no() {
            return house_no;
        }

        public void setHouse_no(String house_no) {
            this.house_no = house_no;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getArea() {
            return area;
        }

        public void setArea(String area) {
            this.area = area;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getMobile_no() {
            return mobile_no;
        }

        public void setMobile_no(String mobile_no) {
            this.mobile_no = mobile_no;
        }

        public String getAlt_mobile_no() {
            return alt_mobile_no;
        }

        public void setAlt_mobile_no(String alt_mobile_no) {
            this.alt_mobile_no = alt_mobile_no;
        }

            @Override
            public int describeContents() {
                return 0;
            }

            @Override
            public void writeToParcel(Parcel parcel, int i) {
                parcel.writeString(id);
                parcel.writeString(pincode);
                parcel.writeString(house_no);
                parcel.writeString(city);
                parcel.writeString(area);
                parcel.writeString(state);
                parcel.writeString(name);
                parcel.writeString(mobile_no);
                parcel.writeString(alt_mobile_no);
            }
        }
}
0

Api Calling - Java First upon inject dependencies in build.gradle(module) file

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2'
implementation 'com.github.bumptech.glide:glide:4.13.2'

Create service class then

public class RetrofitClient {

public static <S> S createService(Class<S> serviceClass, String url) {

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient httpClient = new OkHttpClient.Builder().connectTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES)
            .readTimeout(1, TimeUnit.MINUTES)
            .addInterceptor(interceptor).build();

    Retrofit.Builder builder =
            new Retrofit.Builder()
                    .client(httpClient)
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create(gson));

    Retrofit retrofit = builder.client(httpClient).build();
    return retrofit.create(serviceClass);
}}

Then create interface web service for URI end point with fetch response model class

public interface RemarkApi {

@GET("Remarks/List")
Call<ArrayList<RemarkResponsePojo>> remarkNotificationList(@Header("key") String key,
                                                      @Header("userid") String userId);

@GET("Remarks/ListDetails")
Call<ArrayList<RemarkResponsePojo>> remarkCallerList(@Header("key") String key,
                                                     @Header("userid") String userId,
                                                     @Header("caller_id") String callerNumber);
}

First any API giving you first check in postman response success or not **then if success response in any API then go to website "https://json2kt.com/" and select "json to java" then just paste your response in website container then get your answer then all answer parameter copy and go to the your class file and paste here. after that press keyboard key "Alt" + "insert" then select get and set option double clicked. done. ** *for example: *

public class RemarkResponsePojo implements Serializable {

@SerializedName("Caller")
String Caller;

public String getCaller() {
    return Caller;
}

public void setCaller(String caller) {
    Caller = caller;
}}

After that you used anywhere class file Just create method and call init method or onCreate method

*for example : *

private void getRemarkNotificationServer() {
    refreshLayout.setRefreshing(true);
    key = QuickUtils.prefs.getString(AUtils.KEY, "");
    userId = QuickUtils.prefs.getString(AUtils.AGENT_ID, "0");

    RemarkApi remarkApiWebService = RetrofitClient.createService(RemarkApi.class, AUtils.SERVER_URL);
    Call<ArrayList<RemarkResponsePojo>> getNotificationList = remarkApiWebService.remarkNotificationList(key,userId);

    getNotificationList.enqueue(new Callback<ArrayList<RemarkResponsePojo>>() {
        @Override
        public void onResponse(Call<ArrayList<RemarkResponsePojo>> call, Response<ArrayList<RemarkResponsePojo>> response) {
            if (response.code() == 200){
                if (response.body() != null) {
                    refreshLayout.setRefreshing(false);
                    txtNoDataFound.setVisibility(View.GONE);

                     remarkList = response.body();
                    Log.e("TAG", "response: "+response.body());
                    if (remarkList.isEmpty()){
                        txtNoDataFound.setVisibility(View.VISIBLE);
                    }else {
                        txtNoDataFound.setVisibility(View.GONE);
                        setAdapter(remarkList);
                    }


                }
            } else if (response.code() == 500){
                refreshLayout.setRefreshing(false);
                recyclerView.setVisibility(View.GONE);
                txtNoDataFound.setVisibility(View.VISIBLE);
                Toast.makeText(context,""+response.body(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ArrayList<RemarkResponsePojo>> call, Throwable t) {
            refreshLayout.setRefreshing(false);
            txtNoDataFound.setVisibility(View.VISIBLE);
            Log.e("TAG", "onFailure: ", t);
            Toast.makeText(context,""+t, Toast.LENGTH_SHORT).show();

        }
    });
}