Using Retrofit 2.0 in Android

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

It seems that recently there have been significant changes in the transition from Retrofit 1.9 to 2.0, for example, API changes. Therefore, I could not find the correct documentation for using the library, even on my own web page.

When it comes to implementing an HTTP request to register a user on the server, it seems, according to the web page, you first need to create an interface that defines the role (for example, POST, GET, etc.). For instance:

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

And it seems to me, I should create an instance of Retrofit to connect to the server and use

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

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

What I really would like to know

  • ? , .

  • , , @POST @GET? URL- ? @GET, listRepos - ? .

, , . .

+4
3
  • 'Repo' Github. Retrofit JSON Java POJO. Github API Github, ​​ Repo/List of Repo. , /API.
  • URL- ?

, . /Uri , , baseUrl.

baseUrl https://api.github.com. /users/{user}/repos.

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

{user} .

, JakeWharton, Uri

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

, . Url/Uri API, .

.

+4

enter image description here   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();
}

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

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'

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

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

0

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

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

Source: https://habr.com/ru/post/1662982/


All Articles