Home > Enterprise >  Kotlin null handling - making buttons transparent or hiding them
Kotlin null handling - making buttons transparent or hiding them

Time:03-10

Why does my app crash after pressing button which makes buttons transparent, it says that Reading a NULL string not supported here.

    lateinit var Button1: Button
    lateinit var Button2: Button


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

        Button1= view?.findViewById(R.id.btn1)
        Button2 = view?.findViewById(R.id.btn2)


        Button1?.setBackgroundColor(Color.TRANSPARENT)
        Button2?.setBackgroundColor(Color.TRANSPARENT)

    }

Logs

E/OplusCustomizeRestrictionManager: sInstance is null, start a new sInstance
E/libEGL: Invalid file path for libcolorx-loader.soE/libEGL: Invalid file path for libcolorx-loader.so
E/Parcel: Reading a NULL string not supported here.
E/ScreenmodeClient:  display mode not support 

Please help me quickly.

CodePudding user response:

According to your code and exception you said, I think the button may be null, but you define it as lateinit, which means you create later but it can not be null.

Firstly you should make sure the buttons exist, then change the button defines as the following:

    var Button1: Button? = null
    var Button2: Button? = null


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

        Button1= view?.findViewById(R.id.btn1)
        Button2 = view?.findViewById(R.id.btn2)


        Button1?.setBackgroundColor(Color.TRANSPARENT)
        Button2?.setBackgroundColor(Color.TRANSPARENT)

    }

```
the other way is not to use `?`, because the view has to exit.

```
    lateinit var Button1: Button
    lateinit var Button2: Button


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

        Button1= view.findViewById(R.id.btn1)
        Button2 = view.findViewById(R.id.btn2)


        Button1.setBackgroundColor(Color.TRANSPARENT)
        Button2.setBackgroundColor(Color.TRANSPARENT)

    }
```

CodePudding user response:

TRY this -

OPTION 1-

     lateinit var button1: AppCompatButton
        lateinit var button2: AppCompatButton

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        button1 = view.findViewById(R.id.Button1)
        button2 = view.findViewById(R.id.Button2)

        button1.setBackgroundColor(Color.TRANSPARENT)
        button2.setBackgroundColor(Color.TRANSPARENT)
}

Option 2- Simply add in button -

android:background="@null"

<androidx.appcompat.widget.AppCompatButton
        android:id="@ id/Button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:text="Button1" />
  • Related