How to propertly get data from editText in data binding(beginner)

57 views Asked by At

I'm a beginner in android programming. I'm trying to build my first app and wanted to implement straight away the right logic. I read about DataBinding and tried to implement this thing in my project.

My first and main problem, that I can't understand how to receive data from edit text using data binding.

This is one of my XML files where I'm using editText

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <data>
        <variable
            name="viewmodel"
            type="com.example.myapplication.ui_logic.MainScreenLogic" />
    </data>
    <LinearLayout 
        android:orientation="vertical"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:stretchColumns="1">


        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:padding="3dip"
                android:text="@string/start" />

        </TableRow>
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:padding="3dip"
                android:text="@string/destination" />

        </TableRow>
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:padding="3dip"
                android:text="@string/time" />

        </TableRow>
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:padding="3dip"
                android:text="@string/turns" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:text="@={viewmodel.link}"
                android:id="@+id/link"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/green"
                android:hint="@string/maps_link"
                android:inputType="text"
                android:minHeight="35dp"
                android:maxHeight="70dp"
                android:importantForAutofill="no">
                <requestFocus />

            </EditText>


        </TableRow>


    </LinearLayout>
</layout>

this is part of my Main Activity file

class Main_screen : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val binding: ScreenMainBinding = DataBindingUtil.setContentView(this, R.layout.screen_main)
        val viewModel = ViewModelProvider(this)[MainScreenLogic::class.java]
        binding.viewmodel = viewModel
    }
}

And this is viewModel file.

package com.example.myapplication.ui_logic

import android.util.Log
import android.view.View
import androidx.databinding.Bindable
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel


class MainScreenLogic() : ViewModel() {
    var link = ""
    //val route = inputs(link)
    fun generateBt(view: View) {

        Log.d("button", link)

    }
}

And my grade dependencies:

    plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'org.jetbrains.kotlin.plugin.serialization'
}

android {
    namespace 'com.example.myapplication'
    compileSdk 34

    defaultConfig {
        applicationId "com.example.myapplication"
        minSdk 21
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    dataBinding {
        enabled = true
    }
}

dependencies {
    def ktor_version = "2.3.2"
    implementation 'androidx.core:core-ktx:1.12.0-beta01'
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.9.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.core:core-ktx:1.12.0-beta01'
    implementation "io.ktor:ktor-client-core:$ktor_version"
    implementation "io.ktor:ktor-client-okhttp:$ktor_version"
    implementation "io.ktor:ktor-client-logging:$ktor_version"
    implementation "io.ktor:ktor-serialization-kotlinx-json:$ktor_version"
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-core:1.5.1"
    implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
    implementation "androidx.activity:activity-ktx:1.7.2"
    implementation "androidx.fragment:fragment-ktx:1.5.7"
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

When I'm trying to read Log, link variable is empty for some reason.

I'm a bit confused in all this stuff, because i've also read about mutableLiveData, @Bindable, and so many terms making me a bit lost. I was planning to send link String text to another class function.

Am i at least on the right way?

I was thinking about this code structure:

Do you think this is a right way to architect the code?My Structure

Thank you!

(and I also have this error, it doesn't stop the code from work, but maybe it is important: error message )

I'm trying to recive String from EditText using databinding.

1

There are 1 answers

1
AndroidNoob On

In your given code, link is String. To make it work in Data binding, change it to MutableLiveData of String type.

So your view model where you defined the link variable will be,

val link = MutableLiveData<String>("")

Now, you can change the value in edit text and it will be reflected in the link variable.

You can access the value in link variable using value property. Ex.

println(link.value)

I would highly recommend you to go through this basic databinding codelab given by Google on their official website.

https://developer.android.com/codelabs/android-databinding#0