У меня почему-то не работает RecyclerView. Скорее всего это связано с какими-то особенностями при работе из фрагмента, потому что у меня больше нет идей.
Я специально распарсил ArrayList в TextView, чтобы убедиться что не передаю пустой лист пустой. Ошибка все таки была, но и после ее отладки ничего не заработало. После этого заменил свой адаптер на 100% рабочий код с ютуба, чтобы исключить свои возможные ошибки. Но все равно Recycler оставался пустой.
Итого: я не знаю, в чем ошибка. Буду благодарен за любую помощь!
Код получения и передачи листа тексту (test()) и ресайклеру (inflateRecycler()):
override fun onResume() {
super.onResume()
val accessToken = activity?.getSharedPreferences(PREFFILE_AUTH, MODE_PRIVATE)
?.getString(PREFNAME_ACCESS_TOKEN, "")
val handler = CoroutineExceptionHandler { _, _ ->
CoroutineScope(Dispatchers.IO).launch {
withContext(Dispatchers.Main) {
errorRoot.visibility = View.VISIBLE
test.visibility = View.GONE
messagesProgress.visibility = View.GONE
messagesRefresh.visibility = View.VISIBLE
}
}
}
CoroutineScope(Dispatchers.IO).launch(handler) {
val responseCoroutine = async {
val requestResponse = getConversations().getRequest(accessToken!!, false)
return@async CallToVK().call(requestResponse)
}
val response = responseCoroutine.await()
val parsedResponseCoroutine = async {
return@async getConversations().parseResponse(
response,
activity?.applicationContext!!
)
}
val parsedResponse = parsedResponseCoroutine.await()
withContext(Dispatchers.Main) {
test(parsedResponse)
inateRecycler(parsedResponse)
}
}
messagesRefresh.setOnClickListener {
errorRoot.visibility = View.GONE
test.visibility = View.VISIBLE
messagesProgress.visibility = View.VISIBLE
messagesRefresh.visibility = View.GONE
CoroutineScope(Dispatchers.IO).launch(handler) {
val responseCoroutine = async {
val requestResponse = getConversations().getRequest(accessToken!!, false)
return@async CallToVK().call(requestResponse)
}
val response = responseCoroutine.await()
val parsedResponseCoroutine = async {
return@async getConversations().parseResponse(
response,
activity?.applicationContext!!
)
}
val parsedResponse = parsedResponseCoroutine.await()
withContext(Dispatchers.Main) {
test(parsedResponse)
inflateRecycler(parsedResponse)
}
}
}
}
fun test(array: ArrayList<MessagesListModel>) {
var text = ""
for (i in 0 until array.size) {
text += "title: " + array[i].title + "\nphoto: " + array[i].photo + "\npreview: " + array[i].preview + "\n"
if (array[i].hasUnread) {
text += "countUnread: " + array[i].countUnread + "\n"
if (array[i].mutedUnread) {
text += "mutedUnread: true\n"
} else {
text += "mutedUnread: false\n"
}
}
if (array[i].online == 1) {
text += "online: desktop\n"
} else if (array[i].online == 2) {
text += "online: mobile\n"
}
text += "\n"
}
test.text = text
messagesProgress.visibility = View.GONE
}
fun inflateRecycler(gotList: ArrayList<MessagesListModel>) {
recyclerMessages.adapter = CommonMessagesAdapter(gotList)
recyclerMessages.layoutManager = LinearLayoutManager(activity?.applicationContext)
recyclerMessages.setHasFixedSize(true)
}
Код Adapter'a:
class CommonMessagesAdapter (array: ArrayList<MessagesListModel>): RecyclerView.Adapter<CommonMessagesAdapter.CommonMessagesViewHolder>() {
var list = array
class CommonMessagesViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val photo: ImageView = itemView.profilePhoto
val title: TextView = itemView.textName
val preview: TextView = itemView.textPreview
val unread: TextView = itemView.textUnreadCount
val unreadMuted: TextView = itemView.textUnreadMutedCount
val online: ImageView = itemView.onlineIcon
val onlineParent: FrameLayout = itemView.onlineBg
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommonMessagesViewHolder {
return CommonMessagesViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_message_list_item,
parent, false))
}
override fun onBindViewHolder(holder: CommonMessagesViewHolder, position: Int) {
val item = list[position]
holder.title.text = item.title
holder.preview.text = item.preview
holder.photo.load(item.photo) {
crossfade(true)
placeholder(R.drawable.profile_placeholder)
error(R.drawable.profile_placeholder)
}
if (item.hasUnread) {
if (item.mutedUnread) {
holder.unreadMuted.visibility = View.VISIBLE
holder.unreadMuted.text = item.countUnread
} else {
holder.unread.visibility = View.VISIBLE
holder.unread.text = item.countUnread
}
}
if (item.online == 1) {
holder.onlineParent.visibility = View.VISIBLE
} else if (item.online == 2) {
holder.onlineParent.visibility = View.VISIBLE
holder.online.setImageResource(R.drawable.ic_online_mobile_12)
}
}
override fun getItemCount(): Int = list.size
fun commonSetList (al: ArrayList<MessagesListModel>) {
this.list = al
notifyDataSetChanged()
}
}
Если нужно еще что-то - скину. Заранее спасибо!
Дополнение: разметка:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="@color/fui_white">
<TextView
android:id="@+id/toolbarTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/messages_messages"
android:textColor="@color/fui_black"
android:textSize="24dp"
android:textStyle="bold" />
<FrameLayout
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="16dp">
<ProgressBar
android:id="@+id/messagesProgress"
style="?android:attr/progressBarStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<ImageView
android:id="@+id/messagesRefresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?selectableItemBackgroundBorderless"
android:src="@drawable/ic_refresh_outline_28"
android:tint="?colorPrimary"
android:visibility="gone" />
</FrameLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_alignParentBottom="true"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:background="#dfdfdf" />
</RelativeLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Loading..."
android:textColor="@color/fui_dark_grey" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone"
android:id="@+id/errorRoot">
<ImageView
android:layout_width="56dp"
android:layout_height="56dp"
android:src="@drawable/ic_error_outline_56"
android:tint="@color/fui_red" />
<TextView
android:id="@+id/errorMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/messages_error_loading"
android:textColor="@color/fui_black"
android:textSize="16dp" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerMessages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
xmlns:tools="http://schemas.android.com/tools"
tools:listitem="@layout/view_message_list_item"/>
Решение: В моем случае оказалось, что ресайклеру просто не хватало места для отображения, а код был правильным. Если на примере моей разметки: сверху над ресайклером есть TextView, который позже (в функции test() становится гораздо массивнее, чем просто "Loading..." и загромождает весь фрагмент, а значит у ресайклера не остается места для отображения. Надеюсь, кому-то поможет моя ошибка.