如何在Android中使用Retrofit庫?
介紹
Retrofit 是一個流行的 HTTP 庫,用於使用 API 解析來自網際網路的資料。我們可以使用此庫以 JSON 格式從 API 獲取資料,並在我們的應用程式中顯示該 JSON 資料。在本文中,我們將瞭解如何在 Android 中使用 Retrofit 庫。
實現
我們將建立一個簡單的應用程式,其中我們將建立一個 TextView 用於顯示應用程式的標題。之後,我們將建立另一個 TextView,用於使用 Retrofit 庫顯示來自 API 呼叫的響應。
步驟 1:在 Android Studio 中建立一個新專案
導航到 Android Studio,如下圖所示。在下面的螢幕中,單擊“新建專案”以建立一個新的 Android Studio 專案。
單擊“新建專案”後,您將看到下面的螢幕。
在此螢幕中,我們只需選擇“Empty Activity”並單擊“Next”。單擊“Next”後,您將看到下面的螢幕。
在此螢幕中,我們只需指定專案名稱。然後包名將自動生成。
注意:確保選擇 Java 作為語言。
指定所有詳細資訊後,單擊“Finish”以建立一個新的 Android Studio 專案。
專案建立完成後,我們將看到開啟的兩個檔案,即 activity_main.xml 和 MainActivity.java 檔案。
步驟 2:使用 activity_main.xml
導航到 activity_main.xml。如果此檔案不可見,則要開啟此檔案。在左側窗格中導航到 app>res>layout>activity_main.xml 以開啟此檔案。開啟此檔案後,向其中新增以下程式碼。程式碼中添加了註釋以詳細瞭解。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- on below line creating a text view for heading -->
<TextView
android:id="@+id/idTVHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="5dp"
android:padding="4dp"
android:text="Retrofit in Android"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="20sp"
android:textStyle="bold" />
<!-- on below line creating a text view for displaying a response message -->
<TextView
android:id="@+id/idTVMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idTVHeading"
android:layout_margin="5dp"
android:padding="4dp"
android:text="Message"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="18sp" />
</RelativeLayout>
說明:在上面的程式碼中,我們建立了一個根佈局作為相對佈局。在此佈局內,我們建立了一個 TextView 用於顯示應用程式的標題。之後,我們建立了另一個 TextView,用於顯示來自 API 呼叫的響應。
步驟 3:在 AndroidManifest.xml 檔案中新增許可權
導航到 app>AndroidManifest.xml 檔案,並在 manifest 標籤中新增以下許可權以讀取簡訊。
<!-- adding permissions on below line --> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
步驟 4:在 build.gradle 檔案中新增使用 Retrofit 庫的依賴項
導航到 Gradle Scripts>build.gradle 檔案,並在 dependencies 部分新增以下依賴項以使用 Retrofit 庫。
// adding below dependencies. implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
在 dependencies 部分新增上述依賴項後,只需同步您的專案即可安裝所有依賴項。
步驟 5:為響應物件建立一個新的 Java 類
導航到 app>java>您的應用程式的包名>右鍵單擊它>新建 Java 類,並將其命名為 Response Object,然後向其中新增以下程式碼。程式碼中添加了註釋以詳細瞭解。
package com.example.java_test_application;
// on below line creating a class for response object.
public class ResponseObject {
// on below line creating a variable for message.
private String message;
// on below line creating a getter method.
public String getMessage() {
return message;
}
// on below line creating a setter method.
public void setMessage(String message) {
this.message = message;
}
// on below line creating a constructor method.l
public ResponseObject(String message) {
this.message = message;
}
}
步驟 6:建立一個介面類以進行 Retrofit API 呼叫
導航到 app>java>您的應用程式的包名>右鍵單擊它>新建 Java 類,並將其命名為 RetrofitAPICall,然後向其中新增以下程式碼。程式碼中添加了註釋以詳細瞭解。
package com.example.java_test_application;
import retrofit2.Call;
import retrofit2.http.GET;
public interface RetrofitAPICall {
// as we are making a get request specifying annotation as get and adding a url end point to it.
@GET("43d590f03930")
// on below line specifying the method name which we have to call.
Call<ResponseObject> getData();
}
步驟 7:使用 MainActivity.java 檔案
導航到 MainActivity.java。如果此檔案不可見,則要開啟此檔案。在左側窗格中導航到 app>res>layout>MainActivity.java 以開啟此檔案。開啟此檔案後,向其中新增以下程式碼。程式碼中添加了註釋以詳細瞭解。
package com.example.java_test_application;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
// creating variables for text view on below line.
private TextView msgTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing variable for text view and button on below line.
msgTV = findViewById(R.id.idTVMsg);
// on below line we are creating a retrofit
// builder and passing our base url
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://json.extendsclass.com/bin/")
// on below line we are calling add Converter
// factory as GSON converter factory.
.addConverterFactory(GsonConverterFactory.create())
// at last we are building our retrofit builder.
.build();
// below line is to create an instance for our retrofit api call class and initializing it.
RetrofitAPICall retrofitAPI = retrofit.create(RetrofitAPICall.class);
// on below line creating and initializing call variable for get data method.
Call<ResponseObject> call = retrofitAPI.getData();
// on below line adding an enqueue to parse the data from api.
call.enqueue(new Callback<ResponseObject>() {
// on below line calling on response method.
@Override
public void onResponse(Call<ResponseObject> call, Response<ResponseObject> response) {
// inside on response method setting text from our api response.
msgTV.setText(response.body().getMessage());
}
// on below line calling on failure method.
@Override
public void onFailure(Call<ResponseObject> call, Throwable t) {
// displaying a toast message when as error is received.
Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
}
});
}
}
說明:在上面的程式碼中,我們首先為 TextView 建立變數。現在我們將看到 onCreate 方法。這是每個 Android 應用程式的預設方法。建立應用程式檢視時會呼叫此方法。在此方法內,我們設定內容檢視,即名為 activity_main.xml 的佈局檔案,以從該檔案中設定 UI。在 onCreate 方法內,我們初始化 TextView 的變數。然後我們建立並初始化 Retrofit 的變數。在其中,我們還指定基本 URL 並向其新增 Gson 轉換器工廠。之後,我們使用 call.enqueue 方法進行 Retrofit API 呼叫。在此方法內,我們建立了兩種方法: onResponse 和 onFailure。在 response 方法中,我們將文字訊息設定為我們的 TextView,在錯誤方法中,我們顯示一個 Toast 訊息。
新增上述程式碼後,我們只需單擊頂部欄中的綠色圖示即可在移動裝置上執行我們的應用程式。
注意:確保已連線到您的真實裝置或模擬器。
輸出
結論
在本文中,我們瞭解瞭如何在 Android 中使用 Retrofit 庫,以及如何使用此庫從網際網路載入資料。
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP