Home > Back-end >  error in fragment when i use FindViewById
error in fragment when i use FindViewById

Time:09-06

I'm trying to use fragments to not burden my application with too many activities. In my mainActivity there is a map, I then created a fragment where there are editText fields, I would like to use these editText to insert numbers to be used as parameters to pass to a function created in another class called navFun. I tried to write the code but I don't understand why I get these errors when using findViewById:

Unresolved reference: findViewById

this is my fragment code

package uk.co.lorenzopulcinelli.navigationdrawer

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import java.lang.Exception

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [CreatePathFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class CreatePathFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null


    val mainActivity: MainActivity = MainActivity()
    val navFun: NavFun = NavFun(mainActivity.context, mainActivity.mapView)

    private lateinit var editTextLatitudineP1: EditText
    private lateinit var editTextLongitudineP1: EditText
    private lateinit var editTextLatitudineP2: EditText
    private lateinit var editTextLongitudineP2: EditText


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

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



        // create path between editText points

        editTextLatitudineP1 = findViewById<EditText>(R.id.editTextLatitudineP1)
        editTextLongitudineP1 = findViewById<EditText>(R.id.editTextLongitudineP1)
        editTextLatitudineP2 = findViewById<EditText>(R.id.editTextLatitudineP2)
        editTextLongitudineP2 = findViewById<EditText>(R.id.editTextLongitudineP2)

        val b = findViewById<Button>(R.id.location)
        b.setOnClickListener{
            try {
               Log.d("Path", "Clicked")
               val p1lati: Double = editTextLatitudineP1.text.toString().toDouble()
               val p1long: Double = editTextLongitudineP1.text.toString().toDouble()
               val p2lati: Double = editTextLatitudineP2.text.toString().toDouble()
               val p2long: Double = editTextLongitudineP2.text.toString().toDouble()
               println("latitudine: $p2lati, longitudine: $p2long")
               navFun.routePath(p1lati, p1long, p2lati, p2long)
               mainActivity.mapView.invalidate()
            } catch (e: Exception) {
                Toast.makeText(context, "Error when entering coordinates", Toast.LENGTH_SHORT).show()
            }
        }

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_create_path, container, false)
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment CreatePathFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            CreatePathFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}

and this is my fragment xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".CreatePathFragment"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/crea_percorso"
        android:textColor="@color/black"
        android:textSize="40sp"
        android:textStyle="bold" />

    <TextView
        android:id="@ id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/inserisci_le_coordinate_dei_punti_tra_cui_vuoi_creare_un_percorso" />

    <TextView
        android:id="@ id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/latitudine_punto_di_partenza" />

    <EditText
        android:id="@ id/editTextLatitudineP1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:ems="10"
        android:hint="@string/latitudine_p1"
        android:inputType="numberSigned|numberDecimal" />

    <TextView
        android:id="@ id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/longitudine_punto_di_partenza" />

    <EditText
        android:id="@ id/editTextLongitudineP1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:ems="10"
        android:hint="@string/longitudine_p1"
        android:inputType="numberSigned|numberDecimal" />

    <TextView
        android:id="@ id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/latitudine_punto_di_arrivo" />

    <EditText
        android:id="@ id/editTextLatitudineP2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:ems="10"
        android:hint="@string/latitudine_p2"
        android:inputType="numberSigned|numberDecimal" />

    <TextView
        android:id="@ id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/longitudine_punto_di_arrivo" />

    <EditText
        android:id="@ id/editTextLongitudineP2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:ems="10"
        android:hint="@string/longitudine_p2"
        android:inputType="numberSigned|numberDecimal" />

    <Button
        android:id="@ id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/crea_percorso"
        />

</LinearLayout>

CodePudding user response:

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

    val view = inflater.inflate(R.layout.fragment_create_path, container, false)

    // create path between editText points

    editTextLatitudineP1 = view.findViewById<EditText>(R.id.editTextLatitudineP1)
    editTextLongitudineP1 = view.findViewById<EditText>(R.id.editTextLongitudineP1)
    editTextLatitudineP2 = view.findViewById<EditText>(R.id.editTextLatitudineP2)
    editTextLongitudineP2 = view.findViewById<EditText>(R.id.editTextLongitudineP2)

    val b = findViewById<Button>(R.id.location)
    b.setOnClickListener{
        try {
           Log.d("Path", "Clicked")
           val p1lati: Double = editTextLatitudineP1.text.toString().toDouble()
           val p1long: Double = editTextLongitudineP1.text.toString().toDouble()
           val p2lati: Double = editTextLatitudineP2.text.toString().toDouble()
           val p2long: Double = editTextLongitudineP2.text.toString().toDouble()
           println("latitudine: $p2lati, longitudine: $p2long")
           navFun.routePath(p1lati, p1long, p2lati, p2long)
           mainActivity.mapView.invalidate()
        } catch (e: Exception) {
            Toast.makeText(context, "Error when entering coordinates", Toast.LENGTH_SHORT).show()
        }
    }

    // Inflate the layout for this fragment
    return view
}

You must create your view first and than call findViewById on that view.

CodePudding user response:

findViewById will not work inside onCreateView, because at that time the UI is being created, so the views are not initialized yet.

try to link the views inside onViewCreated instead. <-- you can import it using ctrl O

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
     
       editTextLatitudineP1 = findViewById<EditText>(R.id.editTextLatitudineP1)

       //.....the rest of your code
    }
  • Related