教學

Kotlin Android Gson

Gson

序列化Java物件變JSON字串,或反序列化JSON字串成Java物件

Gson與RecyclerView與Glide與Anko的搭配
解析出來的需要自訂List存起來Gson裡需要加入TypeToken
{"account":"jack","date":"20160501","amount":1500,"type":0},
{"account":"jack","date":"20160501","amount":6000,"type":0},
{"account":"jack","date":"20160502","amount":3000,"type":1},
{"account":"jack","date":"20160501","amount":2000,"type":0},
{"account":"jack","date":"20160501","amount":1000,"type":1}

1.Gradle導入函示庫

implementation 'com.google.code.gson:gson:2.8.5'
implementation "org.jetbrains.anko:anko:0.10.8"
implementation 'com.github.bumptech.glide:glide:4.9.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'

2.先創建JSON抓下來的JavaBean

可以去載外掛
file>Settings>Plugins>JSON To Kotlin Class>重啟Android Studio
使用
Alt + Insert
 
data class NewsApi(
    val articles: List<Article>,
    val status: String,
    val totalResults: Int
)

data class Article(
    val author: String,
    val content: Any,
    val description: String,
    val publishedAt: String,
    val source: Source,
    val title: String,
    val url: String,
    val urlToImage: String
)

data class Source(
    val id: Any,
    val name: String
)

3.利用Gson解析JSON

val myURL = "https://newsapi.org/v2/top-headlines?country=tw&apiKey=a43a0c3447c448b795632938f18f13f6"
doAsync {
            val json = URL(myURL).readText()
            val newsApi = Gson().fromJson<NewsApi>(json, NewsApi::class.java)
            uiThread {
                recycler.adapter = ArticleAdapter(newsApi.articles)
            }
        }

4.配合RecyclerView 創建ViewHolder

recycler.apply {
            setHasFixedSize(true)
            layoutManager = LinearLayoutManager(this@MainActivity)
        }
		
class ArticleHolder(view: View) : RecyclerView.ViewHolder(view) {
        val image = view.article_image
        val title = view.article_title
    }

5.創建Adapter

inner class ArticleAdapter(val articles: List<Article>) : RecyclerView.Adapter<ArticleHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleHolder {
            return ArticleHolder(layoutInflater.inflate(R.layout.row_article, parent, false))
        }

        override fun getItemCount(): Int {
            return articles.size
        }

        override fun onBindViewHolder(holder: ArticleHolder, position: Int) {
            val article = articles.get(position)
            holder.title.text = article.title

            if (article.urlToImage != null) {
                Glide.with(holder.itemView.context)
                    .load(article.urlToImage)
                    .override(150, 120)
                    .into(holder.image)
            } else {
                Glide.with(holder.itemView.context)
                    .load("https://www.bomb01.com/upload/news/original/c95e0d21eda50ebc16d5f8ef568f60a7.png")
                    .override(150, 500)
                    .into(holder.image)
            }

            holder.itemView.setOnClickListener {
                val intent = Intent(this@MainActivity, WebActivity::class.java)
                intent.putExtra("URL", article.url)
                startActivity(intent)
            }
        }
    }

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *