Kotlinを使用したAndroid上のRetrofit2

今日は、Retrofit 2での作業を検討します。真実のために、PicassoSpots-dialogという2つの別々のライブラリで作業することに注意してください



この記事は、Retrofit 2をまだ使用したことがない人にのみ読むことをお勧めします。結局のところ、この記事では、すべての人が理解できるように、すべてを可能な限り詳細に説明します。



0.プロジェクトの作成



ここでのすべては可能な限り単純です。AndroidStudioで新しいプロジェクトを作成し、[空のアクティビティ]を選択します。次に、プログラミング言語を選択する必要があります。Kotlinを使用します。



1.依存関係を追加します



次に、必要なすべてのライブラリを追加する必要があるため、build.gradleに移動して、以下を追加します。



dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.picasso:picasso:2.71828'

    //noinspection GradleCompatible
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.github.d-max:spots-dialog:1.1@aar'
}


お気づきかもしれませんが、ここでは、スポットの進行状況ダイアログを含む、必要なすべてのライブラリを追加しました。あなたはそれについてもっと読むことができます。次に、build.gradle(Modul:app)にこれを挿入する必要があります:



 compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }


マニフェストに移動し、電話を使用する許可を追加するだけです。
  <uses-permission android:name="android.permission.INTERNET"/>




2.データクラスの追加



2番目のポイントに進む前に、どこからデータを取得するかを見つける必要がありますか?解析はここからです。



それでは、このサイトのコンテンツをコピーして、ここにアクセスしてください。ここで、以前にコピーしたテキストをサイトから貼り付けます。ツリーをクリックした後、リストが表示され、それを開きます。これで、8つのオブジェクトがあることがわかります。誰かが理解できない場合は、画面を表示します。







右側に表示されているのは、コピーしたテキストであり、右側に表示されているのは、すでに処理されたデータです。



ここでAndroidStudioに戻り、フォルダを作成し、それをModelと呼びます。そこで、kotlinクラスを作成し、通常のクラスからMovieという名前を付け、データクラスを変換し、クラスの前にデータを追加し、中括弧を括弧に置き換えます。次に、すでに括弧で囲まれている変数を示します。ちなみに、変数はnull可能なタイプである必要があります。



完全なコード
data class Movie(
    var name: String? = null,
    var realname: String? = null,
    var team: String? = null,
    var firstapperance: String? = null,
    var createdby: String? = null,
    var publisher: String? = null,
    var imageurl: String? = null,
    var bio: String? = null
)




フォルダーがModelと呼ばれる理由がわからない場合は、次のように説明します



。Modelは、アプリケーションデータに関連付けられているロジックです。言い換えれば、これらはPOJO、API、データベースを操作するためのクラスです。



3.クライアントの作成



次に、Retrofitフォルダーを作成し、そのフォルダーにオブジェクトを作成してRetrofitClientという名前を付け、次にRetrofitタイプのretrofit変数を作成します。その後、関数を作成してgetCleint(baseUrl:String)と呼び、戻りタイプはRetrofitです。関数の本体では、retrofitがnullであるかどうかを確認する必要があり、retrofitがnullの場合は、Retrofitをretrofit.Builder()に割り当て、baseUrlパラメーターを使用してbaseUrlをアタッチし、次にGsonConverterFactory.create()パラメーターを使用してaddconverterFactoryメソッドをアタッチし、build( )そしてレトロフィットをゼロ以外のタイプに戻します



完全なコード

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

object RetrofitClient {
    private var retrofit: Retrofit? = null

    fun getClient(baseUrl: String): Retrofit {
        if (retrofit == null) {
            retrofit = Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
        return retrofit!!
    }
}




RetrofitのBuilderは、BuilderインターフェイスとAPIを使用してHTTP操作のURLエンドポイント定義を定義するインスタンスです。



4.インターフェイスの操作



インターフェイス-抽象クラスを作成するために必要です。



その中にインターフェイスパッケージを作成し、インターフェイスを配置してRetrofitServiecesと呼びます。括弧内にGetリクエストを作成し、引用符を書き込みます。引用符でデータを解析するブランチを示します。これは驚くべきことです。ただし、その前に、GETおよびPOST要求とは

GET(特定のリソース(サイト)

POSTからデータを要求する)とは何かを言う価値があります。さらに処理するためにサーバーにデータを送信



します。次に、getMovieList関数を作成する必要があります。この関数は、MutableListタイプの呼び出しを返す必要があり、MutableListは次のようになります。映画の種類



完全なコード

import com.example.retrofitmarvel.Model.Movie
import retrofit2.Call
import retrofit2.http.*

interface RetrofitServices {
    @GET("marvel")
    fun getMovieList(): Call<MutableList<Movie>>
}




5.共通



ここで、Commonフォルダーを作成する必要があります。このフォルダーにオブジェクトを配置してCommonと呼び、変数を作成してBASE_URLと呼びます。その中に、データを解析するためのリンクを配置する必要がありますが、データを受信するのはそこからであるため、最後のブランチは配置しません。 ..。retrofitServices変数を作成し、get()メソッドを使用して、RetrofitClientを割り当てます。その後、getClientメソッドとRetrofitServices :: class.javaパラメーターをRetrofitClientにネットワーク接続します。



完全なコード

import com.example.retrofitmarvel.Interface.RetrofitServices
import com.example.retrofitmarvel.Retrofit.RetrofitClient

object Common {
    private val BASE_URL = "https://www.simplifiedcoding.net/demos/"
    val retrofitService: RetrofitServices
        get() = RetrofitClient.getClient(BASE_URL).create(RetrofitServices::class.java)
}




6.レイアウト



activity_main.xmlに移動し、そこにRecyclerViewを追加します



XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerMovieList"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>




レイアウトフォルダで、ルート要素にitem_layoutを作成し、CardViewを指定します



item_layout
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardElevation="8dp"
    android:layout_margin="8dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="167dp">


        <ImageView
            android:id="@+id/image_movie"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/txt_name"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.238" />

        <TextView
            android:id="@+id/txt_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="192dp"
            android:layout_marginLeft="192dp"
            android:layout_marginTop="16dp"
            android:text="name"
            android:textColor="@android:color/black"
            android:textSize="20sp"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/txt_team"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="196dp"
            android:layout_marginLeft="196dp"
            android:layout_marginTop="8dp"
            android:text="team"
            android:textColor="@android:color/black"
            android:textSize="16sp"
            android:textStyle="normal"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/txt_name" />

        <TextView
            android:id="@+id/txt_createdby"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="184dp"
            android:layout_marginLeft="184dp"
            android:layout_marginTop="12dp"
            android:text="createdby"
            android:textColor="@android:color/black"
            android:textSize="18sp"
            android:textStyle="italic"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/txt_team" />


    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>




7.アダプター



今、私たちは私たちは、クラスを入れているアダプタのパッケージを作成し、MyMovieAdapterそれを呼び出す必要があり

アダプタは、このデータに基づいてオブジェクトデータセットからデータを取得するため、Viewを作成する責任があります。



MyMovieAdapterクラスでは、このクラスでのみ使用できる変数を作成します。privateval movieList:MovieタイプのMutableListで、戻り値のタイプを指定します。MyMovieAdapter.MyViewHolderタイプのRecyclerView.Adapter



メソッド、つまりonCreateViewHolder、getItemCount、onBindViewHolderを実装します。

MyViewHolderクラスを作成します。このクラスでは、itemView:Viewパラメーターと戻りタイプRecyclerView.ViewHolderを指定し、このクラスの本体に変数​​を配置します。次に例を示します。



val image:ImageView = itemView.image_movie image_movieはitem_layoutから描画される

ため、残りのすべてのビューアイテムに指定します。



listItem:Movieパラメーターを使用してバインド関数を作成しましょう。ここでは、ビューアイテムをクリック可能にすることができます。これは可能だと思います。



次に、getItemCount()を書き直して、fun getItemCount()= movieList.sizeをオーバーライドします。ここではすべてが単純です。関数を作成してmovieList.sizeを返します。グレート、すべてのことに変わりはonBindViewHolderとonCreateViewHolderに対処するためである



onCreateViewHolder - RecyclerViewがそれを必要とするたびに新しいViewHolderオブジェクトを作成します。



onBindViewHolder -ViewHolderオブジェクトを受け取り、ビューコンポーネントの対応する行に必要なデータを設定します



次に、onCreateViewHolderリターンタイプMyViewHolderのケースを分析します。

itemView変数を作成し、LayoutInflater.from(parent.context).inflate(R.layout.item_layout、parent、false)を割り当て、itemViewパラメーターを指定してMyViewHolderを返します。次に、本体のonBindViewHolderに移動して、変数listItem:Movieを作成し、movieList [position]を割り当てます。次に、listItemパラメーターを指定したbindメソッドをholder'yにアタッチします。次に、Picassoライブラリを使用します。



Picasso.get()。Load(movieList [position] .imageurl).into(holder.image)。次に、holder.txt_name.text = movieList [position] .nameを追加します。これが、すべてのビュー要素の処理方法です。



完全なコード

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.example.retrofitmarvel.Model.Movie
import com.example.retrofitmarvel.R
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.item_layout.view.*

class MyMovieAdapter(private val context: Context,private val movieList: MutableList<Movie>):RecyclerView.Adapter<MyMovieAdapter.MyViewHolder>() {

    class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
        val image: ImageView = itemView.image_movie
        val txt_name: TextView = itemView.txt_name
        val txt_team: TextView = itemView.txt_team
        val txt_createdby: TextView = itemView.txt_createdby

        fun bind(listItem: Movie) {
            image.setOnClickListener {
                Toast.makeText(it.context, "  ${itemView.image_movie}", Toast.LENGTH_SHORT)
                    .show()
            }
            itemView.setOnClickListener {
                Toast.makeText(it.context, "  ${itemView.txt_name.text}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
        return MyViewHolder(itemView)
    }

    override fun getItemCount() = movieList.size

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val listItem = movieList[position]
        holder.bind(listItem)

        Picasso.get().load(movieList[position].imageurl).into(holder.image)
        holder.txt_name.text = movieList[position].name
        holder.txt_team.text = movieList[position].team
        holder.txt_createdby.text = movieList[position].createdby
    }

}





8. MainActivity



優れた!少しだけ残しました。まずMainActivityに移動し、変数を作成します。null型で宣言しないように、lateinit var mService:RetrofitServicesで宣言します。さらに、LinearLayoutManager、MyMovieAdapter、AlertDialogの3つを作成する必要があります。あなたはそれらを好きなように呼ぶことができます、それは問題ではありません。 onCreateメソッドで、Common.retrofitServicesをRetrofitServicesに割り当てます。次の行で、setHasFixedSize(true)をrecyclerViewにアタッチします。このメソッドのおかげで、リストを最適化してから、LinearLayoutManager(this)をlayoutManagerに割り当てます。



レイアウトマネージャー-これは、ユーザーに表示されなくなったViewコンポーネントの配置を担当するものです。さらに、すべてがリストlayoutManagerに添付するのと同じくらい簡単で、すでにlayoutManagerをこれに割り当てています。 OK、SpotsDialogライブラリを使用しています。以前に名前を付けた変数をAlertDialogタイプで指定し、SpotsDialogを割り当てます。その後、Builderメソッドをアタッチします。その後、これにtrueパラメーターを指定してsetCancelablecメソッドをアタッチします。これに、thisパラメーターを指定してsetContextメソッドをアタッチし、buildメソッドをアタッチする必要があります。



次に、関数getAllMovieListと呼ばれるonCreateメソッドの外部に新しい関数を作成する必要があります。この関数の本体で、ダイアログを指定してそれにshow()メソッドをアタッチしてから

、getMovieListメソッドをmService .enqueueに追加する必要があります(オブジェクト:Callback <MutableList> {)



ここで、メソッドを実装する必要があります。onResponseonFailureの2つと、onResponseにあります

。つまり、このメソッドの本体に、adapter'yに割り当てます。



MyMovieAdapter(baseContext, response.body() as MutableList<Movie>)


さらにadapter'yに、notifyDataSetChanged()メソッドを割り当てます。リストに、アダプターを接続してアダプターを割り当てます。次に、dismiss()メソッドをdialogに割り当てます。これは、データがロードされた後、ダイアログが消えることを意味します。



完全なコード

import android.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.retrofitmarvel.Adapter.MyMovieAdapter
import com.example.retrofitmarvel.Common.Common
import com.example.retrofitmarvel.Interface.RetrofitServices
import com.example.retrofitmarvel.Model.Movie
import com.example.retrofitmarvel.R

import dmax.dialog.SpotsDialog
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MainActivity : AppCompatActivity() {

    lateinit var mService: RetrofitServices
    lateinit var layoutManager: LinearLayoutManager
    lateinit var adapter: MyMovieAdapter
    lateinit var dialog: AlertDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mService = Common.retrofitService
        recyclerMovieList.setHasFixedSize(true)
        layoutManager = LinearLayoutManager(this)
        recyclerMovieList.layoutManager = layoutManager
        dialog = SpotsDialog.Builder().setCancelable(true).setContext(this).build()

        getAllMovieList()
    }

    private fun getAllMovieList() {
        dialog.show()
        mService.getMovieList().enqueue(object : Callback<MutableList<Movie>> {
            override fun onFailure(call: Call<MutableList<Movie>>, t: Throwable) {

            }

            override fun onResponse(call: Call<MutableList<Movie>>, response: Response<MutableList<Movie>>) {
                adapter = MyMovieAdapter(baseContext, response.body() as MutableList<Movie>)
                adapter.notifyDataSetChanged()
                recyclerMovieList.adapter = adapter

                dialog.dismiss()
            }
        })
    }
}




優れた!この記事では、Retrofit2を操作してRecyclerViewに配置する方法を学びました。



All Articles