onClick not working in mvvm in android databinding - android

I am trying to implement mvvm and databinding in kotlin first time. I followed some tutorial and able to implement same. But now button click is not working which I have written in mvvm.
Here is activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewmodel"
type="com.abc.abc.presentation.user.viewmodels.LoginViewModel"/>
</data>
<RelativeLayout
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"
tools:context=".presentation.user.views.LoginActivity"
android:layout_margin="24dip">
<Button
android:layout_width="match_parent"
android:layout_height="40dip"
android:background="#drawable/btn_user_create_account"
android:layout_above="#+id/or_layout"
android:layout_marginBottom="24dp"
android:text="#string/create_account"
android:id="#+id/btn_create_account"
android:layout_marginEnd="12dip"
android:layout_marginStart="12dip"
android:gravity="center_horizontal|center_vertical"
android:textColor="#color/text_color"
android:textAllCaps="false"
android:onClick="#{() -> viewmodel.redirectToRegisterActivity()}"
android:fontFamily="#font/vollkron"
android:textStyle="bold"
/>
<Button
android:layout_width="match_parent"
android:layout_height="40dip"
android:background="#drawable/btn_user_login_reg"
android:layout_above="#+id/btn_create_account"
android:layout_marginBottom="12dp"
android:text="#string/login"
android:id="#+id/btn_login"
android:layout_marginEnd="12dip"
android:layout_marginStart="12dip"
android:gravity="center_horizontal|center_vertical"
android:textColor="#color/white"
android:textAllCaps="false"
android:onClick="#{() -> viewmodel.executeEmailLogin(context)}"
android:fontFamily="#font/vollkron"
android:textStyle="bold"/>
</RelativeLayout>
Here is my ViewModel code :
class LoginViewModel(application: Application) : AndroidViewModel(application) {
var email: ObservableField<String>? = null
var password: ObservableField<String>? = null
var progressDialog: SingleLiveEvent<Boolean>? = null
var launchRegisterActivity: SingleLiveEvent<Boolean>? = null
var userLogin: LiveData<User>? = null
init {
progressDialog = SingleLiveEvent<Boolean>()
launchRegisterActivity = SingleLiveEvent<Boolean>()
email = ObservableField("")
password = ObservableField("")
userLogin = MutableLiveData()
}
fun redirectToRegisterActivity() {
launchRegisterActivity?.value = true
}
fun executeEmailLogin(context: Context) {
progressDialog?.value = true
val user = User(
email = email.toString(),
password = password.toString(),
)
userLogin = UserRepository.getInstance().registerUserUsingEmail(context, user)
}
}
Here is my Login Activity
class LoginActivity : AppCompatActivity() {
var binding: ActivityLoginBinding? = null
var viewModel: LoginViewModel? = null
var customProgressDialog: CustomProgressDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
FacebookSdk.sdkInitialize(applicationContext);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login)
customProgressDialog = CustomProgressDialog(this)
viewModel = ViewModelProviders.of(this).get(LoginViewModel::class.java)
observeViewModel(viewModel!!)
}
private fun observeViewModel(viewModel: LoginViewModel) {
viewModel.progressDialog?.observe(this, Observer {
if (it!!) customProgressDialog?.show() else customProgressDialog?.dismiss()
})
viewModel.launchRegisterActivity?.observe(this, Observer {
if (it!!) startActivity(Intent(this, RegisterActivity::class.java))
})
viewModel.userLogin?.observe(this, Observer { user ->
// redirect user to home scree
Toast.makeText(this, "welcome, ${user?.user_name}", Toast.LENGTH_LONG).show()
})
}
}
Can you please help me to understand what things I am doing wrong here. Do I implemented mvvm correctly?
Any button click is not working.

I think, You forgot to bind viewmodel to databinding.
Add this in onCreate of LoginActivity :
binding.lifecycleOwner = this
binding.viewmodel = viewModel

Try adding
binding.lifecycleOwner = this
after inflating your layout.

Related

On Click event Does not working with Data Binding in Android Studio

I am learning DataBinding in android studio. But I am facing a problem with binding a ModelView. I want to bind a function with a button on click event. I set a function in the model view. I want to update my text view with on click event of my button. But When I click the button my text is not updating. I can not understand what I have done wrong.
XML layout:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="model"
type="com.example.jetpack.MainModelView" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{model.title}"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Update Text"
android:onClick="#{()-> model.update()}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Main Model View:
class MainModelView : ViewModel() {
var title: String = " This is My Application"
fun update() {
title = "I am Changed"
Log.d("UPDATE", "update successfully from main model view")
}
}
Main Activity:
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
lateinit var mainModelView: MainModelView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
mainModelView = ViewModelProvider(this).get(MainModelView::class.java)
binding.model = mainModelView
}
}
My app Image:
thanks in advance for helping.
The title variable in ViewModel needs to be a ObservableField or LiveData otherwise you xml will never know when it's value got updated –
class MainViewModel : ViewModel() {
var text = MutableLiveData(" Welcome to my application ")
fun updateText() {
text.value = " Text is updated successfully "
}
}
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
// Creating MainViewModel object
mainViewModel = MainViewModel()
// Binding mainViewModel variable
// with MainViewModel object
binding.mainViewModel = mainViewModel
// passing LifeCycleOwner to binding object
binding.lifecycleOwner = this
}
}

How to pass multiple views as parameters in BindingAdapter in Data binding android?

I have one relative layout and one ImageView. I want to set visibility based on Image loading like if image loads successfully then imageview is visible and if some error occurs relative layout is visible. How can I manage this scenario in data binding using BindingAdapter ?
Your question is not clear so I don't know if it will help you.
These are steps to implement
1: Create parameters in BindingAdapter.kt
#BindingAdapter("showLoading")
fun View.showLoading(loading: Boolean) {
if (loading) {
visible()
} else {
gone()
}
}
#BindingAdapter("showError")
fun View.showError(error: Boolean) {
if (error) {
visible()
} else {
gone()
}
}
fun View.gone() {
this.visibility = View.GONE
}
fun View.visible() {
this.visibility = View.VISIBLE
}
2: Use parameters [app:showLoading="#{viewModel.showLoading}"] and [app:showError="#{viewModel.showError}"] created in file XML
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="com.xxx.xxx.MainViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#EAEAE2"
android:orientation="vertical">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ShowLoading" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:showLoading="#{viewModel.showLoading}" />
<RelativeLayout
android:id="#+id/viewError"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#color/colorPrimary"
app:showError="#{viewModel.showError}" />
</LinearLayout>
</layout>
3: Create showError and showLoading variables in Viewmodel.
And assign the viewModel variable to the binding.
class MainViewModel: ViewModel() {
val showError: MutableLiveData<Boolean> = MutableLiveData()
val showLoading: MutableLiveData<Boolean> = MutableLiveData()
init {
showError.postValue(false)
showLoading.postValue(true)
}
}
class MainActivity : AppCompatActivity() {
private val viewModel = MainViewModel()
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.lifecycleOwner = this
binding.viewModel = viewModel
initViews()
}
private fun initViews() {
binding.btnAdd.setOnClickListener {
viewModel.showError.postValue(true)
viewModel.showLoading.postValue(false)
}
}
}

How can a ViewModel function access the Place instance returned by PlaceSelectionListener of AutocompleteSupportFragment?

I am building an Android app using Kotlin.
I have a layout that contains a create_button. When the user clicks the button, the onClick should call onCreateJourney() in my ViewModel. This function requires the selectedPlaceId parameter to update a Journey entity with its value.
In my Fragment, I use the AutocompleteSupportFragment for the user to search and choose the desired place. This works well, as onPlaceSelected() returns the correct place in response to the user's selection. But I can't figure out how to use the returned place id value (p0.id) in my ViewModel onCreateJourney().
At this stage, the compiler throws this error:
cannot find method onCreateJourney() in class com.example.traveljournal.journey.NewJourneyViewModel
Please, can you shed some light on this issue for me?
My UI (.xml fragment layout):
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".journey.NewJourneyFragment">
<data>
<variable
name="newJourneyViewModel"
type="com.example.traveljournal.journey.NewJourneyViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/whereQuestion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:text="#string/whereQuestion"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.027"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/journeyBckgImageView" />
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent">
</androidx.cardview.widget.CardView>
<fragment
android:id="#+id/autocomplete_fragment"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/whereQuestion" />
<Button
android:id="#+id/create_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:onClick="#{() -> newJourneyViewModel.onCreateJourney()}"
android:text="#string/createJourneyButton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
My ViewModel
class NewJourneyViewModel (
private val journeyKey: Long = 0L,
val database: TravelDatabaseDao) : ViewModel() {
private var viewModelJob = Job()
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
private val _navigateToJourneys = MutableLiveData<Boolean?>()
val navigateToJourneys: LiveData<Boolean?>
get() = _navigateToJourneys
fun doneNavigating() {
_navigateToJourneys.value = null
}
fun onCreateJourney(selectedPlaceId: String) {
uiScope.launch {
withContext(Dispatchers.IO) {
val journey = database.getJourney(journeyKey) ?: return#withContext
journey.placeId = selectedPlaceId
database.updateJourney(journey)
}
_navigateToJourneys.value = true
}
}
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
}
My Fragment
class NewJourneyFragment : Fragment(), PlaceSelectionListener {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
(activity as AppCompatActivity).supportActionBar?.title = getString(R.string.createJourney)
val binding: FragmentNewJourneyBinding = DataBindingUtil.inflate(
inflater,
R.layout.fragment_new_journey, container, false
)
val application = requireNotNull(this.activity).application
val arguments = NewJourneyFragmentArgs.fromBundle(arguments!!)
val dataSource = TravelDatabase.getInstance(application).travelDatabaseDao
val viewModelFactory = NewJourneyViewModelFactory(arguments.journeyKey, dataSource)
val newJourneyViewModel =
ViewModelProviders.of(
this, viewModelFactory).get(NewJourneyViewModel::class.java)
binding.newJourneyViewModel = newJourneyViewModel
newJourneyViewModel.navigateToJourneys.observe(this, Observer {
if(it == true) {
this.findNavController().navigate(
NewJourneyFragmentDirections.actionNewJourneyDestinationToJourneysDestination())
newJourneyViewModel.doneNavigating()
}
})
if (!Places.isInitialized()) {
this.context?.let { Places.initialize(it, getString(R.string.apiKey), Locale.US) }
}
val autocompleteFragment = childFragmentManager.findFragmentById(R.id.autocomplete_fragment)
as? AutocompleteSupportFragment
autocompleteFragment?.setOnPlaceSelectedListener(this)
autocompleteFragment!!.setHint(getString(R.string.destinationExample))
autocompleteFragment!!.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME))
return binding.root
}
#ExperimentalStdlibApi
override fun onPlaceSelected(p0: Place) {
Log.i("PLACE", "Place: " + p0.name + ", " + p0.id)
}
override fun onError(status: Status) {
Toast.makeText(this.context,""+status.toString(),Toast.LENGTH_LONG).show()
Log.i("ERROR", "An error occurred: " + status)
}
}
You have to pass the field selectedPlaceId as an argument in the xml :
android:onClick="#{() -> newJourneyViewModel.onCreateJourney(newJourneyViewModel.selectedPlaceId)}"
How will you get the selectedPlaceId in view model depends on your programming logic.
For testing purposes, you can hardcode the value.
In NewJourneyViewModel, I set up selectedPlaceId as MutableLiveData.
val selectedPlaceId = MutableLiveData<String>()
In NewJourneyFragment, I used lateinit to create a field for NewJourneyViewModel called newJourneyViewModel and initialized it in onCreateView().
private lateinit var newJourneyViewModel : NewJourneyViewModel
Now having access to my ViewModel outside of onCreateView(), in my Fragment onPlaceSelected() method I can set the value of selectedPlaceId to p0.id.
newJourneyViewModel.selectedPlaceId.value = p0.id
If anybody can come up with a better and safer approach on this, it will be highly appreciated.

How to dynamically load images from a URL into ImageView from a ViewModel in Kotlin

I am writing an app to display NHL scores, and would like for each team in the RecyclerView to have their logo next to it. There is a URL that I can request with a team's ID that will return a hi-res image of the team's logo. I am trying to make it so that I can load the images in my viewModel and set them in the view, as I'm doing for things like the team name, current score, etc.
I have tried using Picasso for this, but it requires a context, which the viewModel doesn't have, and the viewModel cannot directly access the imageView to be able to change it. So how can I load the images and expose them either with data binding or something else, to allow the view to display them?
Here is my MainActivity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var viewModel: GameListViewModel
private var errorSnackbar: Snackbar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.lifecycleOwner = this
binding.gameList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
viewModel = ViewModelProviders.of(this).get(GameListViewModel::class.java)
viewModel.errorMessage.observe(this, Observer { errorMessage ->
if (errorMessage != null)
showError(errorMessage)
else
hideError()
})
binding.viewModel = viewModel
}
private fun showError(#StringRes errorMessage:Int) {
errorSnackbar = Snackbar.make(binding.root, errorMessage, Snackbar.LENGTH_INDEFINITE)
errorSnackbar?.setAction(R.string.retry, viewModel.errorClickListener)
errorSnackbar?.show()
}
private fun hideError() {
errorSnackbar?.dismiss()
}
}
ViewModel:
class GameViewModel:BaseViewModel() {
private val awayTeamName = MutableLiveData<String>()
private val homeTeamName = MutableLiveData<String>()
private val awayTeamScore = MutableLiveData<String>()
private val homeTeamScore = MutableLiveData<String>()
private val timeRemaining = MutableLiveData<String>()
fun bind(response: Game) {
awayTeamName.value = response.gameData.teams.away.name
homeTeamName.value = response.gameData.teams.home.name
awayTeamScore.value = response.liveData.linescore.teams["away"]?.goals.toString()
homeTeamScore.value = response.liveData.linescore.teams["home"]?.goals.toString()
if (response.gameData.status.detailedState == "Scheduled") {
val parser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
parser.timeZone = TimeZone.getTimeZone("UTC")
val formatter = SimpleDateFormat("hh:mm a", Locale.getDefault())
formatter.timeZone = TimeZone.getDefault()
timeRemaining.value = formatter.format(parser.parse(response.gameData.datetime.dateTime))
} else {
timeRemaining.value = response.liveData.linescore.currentPeriodTimeRemaining + " " + response.liveData.linescore.currentPeriodOrdinal
}
}
fun getAwayTeamName(): MutableLiveData<String> {
return awayTeamName
}
fun getHomeTeamName(): MutableLiveData<String> {
return homeTeamName
}
fun getAwayTeamScore(): MutableLiveData<String> {
return awayTeamScore
}
fun getHomeTeamScore(): MutableLiveData<String> {
return homeTeamScore
}
fun getTimeRemaining(): MutableLiveData<String> {
return timeRemaining
}
}
and XML for the recyclerView row:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="com.example.nhlstats.ui.game.GameViewModel" />
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/awayTeam"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="12dp">
<ImageView
android:id="#+id/awayTeamLogo"
android:layout_height="36dp"
android:layout_width="0dp"
android:layout_weight="1"
tools:src="#drawable/ic_launcher_background"/>
<TextView
android:id="#+id/awayTeamName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:layout_gravity="center_vertical"
android:text="#{viewModel.awayTeamName}"
tools:text="CHI Blackhawks"/>
<TextView
android:id="#+id/awayScore"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:text="#{viewModel.awayTeamScore}"
tools:text="0"/>
<TextView
android:id="#+id/gameTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:text="#{viewModel.timeRemaining}"
tools:text="14:26 3rd"/>
</LinearLayout>
<LinearLayout
android:id="#+id/homeTeam"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_marginBottom="24dp">
<ImageView
android:id="#+id/homeTeamLogo"
android:layout_height="36dp"
android:layout_width="0dp"
android:layout_weight="1"
tools:src="#drawable/ic_launcher_background"/>
<TextView
android:id="#+id/homeTeamName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:layout_gravity="center_vertical"
android:text="#{viewModel.homeTeamName}"
tools:text="CAR Hurricanes"/>
<TextView
android:id="#+id/homeScore"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="2"
android:text="#{viewModel.homeTeamScore}"
tools:text="4"/>
</LinearLayout>
</LinearLayout>
</layout>
Thanks in advance.
Using data binding you should create a custom binding adapter like below:
#BindingAdapter("app:imageUri")
fun loadImageWithUri(imageView: ImageView, imageUri: String){
Glide.with(imageView.context).load(Uri.parse(imageUri)).into(imageView)
}
And change you imageview like this:
<androidx.appcompat.widget.AppCompatImageView
android:layout_height="36dp"
android:layout_width="0dp"
android:layout_weight="1"
app:imageUri="#{viewmodel.teamLogoUri}"/>
For Android Architecture Components View Model,
It's not a good practice to pass your Activity Context to the Activity's ViewModel as its a memory leak. I don't support to to that.
You can create image url observer in viewmodel and observe it in your View class (Activity or fragment), Like this (as Duy Khanh Nguyen answered):-
viewModel.url.observe(this, Observer {
it?.let { url ->
//So image into itemView using Picasso
}
})
But if you want to go with otherwise you can simply use an Application context which is provided by the AndroidViewModel, you should extend AndroidViewModel which is simply a ViewModel that includes an Application reference. I your case do it into your BaseViewModel. Example:-
class BaseViewModel(application: Application) : AndroidViewModel(application) {
val context = getApplication<Application>().applicationContext
//... ViewModel methods
}
I guest you'll create GameViewModel for each itemView, so when binding the view holder:
Your GameViewModel class
val awayLogoUrl = MutableLiveData<String>()
val homeLogoUrl = MutableLiveData<String>()
fun bind(response: Game) {
awayLogoUrl.value = response... //set away logo url here
homeLogoUrl.value = response... //set home logo url here
}
Your ViewHolder class
viewModel.awayLogoUrl.observe(this, Observer {
it?.let { url ->
//Show image into itemView using Picasso or Glide
Glide.with(itemView.context).load(url).into(binding.awayTeamLogo)
}
})
viewModel.homeLogoUrl.observe(this, Observer {
it?.let { url ->
//Show image into itemView using Picasso or Glide
Glide.with(itemView.context).load(url).into(binding.homeTeamLogo)
}
})

How to change my existing code by integrating data binding android

I have an exisitng code which I integrate with Live data by using retrofit.
Now if I want to integrate databinding, where are all changes to be done to make the code looks perfect?
Here is my code.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Android Versions"
android:textColor="#ffffff"
android:textSize="20sp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
items.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:background="#445566"
android:layout_margin="5dp"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvFname"
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|start"
android:layout_marginTop="8dp"
android:textColor="#ffffff"
android:layout_weight="1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="#+id/tvLname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|start"
android:padding="5dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:ellipsize="end"
android:textColor="#ffffff"
android:maxLines="5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvFname"/>
</android.support.constraint.ConstraintLayout>
Here is view model class which I integrated
class AndroidViewModel:ViewModel() {
private val mService = RetrofitService()
fun getAndroidData():MutableLiveData<List<AndroidData>>?{
return mService.loadAndroidData()
}
}
Pojo class generated is just a simple one:
data class AndroidData (val name:String, val apiLevel:String)
Service integration:
class RetrofitService {
val liveUserResponse:MutableLiveData<List<AndroidData>> = MutableLiveData()
companion object Factory {
var gson = GsonBuilder().setLenient().create()
fun create(): ApiInterface {
Log.e("retrofit","create")
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl("https://learn2crack-json.herokuapp.com/api/")
.build()
return retrofit.create(ApiInterface::class.java)
}
}
fun loadAndroidData(): MutableLiveData<List<AndroidData>>? {
Log.e("loadAndroidData","yes")
val retrofitCall = create().getAndroid()
retrofitCall.enqueue(object : Callback<List<AndroidData>> {
override fun onFailure(call: Call<List<AndroidData>>, t: Throwable?) {
Log.e("on Failure :", "retrofit error")
}
override fun onResponse(call: Call<List<AndroidData>>, response: retrofit2.Response<List<AndroidData>>) {
val list = response.body()
for (i in list.orEmpty()){
Log.e("on response 1:", i.name)
}
liveUserResponse.value = list
Log.e("hasActiveObservers 1", liveUserResponse.hasActiveObservers().toString()+" check")
Log.e("on response 2 :", liveUserResponse.toString()+" check")
}
})
return liveUserResponse
}
Main Activity:
class MainActivity : AppCompatActivity(){
private lateinit var linearLayoutManager: LinearLayoutManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
linearLayoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
getAndroidVersion()
}
private fun getAndroidVersion() {
Log.e("getAndroidVersion", "yes")
val mAndroidViewModel = ViewModelProviders.of(this#MainActivity).get(AndroidViewModel::class.java)
mAndroidViewModel.getAndroidData()?.observe(this, Observer<List<AndroidData>> { androidList ->
Log.e("list", androidList?.size.toString())
recyclerView.adapter = EmpAdapter(this#MainActivity, androidList as ArrayList<AndroidData>, object :
ItemClickListener {
override fun onItemClick(pos: Int, name:String) {
Toast.makeText(applicationContext, "item "+pos+ "clicked"+ name, Toast.LENGTH_LONG).show()
}
})
})
}
}
Adapter class:
class EmpAdapter(
var context: MainActivity,
var mEmpList: ArrayList<AndroidData>,
private val itemClick:ItemClickListener
) :
RecyclerView.Adapter<EmpAdapter.EmpHolder>() {
override fun getItemCount(): Int {
return mEmpList.size
}
companion object {
var mItemClickListener : ItemClickListener? = null
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EmpHolder {
val view = LayoutInflater.from(context).inflate(R.layout.items, parent, false)
return EmpHolder(view)
}
override fun onBindViewHolder(holder: EmpHolder, position: Int) {
mItemClickListener = itemClick
holder.tvFname?.text = mEmpList[position].name
holder.tvLname?.text = mEmpList[position].apiLevel
RxView.clicks(holder.mView).subscribe {
mItemClickListener!!.onItemClick(position,mEmpList[position].name)
}
}
class EmpHolder(view: View) : RecyclerView.ViewHolder(view) {
val tvFname = view.tvFname
val tvLname = view.tvLname
val mView = view
}
}
interfaces for retrofit:
interface ApiInterface {
#GET("android")
fun getAndroid(): Call<List<AndroidData>>
}
Now my question is, if I integrate tag and in xml, which variable i need to specify for textview to integrate to connect for textview in adapter? Kindly guide me where are all I need to change to apply, if I use live data
First of all, i strongly recommend to use a Retrofit Adapter that converts the response into LiveData automatically for you. See this example
https://github.com/yasiralijaved/android-architecture-components/blob/master/component_http/src/main/java/com/yasiralijaved/android/arc/component/http/BackendService.java
Secondly there are detailed tutorials out there which can surely help you how to implement Data Bindings in RecyclerView Adapter. A few tutorials are:
https://medium.com/androiddevelopers/android-data-binding-recyclerview-db7c40d9f0e4
https://android.jlelse.eu/how-to-bind-a-list-of-items-to-a-recyclerview-with-android-data-binding-1bd08b4796b4
Do let me know if it is still not clear and i will share some more details.
Happy coding!!

Categories

Resources