Last active
July 13, 2022 06:19
-
-
Save ipetrushin/51e96eb279f8eb10be020ceb6b490985 to your computer and use it in GitHub Desktop.
Retrofit cheat sheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Добавить в build.gradle в раздел | |
dependencies { | |
compile 'com.squareup.retrofit2:retrofit:2.5.0' | |
compile 'com.squareup.retrofit2:converter-gson:2.5.0' | |
} | |
Этапы создания приложения: | |
1) Описать классы для запросов и ответов сервера | |
2) Описываем интерфейс сервиса обращения к JSON API | |
interface JsonServer { | |
@POST("/") // путь к API | |
Call<Registration> register(@Body User user); | |
// Тип ответа, действие, тип запроса | |
} | |
В интерфейсе упоминаете классы и путь к API | |
3) Создаёте экземпляр библиотеки Retrofit | |
Retrofit retrofit = new Retrofit.Builder() | |
.baseUrl(API_URL) // адрес сервера | |
.addConverterFactory(GsonConverterFactory.create()) | |
.build(); | |
4) Генерируете сервис обращения к JSON API, интерфейс которого описан ранее | |
JsonServer jsonServer = retrofit.create(JsonServer.class); | |
5) Создаём запрос к серверу | |
Call<Registration> call = jsonServer.register(new User("register", nickname)); | |
6) Описываем обработчики ответов от сервера (onResponse, onFailure) | |
Callback<Registration> callback = new Callback<Registration>() { | |
@Override | |
public void onResponse(Call<Registration> call, retrofit2.Response<Registration> response) { | |
Registration register = response.body(); // получили ответ в виде объекта | |
} | |
@Override | |
public void onFailure(Call<Registration> call, Throwable t) { | |
// обрабатываем ошибку, если она возникла | |
} | |
}; | |
7) Поставить запрос в очередь, указав обработчик | |
call.enqueue(callback); | |
Ответ на запрос будет передан в метод onResponse (в качестве параметра). | |
Готовый код класса https://pastebin.com/KZf3KkzW | |
Для отображения данных на Listview через ArrayAdapter испльзуйте разметку | |
<TextView xmlns:android="http://schemas.android.com/apk/res/android" | |
android:textSize="30sp" | |
android:textColor="#887700" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment