Home > Software design >  I cant refrence the adapter
I cant refrence the adapter

Time:05-24

I have an adaptor that I initiate in onCreate and a listview that I initiate in onViewCreated I'm trying to setAdapter but I can't pass the adapter in onViewCreated. Ive tried multiple things like moving them from onCreate in onViewCreated but it seems that the app crashes if I initialize the adapter anywhere else and I cant use findViewById anywhere but in onViewCreated

class Istoric : Fragment() {
    var array= arrayOf("item1","item2")



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val adapter = ArrayAdapter(MainActivity(),R.layout.listview_item,array)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_istoric, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val lv1: ListView = view.findViewById(R.id.lv)
        lv1.setAdapter(adapter)
    }
}

CodePudding user response:

Your adapter object is a local variable to onCreate(...) so it cannot be accessed elsewhere. You can move it to a class variable like this:

class Istoric : Fragment() {
    var array= arrayOf("item1","item2")

    private lateinit var adapter: ArrayAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        adapter = ArrayAdapter(requireContext(), R.layout.listview_item, array)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_istoric, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val lv1: ListView = view.findViewById(R.id.lv)
        lv1.setAdapter(adapter)
    }
}

I also added the requireContext() call to your ArrayAdapter constructor since you don't want to create a new instance of your MainActivity there.

  • Related