How can I display Recycler view in Fragment?

Asked 2 years ago, Updated 2 years ago, 173 views

Hello~~ I'm a beginner who just started learning how to make an app..

The app I'm planning is composed of several fragments in one MainActivity. I'm stuck in thinking of one of the Fragments, UserFragments, so I'm asking you a question ㅠ<

Two Fragments were positioned as Viewpager inside the User Fragment. The problem is, I want to configure View plants Fragment as Recyclerview, but layout is applied (checked with background color), but recyclerview is not displayed (error name: /RecyclerView: No adapter attached; sliding layout).

Note that it works by applying Recyclerview to the UserFragment layout rather than the ViewplantFragment layout with the same code.

I've been struggling with this issue for days crying How can I display Recycler view in Fragment? I look forward to hearing from you. Thank you.

UserFragment.kt

class UserFragment : Fragment() {

    var fragmentView: View? = null

    var firestore: FirebaseFirestore? = null
    var currentUserUid: String? = null 
    var uid: String? = null /
    var auth: FirebaseAuth? = = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        currentUserUid = FirebaseAuth.getInstance().currentUser?.uid
        auth = FirebaseAuth.getInstance()
        uid = arguments?.getString("destinationUid")
        firestore = FirebaseFirestore.getInstance()


        fragmentView = inflater.inflate(R.layout.fragment_user, container, false)

        return fragmentView
    }


//Apply viewpager adapter
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        user_content_viewpager.adapter = UserMainAdapter
        user_content_viewpager.offscreenPageLimit = 1

        setOnClickListener()


    }

    <-- setOnClickListener omitted -->

}

ViewplantsFragment.kt (One of two Fragments to be applied to Viewpager. Located inside UserFragment)

class ViewplantsFragment : Fragment() {
    var fragmentplantsView: View? = null
    var firestore: FirebaseFirestore? = null
    var uid: String? = null 
    var auth: FirebaseAuth? = = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        firestore = FirebaseFirestore.getInstance()
        uid = UserFragment().arguments?.getString("destinationUid")
        auth = FirebaseAuth.getInstance()


        fragmentplantsView = inflater.inflate(R.layout.fragment_viewplants, container, false)
        fragmentplantsView?.user_viewplants_recyclerview?.layoutManager = GridLayoutManager(activity!!, 3)
        fragmentplantsView?.user_viewplants_recyclerview?.adapter = ViewplantsFragmentRecyclerViewAdapter()

        return fragmentplantsView
    }

//Code for displaying recyclerview in this fragment
    inner class ViewplantsFragmentRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        //import from database
        var contentDTOs: ArrayList<ContentDTO>

        init {
            contentDTOs = ArrayList()
            firestore?.collection("images")?.whereEqualTo("uid", uid)
                ?.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
                    if (querySnapshot == null) return@addSnapshotListener
                    for (snapshot in querySnapshot.documents) {
                        contentDTOs.add(snapshot.toObject(ContentDTO::class.java)!!)
                    }

                    //Post Counter Count
                    UserFragment().user_plants_count.text = contentDTOs.size.toString()
                    notifyDataSetChanged()
                }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {


            var width = resources.displayMetrics.widthPixels / 3 //Divided to match screen resolution
            var imageview = ImageView(parent.context)
            imageview.layoutParams = LinearLayoutCompat.LayoutParams(width, width)

            return CustomViewHolder(imageview)
        }


        private inner class CustomViewHolder(var imageview: ImageView) : RecyclerView.ViewHolder(imageview) {
        }

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

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            var imageview = (holder as CustomViewHolder).imageview
            Glide.with(holder.itemView.context).load(contentDTOs[position].imageUrl)
                .apply(RequestOptions().centerCrop()).into(imageview)
        }

    }
}

MainActivity.kt

class MainActivity : AppCompatActivity() ,BottomNavigationView.OnNavigationItemSelectedListener {

    override fun onNavigationItemSelected(item: MenuItem): Boolean {


        when (item.itemId) {

            <--Middle omitted-->

            R.id.action_mypage -> {
                my_toolbar.visibility = View.GONE

                var userFragment = UserFragment()

                var bundle = Bundle()
                var uid = FirebaseAuth.getInstance().currentUser?.uid
                bundle.putString("destinationUid",uid) //Apply user uid
                userFragment.arguments = bundle

                supportFragmentManager.beginTransaction().replace(R.id.main_content, userFragment).commit()


                return true
            }

        }
        return false
    }

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

        main_bottom_navigation.setOnNavigationItemSelectedListener(this)

        //Authorize Photo Storage
        ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE), 1)

        main_bottom_navigation.selectedItemId = R.id.action_home


    }

kotlin recyclerview fragment android android-studio

2022-09-22 19:46

1 Answers

Looking at the View plants Fragment, you are referring to recyclerView at the time of onCreateView, but it seems that initialization of the recyclerView has not progressed at this time. In that state, the user_viewplants_recyclerview will be null, so the adapter or layoutmanager setting probably didn't work, so I think it's better to spit out the error that there is no adapter. Please try setting up user_viewplants_recyclerview in onViewCreated.


2022-09-22 19:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.