Paul Guerrero
Paul Guerrero

Reputation: 65

Kotlin recyclerview on Fragment

Im trying to show a recyclerview of a list that is fed by a volley api request on a fragment but cant and everytime it returns this error "lateinit property tareas view has not been initialized fragment",

I tried using findviewbyid to declare the recyclerview it results in "unresolved reference"

Here is the code of the fragment:

private lateinit var prefs: SharedPreferences
//private lateinit var tareaAdapter: TareaAdapter
private lateinit var viewOfLayout: View
private var listener: OnFragmentInteractionListener? = null
private lateinit  var recyclerView: RecyclerView
private lateinit var tareas: ArrayList<Tarea>

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    viewOfLayout = inflater!!.inflate(R.layout.fragment_tareas_generales, container, false)
    prefs = PreferenceManager.getDefaultSharedPreferences(activity!!.applicationContext)

    val recyclerView = viewOfLayout.findViewById<RecyclerView>(R.id.rvGeneralTareas)
    recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(
        [email protected]!!,
        LinearLayout.VERTICAL,
        false
    )
    getTareaGenerales()
    val adapter = TareaAdapter(tareas)
    recyclerView.adapter = adapter
    return inflater.inflate(R.layout.fragment_tareas_generales, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
}

private fun getTareaGenerales() {
    val recyclerView = viewOfLayout.findViewById<RecyclerView>(R.id.rvGeneralTareas)
    if (!NetworkUtils.isConnected([email protected]!!)) {
        Toast.makeText([email protected]!!, R.string.error_internet2, 
     Toast.LENGTH_LONG).show()
    } else {
        val queue = Volley.newRequestQueue([email protected]!!)
        val URL = "${Utils.URL_SERVER}guardias/tareas"
        val stringRequest = object : StringRequest(Method.GET, URL, Response.Listener<String> { 
           response ->
            try {
                var strResp = response.toString()
                val jsonObj: JSONObject = JSONObject(strResp)
                val jsonArray = jsonObj.getJSONArray("tareas")

                Log.d("paso","Connected to tareas generales $strResp")

                for (i in 0 until jsonArray.length()) {
                    var jsonInner: JSONObject = jsonArray.getJSONObject(i)
                    val id_tarea = jsonInner.get("id_tarea").toString().toInt()
                    val descripcion = jsonInner.get("descripcion").toString()
                    Log.d("add","$id_tarea,$descripcion")
                    tareas.add(Tarea(id_tarea,descripcion))
                }
                val adapter = TareaAdapter(tareas)
                recyclerView.adapter = adapter
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText([email protected]!!, resources.getString(R.string.error_general), Toast.LENGTH_LONG).show()
            }
        }, Response.ErrorListener { error ->
            try {
                error.printStackTrace()
                Toast.makeText([email protected]!!, JSONObject(String(error.networkResponse.data)).getString("message"), Toast.LENGTH_LONG).show()
            } catch (e: Exception) {
                Toast.makeText([email protected]!!, resources.getString(R.string.error_general), Toast.LENGTH_LONG).show()
            }
        }) {
            override fun getHeaders(): MutableMap<String, String> {
                val headers = HashMap<String, String>()
                headers.put("token", prefs.getString("api_key", "")!!)
                return headers
            }
        }
        stringRequest.retryPolicy = DefaultRetryPolicy(180000, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
        queue.add(stringRequest)
    }
}

companion object {
    fun newInstance(): TareasGeneralesFragment {
        return TareasGeneralesFragment()
    }
}

Upvotes: 0

Views: 1848

Answers (1)

mlthlschr
mlthlschr

Reputation: 174

I guess it is connected to the fact, that you are inflating your view twice. First of all you inflate it within onCreateView to viewOfLayout, then you are returning inflater.inflate(R.layout.fragment_tareas_generales, container, false). I guess all your changes within onCreateView are null and void as soon as you are returning a newly inflated view.

  • Why are you not using the kotlin view binding? It is quite convenient.
  • if you would, you could simply use the ids of your recyclerView as stated in the layout you are using (R.layout.fragment_tareas_generales)
  • maybe you should try to do all the view layout and adapter stuff in onViewCreated

Upvotes: 1

Related Questions