So, when i make a post request to my api, it run the onFailure fun. The logcat doesn't give an error. Why is that? Im new to android studio.
Can you help me? Thanks!
Where i send the POST: http://localhost:3000/test
Response (Request sent with postman):
{
"cso": "kobasz!"
}
Heres my code:
Main activity:
package com.alms.chatenium
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import retrofit2.Call
import retrofit2.Callback
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.testbtn)
val textView = findViewById<TextView>(R.id.textView)
button.setOnClickListener{
Toast.makeText(this#MainActivity, "TEST", Toast.LENGTH_SHORT).show()
val retrofit = ServiceBuilder.buildService(APIInterface::class.java)
val obj = RequestModel("djalms")
retrofit.requestTest(obj).enqueue(
object:Callback<Response>{
override fun onResponse(
call: Call<Response>,
response: retrofit2.Response<Response>
) {
textView.text = response.body()?.cso.toString()
}
override fun onFailure(call: Call<Response>, t: Throwable) {
textView.text = "Fail!"
}
}
)
}
}
}
Interface:
package com.alms.chatenium
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST
interface APIInterface {
#POST("test")
fun requestTest(#Body requestModel: RequestModel): Call<Response>
}
Request model:
package com.alms.chatenium
data class RequestModel(
val username: String
)
Response model:
package com.alms.chatenium
class Response (
val cso: String
)
Service builder:
package com.alms.chatenium
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ServiceBuilder {
private val client = OkHttpClient.Builder().build()
private val retrofit = Retrofit.Builder()
.baseUrl("http://localhost:3000/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
fun<T> buildService(service: Class<T>): T{
return retrofit.create(service)
}
}
API tested with postman, and verified, that the api (NestJS) working.
Related
sorry for the inconvenience, but this is my first time trying this. I've been trying on doing this app which it has a recyclerView which I intent it to open a chrome page. The thing is, I'm not able to implement the itemOnClickListener despite having tried a lot of videos. Could you point out where is my mistake?
My Adapter:
package com.example.practica1.adapter
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 androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.practica1.R
import com.example.practica1.data.Video
class MainAdapter(private val context: Context, private val videos: List<Video>): RecyclerView.Adapter<MainAdapter.ViewHolder>(){
private lateinit var mListener: onItemClickListener
interface onItemClickListener{
fun onItemClick(position: Int)
}
fun setOnClickListener(listener: onItemClickListener){
mListener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cartoon, parent, false)
return ViewHolder(view, mListener)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val video = videos[position]
holder.title.text = video.data.short_title
holder.serieTitle.text = video.data.show.title
holder.durationTitle.text = video.data.video.duration + " seg"
Glide.with(context)
.load(video.data.imagepath)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.override(400, 400)
.centerCrop()
.into(holder.imagePrev)
}
override fun getItemCount() = videos.size
inner class ViewHolder(itemView: View, listener: onItemClickListener) : RecyclerView.ViewHolder(itemView){
val title: TextView = itemView.findViewById(R.id.videoTitle)
val serieTitle: TextView = itemView.findViewById(R.id.serieTitle)
val durationTitle: TextView = itemView.findViewById(R.id.durationTitle)
val imagePrev: ImageView = itemView.findViewById(R.id.photoPreview)
init{
itemView.setOnClickListener{
listener.onItemClick(adapterPosition)
}
}
}
}
The fragment in which I tried to implement the method:
package com.example.practica1.fragments
import android.os.Bundle
import android.util.Log
import android.util.Log.d
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.example.practica1.R
import com.example.practica1.adapter.MainAdapter
import com.example.practica1.data.ApiInterface
import com.example.practica1.data.Video
import com.example.practica1.databinding.FragmentMenuBinding
import com.haerul.bottomfluxdialog.BottomFluxDialog
import com.haerul.bottomfluxdialog.BottomFluxDialog.OnInputListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MenuFragment : Fragment() {
private var _binding: FragmentMenuBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentMenuBinding.inflate(inflater, container, false)
val view = inflater.inflate(R.layout.fragment_menu, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val retrofit = Retrofit.Builder()
.baseUrl("https://www.cartoonnetwork.com.co")
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(ApiInterface::class.java)
showProgress()
api.fetchAllVideos().enqueue(object : Callback<List<Video>> {
override fun onResponse(call: Call<List<Video>>, response: Response<List<Video>>) {
if (response.isSuccessful()) {
d("daniel", "onResponse ${response.body()!![0].id}")
if (response.body()!!.size > 0) {
showData(response.body()!!)
getResult(true, "Sucess")
} else
getResult(false, response.message())
hideProgress()
}
}
override fun onFailure(call: Call<List<Video>>, t: Throwable) {
d("daniel", "onFailure")
getResult(false, "Request Timeout. Please Try Again!")
hideProgress()
}
})
binding.search.setOnClickListener { v -> showDialog(v) }
}
fun showData(videos: List<Video>){
val test: RecyclerView = requireActivity().findViewById(R.id.recycler_viewMenu)
var adap = MainAdapter(requireContext(), videos)
test.apply{
adapter = adap
}
adap.setOnClickListener(object: MainAdapter.onItemClickListener{
override fun onItemClick(position: Int){
d("test", "test")
}
})
}
fun showProgress(){
binding.swipeRefresh.setRefreshing(true)
binding.emptyView.setVisibility(View.GONE)
binding.shimmer.startShimmer()
binding.shimmer.setVisibility(View.VISIBLE)
binding.recyclerViewMenu.setVisibility(View.GONE)
}
fun hideProgress(){
binding.swipeRefresh.setRefreshing(false)
binding.shimmer.stopShimmer()
binding.shimmer.setVisibility(View.GONE)
binding.recyclerViewMenu.setVisibility(View.VISIBLE)
}
fun getResult(status: Boolean, message: String){
if(!status) {
binding.emptyView.setVisibility(View.VISIBLE)
binding.textEmptyErr.setText(message)
}
else
binding.emptyView.setVisibility((View.GONE))
}
private fun showDialog(view: View){
BottomFluxDialog.inputDialog(requireActivity())
.setTextTitle("Input Title")
.setTextMessage("This is an input message")
.setRightButtonText("SUBMIT")
.setInputListener(object : OnInputListener {
override fun onSubmitInput(text: String?) {
val bundle = Bundle()
bundle.putString("search", text)
Navigation.findNavController(view)
.navigate(R.id.action_menuFragment_to_listFragment, bundle)
}
override fun onCancelInput() {}
})
.show()
}
}
Thanks!
There is no such common thin like OnItemClickListener for RecyclerView, so you have to design your own. It shouldn't be hard to implement by hand, though. What you can do, is that you can Just set OnClickListener to the whole item view and delegate it clicks to upper lambda.
class YourAdapter(
private val listener: (Video) -> Unit,
private val videos: List<Video>,
): ... {
...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
...
holder.itemView.setOnClickListener { v ->
if (position != RecyclerView.NO_POSITION) {
listener(videos[position])
}
}
}
}
There are no noticeable side-effects of swapping View.OnClickListener in onBindViewHolder() method.
Also, few suggestions:
Read about ListAdapterhere. Looks like it perfect fit for your usecase.
Use getAbsoluteAdapterPosition() instead of adapterPosition() method within ViewHolder, as adapters are designed to be combined. Read more about ConcatAdapter here.
You don't need to pass Context to adapter constructor. View already has context, so you can query context by calling viewHolder.itemView.context.
Make sure to use your binding. It looks like you creating your binding in MenuFragment, but later you are getting RecyclerView by id in an old-fashioned way.
Don't create adapters, that require data for creation. Instead, pass and update data as you requested from the backend. RecyclerView.Adapter is designed to be reused.
sorry for the inconvenience, but this is my first time trying this. I've been trying on doing this app which it has a recyclerView which I intent it to open a chrome page. The thing is, I'm not able to implement the itemOnClickListener despite having tried a lot of videos. Could you point out where is my mistake?
My Adapter:
package com.example.practica1.adapter
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 androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.practica1.R
import com.example.practica1.data.Video
class MainAdapter(private val context: Context, private val videos: List<Video>,
val listener: MyOnClickListener
): RecyclerView.Adapter<MainAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cartoon, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val video = videos[position]
holder.title.text = video.data.short_title
holder.serieTitle.text = video.data.show.title
holder.durationTitle.text = video.data.video.duration + " seg"
Glide.with(context)
.load(video.data.imagepath)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.override(400, 400)
.centerCrop()
.into(holder.imagePrev)
}
override fun getItemCount() = videos.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val title: TextView = itemView.findViewById(R.id.videoTitle)
val serieTitle: TextView = itemView.findViewById(R.id.serieTitle)
val durationTitle: TextView = itemView.findViewById(R.id.durationTitle)
val imagePrev: ImageView = itemView.findViewById(R.id.photoPreview)
init{
itemView.setOnClickListener{
val position = adapterPosition
listener.onClick(position)
}
}
}
interface MyOnClickListener{
fun onClick(position: Int)
}
}
The fragment in which I tried to implement the method (The toast message doesn't appear)
package com.example.practica1.fragments
import android.os.Bundle
import android.util.Log
import android.util.Log.d
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.example.practica1.R
import com.example.practica1.adapter.MainAdapter
import com.example.practica1.data.ApiInterface
import com.example.practica1.data.Video
import com.example.practica1.databinding.FragmentMenuBinding
import com.haerul.bottomfluxdialog.BottomFluxDialog
import com.haerul.bottomfluxdialog.BottomFluxDialog.OnInputListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MenuFragment : Fragment() {
private var _binding: FragmentMenuBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentMenuBinding.inflate(inflater, container, false)
val view = inflater.inflate(R.layout.fragment_menu, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val retrofit = Retrofit.Builder()
.baseUrl("https://www.cartoonnetwork.com.co")
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(ApiInterface::class.java)
showProgress()
api.fetchAllVideos().enqueue(object : Callback<List<Video>> {
override fun onResponse(call: Call<List<Video>>, response: Response<List<Video>>) {
if (response.isSuccessful()) {
d("daniel", "onResponse ${response.body()!![0].id}")
if (response.body()!!.size > 0) {
showData(response.body()!!)
getResult(true, "Sucess")
} else
getResult(false, response.message())
hideProgress()
}
}
override fun onFailure(call: Call<List<Video>>, t: Throwable) {
d("daniel", "onFailure")
getResult(false, "Request Timeout. Please Try Again!")
hideProgress()
}
})
binding.search.setOnClickListener { v -> showDialog(v) }
}
fun showData(videos: List<Video>){
val test: RecyclerView = requireActivity().findViewById(R.id.recycler_viewMenu)
test.apply{
adapter = MainAdapter(context, videos, object: MainAdapter.MyOnClickListener{
override fun onClick(position: Int) {
Toast.makeText(requireContext(), position, Toast.LENGTH_SHORT).show()
}
})
}
}
fun showProgress(){
binding.swipeRefresh.setRefreshing(true)
binding.emptyView.setVisibility(View.GONE)
binding.shimmer.startShimmer()
binding.shimmer.setVisibility(View.VISIBLE)
binding.recyclerViewMenu.setVisibility(View.GONE)
}
fun hideProgress(){
binding.swipeRefresh.setRefreshing(false)
binding.shimmer.stopShimmer()
binding.shimmer.setVisibility(View.GONE)
binding.recyclerViewMenu.setVisibility(View.VISIBLE)
}
fun getResult(status: Boolean, message: String){
if(!status) {
binding.emptyView.setVisibility(View.VISIBLE)
binding.textEmptyErr.setText(message)
}
else
binding.emptyView.setVisibility((View.GONE))
}
private fun showDialog(view: View){
BottomFluxDialog.inputDialog(requireActivity())
.setTextTitle("Input Title")
.setTextMessage("This is an input message")
.setRightButtonText("SUBMIT")
.setInputListener(object : OnInputListener {
override fun onSubmitInput(text: String?) {
val bundle = Bundle()
bundle.putString("search", text)
Navigation.findNavController(view)
.navigate(R.id.action_menuFragment_to_listFragment, bundle)
}
override fun onCancelInput() {}
})
.show()
}
}
Thanks!
If your data is showing in the recycler view and you are getting crash on item click than
replace this toast link :-
Toast.makeText(requireContext(), position, Toast.LENGTH_SHORT).show()
with this :-
Toast.makeText(requireContext(), "$position", Toast.LENGTH_SHORT).show()
or if your video list is not visible in recycler view than you need to implement layout manager in recycler view you can add it on xml or in code also.
I want to share variable : master between MainActivity to ListAdapter. Can you tell me how to do it ? I tried with bundles and a lot of things, but in the end I received errors.
Main Activity
package com.example.roomapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import androidx.navigation.ui.setupActionBarWithNavController
import com.example.roomapp.AESKnowledgeFcatory.decrypt
import com.example.roomapp.HashUtils.sha256
import com.example.roomapp.fragments.add.AddFragment
import kotlinx.android.synthetic.main.activitycreate.*
import kotlinx.android.synthetic.main.activitylogin.*
import kotlinx.android.synthetic.main.custom_row.*
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
class MainActivity : AppCompatActivity() {
var master: String = "0"
var checkLogin2: String = ""
var lf_ch = false
fun createMaster(v:View){
this.master = this.editmasterpass.text.toString()
val sharedPref = this.getPreferences(MODE_PRIVATE) ?:return
with (sharedPref.edit()){
putString("cheie",sha256(master))
commit()
}
val sharedPref2 = this.getPreferences(MODE_PRIVATE) ?: return
val defaultValue = sharedPref2.getString("cheie", "ABA")
System.out.println(" Key value = " + defaultValue)
setContentView(R.layout.activity_main)
}
fun checklogin(v: View)
{
this.checkLogin2 = this.editTextTextPassword.text.toString()
val castoras = this.getPreferences(MODE_PRIVATE)
val defaultValue2 = castoras.getString("cheie", "ABA")
if(sha256(this.checkLogin2)==defaultValue2.toString())
{
setContentView(R.layout.activity_main)
}
else {
textView3.text="Incorrect Password"
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val castoras = this.getPreferences(MODE_PRIVATE)
val defaultValue2 = castoras.getString("cheie", "key not found")
System.out.println("Abracanabra= "+defaultValue2.toString())
if ((defaultValue2.toString())=="key not found") {
setContentView(R.layout.activitycreate)
}
else {
setContentView((R.layout.activitylogin))
}
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.fragment)
return navController.navigateUp() || super.onSupportNavigateUp()
}
// cum sa pasam variabila master
}
ListAdapter
package com.example.roomapp.fragments.list
import android.app.PendingIntent.getActivity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.roomapp.AESKnowledgeFcatory.encrypt
import com.example.roomapp.R
import com.example.roomapp.data.User
import kotlinx.android.synthetic.main.custom_row.view.*
import android.content.SharedPreferences
import com.example.roomapp.MainActivity
class ListAdapter: RecyclerView.Adapter<ListAdapter.MyViewHolder>() {
private var userList = emptyList<User>()
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.custom_row, parent, false))
}
override fun getItemCount(): Int {
return userList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = userList[position]
holder.itemView.id_txt.text = currentItem.id.toString()
holder.itemView.firstName_txt.text = currentItem.firstName
// I want to use the master string here, master+currentItem.salt
holder.itemView.lastName_txt.text = encrypt(currentItem.lastName,currentItem.salt)
holder.itemView.salt_txt.text = currentItem.salt
}
fun setData(user: List<User>){
this.userList = user
notifyDataSetChanged()
}
}
I need a method that can pass me the "master" variable to ListAdapter, because I need to pass certain informations.
List fragment
package com.example.roomapp.fragments.list
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.roomapp.R
import com.example.roomapp.data.UserViewModel
import kotlinx.android.synthetic.main.fragment_list.view.*
class ListFragment() : Fragment() {
private lateinit var mUserViewModel: UserViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_list, container, false)
// Recyclerview
val adapter = ListAdapter()
val recyclerView = view.recyclerview
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(requireContext())
// UserViewModel
mUserViewModel = ViewModelProvider(this).get(UserViewModel::class.java)
mUserViewModel.readAllData.observe(viewLifecycleOwner, Observer { user ->
adapter.setData(user)
})
view.floatingActionButton.setOnClickListener {
findNavController().navigate(R.id.action_listFragment_to_addFragment)
}
return view
}
}
You can simply add a constructor parameter in your ListAdapter and pass the value of master string when creating the ListAdapter in MainActivity, this can be done as
class ListAdapter(private val master: String):
RecyclerView.Adapter<ListAdapter.MyViewHolder>()
and in your MainActivity, where you create object of ListAdapter, pass the value of master
listAdapter = ListAdapter(master)
Now you can use master in your ListAdapter as you like
basically i am trying to create a recycler view and this the main activity
i am getting error at
recyclerView.adapter = adapter
package com.example.newsorning
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView.layoutManager = LinearLayoutManager(this)
val items = fetchData()
val adapter = NewsListAdapter(items)
recyclerView.adapter = adapter
}
private fun fetchData():ArrayList<String>{
val list = ArrayList<String>()
for (i in 0 until 100){
list.add("item $i")
}
return list
}
}
this is where i created adpater
//newsListadapter
package com.example.newsorning
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
class NewsListAdapter(private val item:ArrayList<String>):
RecyclerView.Adapter<NewsViewHolder>() {
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): NewsViewHolder {
val view = LayoutInflater.from(p0.context).inflate(R.layout.item_news,p0,false)
return NewsViewHolder(view)
}
override fun getItemCount(): Int {
return item.size
}
override fun onBindViewHolder(p0: NewsViewHolder, p1: Int) {
val currentItem = item[p1]
p0.titleView.text = currentItem
}
}
class NewsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val titleView : TextView = itemView.findViewById(R.id.titleView)
}
This may be due to you using the old, deprecated support library RecyclerView (android.support.v7) instead of the Jetpack RecyclerView (androidx). Maybe one of the libraries you're using still uses the old support library, so it was in your namespace and you accidentally selected it when choosing which class to import. You need to change the line
import android.support.v7.widget.RecyclerView
to
import androidx.recyclerview.widget.RecyclerView
in both of these files. And you need to enable Jetifier according to these directions.
I am unable to use RecyclerView although I had created Adapter(RecyclerView) and ViewHolder(RecyclerView) so I tried using of ListView and it worked for me.
What should I do for converting ListView to RecyclerView?
package com.example.cryptotracker
import android.os.Bundle
import android.util.Log
import android.widget.Adapter
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var rf : Retrofit = Retrofit.Builder().baseUrl(RetroInterface.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build()
var API : RetroInterface = rf.create(RetroInterface::class.java)
var call:Call<List<Crypto?>?>? = API.posts
call?.enqueue(object :Callback<List<Crypto?>?>{
override fun onResponse(
call: Call<List<Crypto?>?>,
response: Response<List<Crypto?>?>
) {
var postList :List<Crypto>? = response.body() as List<Crypto>
var post : Array<String?> = arrayOfNulls<String>(postList!!.size)
for ( i in postList!!.indices)
post[i] = postList!![i]!!.name
var adapter = ArrayAdapter<String>(applicationContext,android.R.layout.simple_dropdown_item_1line,post)
listview.adapter = adapter
}
override fun onFailure(call: Call<List<Crypto?>?>, t: Throwable) {
TODO("Not yet implemented")
}
})
}
}
====================== Adapter & ViewHolder(RecyclerView) ===================
package com.example.cryptotracker
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 androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class CryptoAdapter(val context:Context, val crypto:List<Crypto> ):RecyclerView.Adapter<CryptoViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CryptoViewHolder {
val view:View = LayoutInflater.from(context).inflate(R.layout.item_crypto,parent,false)
return CryptoViewHolder(view)
}
override fun onBindViewHolder(holder: CryptoViewHolder, position: Int) {
val current_item:Crypto = crypto1[position]
holder.cryptoName.text = current_item.name
holder.cryptoId.text = current_item.exchange
holder.cryptoUrl.text = current_item.website
}
override fun getItemCount(): Int {
return crypto1.size
}
}
class CryptoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var cryptoName = itemView.findViewById<TextView>(R.id.cryptoName)
var cryptoId = itemView.findViewById<TextView>(R.id.cryptoExchangeId)
var cryptoUrl = itemView.findViewById<TextView>(R.id.cryptoUrl)
}
============================ Data class ===========================
package com.example.cryptotracker
data class Crypto (
val exchange_id:String,
val name:String,
val website:String,
)
Replace below lines :
var adapter = ArrayAdapter<String>(applicationContext,android.R.layout.simple_dropdown_item_1line,post)
listview.adapter = adapter
With this :
if(postList != null) {
var cryptoAdapter = CryptoAdapter(this#MainActivity,postList)
recyclerview.layoutManager = LinearLayoutManager(this#MainActivity)
recyclerview.adapter = cryptoAdapter
}
Also in CryptoAdapter.kt
override fun getItemCount(): Int {
return crypto.size
}