I am trying to make a storytelling application that lets you see other’s post, taken from a dummy API, but i just can’t get the recyclerview list to work, as it only ever give me error, saying the adapter is not attached. Here are the codes for MainActivity.
package com.example.makemystory.view.main
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.View
import android.view.WindowInsets
import android.view.WindowManager
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.makemystory.R
import com.example.makemystory.data.helper.ViewModelFactory
import com.example.makemystory.data.network.StoryResponse
import com.example.makemystory.view.welcome.WelcomeActivity
import com.example.makemystory.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private val viewModel by viewModels<MainViewModel> {
ViewModelFactory.getInstance(this)
}
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setTitle("Make my Story")
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
val layoutManager = LinearLayoutManager(this)
binding.rvStory.layoutManager = layoutManager
val itemDecoration = DividerItemDecoration(this, layoutManager.orientation)
binding.rvStory.addItemDecoration(itemDecoration)
viewModel.stories.observe(this) {storyResponse ->
setStoryData(storyResponse)
}
viewModel.isLoading.observe(this) {
showLoading(it)
}
viewModel.getSession().observe(this) { user ->
if (!user.isLogin) {
startActivity(Intent(this, WelcomeActivity::class.java))
finish()
} else {
viewModel.getStories()
}
}
setupView()
}
private fun setStoryData(storyResponse: StoryResponse) {
val consumerStory = storyResponse.listStory
val adapter = StoryAdapter()
adapter.submitList(consumerStory)
binding.rvStory.adapter = adapter
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return super.onCreateOptionsMenu(menu)
}
private fun setupView() {
@Suppress("DEPRECATION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.hide(WindowInsets.Type.statusBars())
} else {
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
}
supportActionBar?.hide()
}
private fun showLoading(isLoading: Boolean) {
binding.progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
}
}
here is the ViewModel
package com.example.makemystory.view.main
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.example.makemystory.data.pref.UserModel
import com.example.makemystory.data.helper.UserRepository
import com.example.makemystory.data.network.ErrorResponse
import com.example.makemystory.data.network.StoryResponse
import com.google.gson.Gson
import kotlinx.coroutines.launch
import retrofit2.HttpException
class MainViewModel(private val repository: UserRepository) : ViewModel() {
private val _stories = MutableLiveData<StoryResponse>()
val stories: LiveData<StoryResponse> = _stories
private val _isLoading = MutableLiveData<Boolean>()
val isLoading: LiveData<Boolean> = _isLoading
fun getStories() {
viewModelScope.launch {
_isLoading.value = true
try {
val response = repository.getStories()
_stories.value = response
} catch (e: HttpException) {
val errorBody = e.response()?.errorBody()?.string()
if (errorBody != null && errorBody.startsWith("<html>")) {
handleError("JSON not found, instead HTML was found.")
} else {
val errorResponse = Gson().fromJson(errorBody, ErrorResponse::class.java)
val errorMessage = errorResponse?.message ?: "Unknown error"
handleError(errorMessage)
}
} catch (e: Exception) {
handleError("An error occurred: ${e.message}")
} finally {
_isLoading.value = false
}
}
}
private fun handleError(errorMessage: String) {
_stories.value = StoryResponse(error = true, message = errorMessage)
}
fun getSession(): LiveData<UserModel> {
return repository.getSession().asLiveData()
}
fun logout() {
viewModelScope.launch {
repository.logout()
}
}
}
and here is the Adapter
`package com.example.makemystory.view.main
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.makemystory.data.network.ListStoryItem
import com.example.makemystory.databinding.ItemStoryBinding
class StoryAdapter : ListAdapter<ListStoryItem, StoryAdapter.MyViewHolder>(DIFF_CALLBACK) {
class MyViewHolder (val binding: ItemStoryBinding) : RecyclerView.ViewHolder(binding.root){
fun bind(story: ListStoryItem) {
binding.tvTitle.text = story.name
binding.tvDescription.text = story.description
Glide.with(binding.root.context)
.load(story.photoUrl)
.into(binding.ivItem)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val binding = ItemStoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MyViewHolder(binding)
}
companion object{
val DIFF_CALLBACK = object : DiffUtil.ItemCallback<ListStoryItem>() {
override fun areItemsTheSame(oldItem: ListStoryItem, newItem: ListStoryItem): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: ListStoryItem, newItem: ListStoryItem): Boolean {
return oldItem == newItem
}
}
}
}
I would appreciate any helps or insights, further need of more codes are open and i am always gonna be willing to take give more codes if the ones above are not enough!
I tried so many things, i even tried using chatgpt but nothing just seem to work, im at my wits end, what i expected to happen was, after logging in, the api is gonna get the token from my account, uses it to get datas from it, and come back bringing datas for the app to show on a recyclerview, but what actually happened was just white screen.
Aruvin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.