How to send data another page and list with kotlin? - kotlin

I just started learning Kotlin. I am making an application that saves bank (IBAN) information. I save the information locally using sharedpreferences.
I save the information to the list and save it as sharedpreferences.
Information is recorded on page 2 and I want to list this recorded information on page 1.
I was doing this simply in Flutter, but I couldn't understand how to do it in Kotlin.
package com.example.ibansfer
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.ibansfer.databinding.ActivityAddIbanBinding
import com.example.ibansfer.models.IbanModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
class AddIbanActivity : AppCompatActivity() {
private lateinit var binding: ActivityAddIbanBinding
private var ibanList: ArrayList<IbanModel> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAddIbanBinding.inflate(layoutInflater)
setContentView(binding.root)
setTitle("IBAN bilgisi ekle")
getSupportActionBar()?.setDisplayHomeAsUpEnabled(true);
val sharedPreferences = this.getSharedPreferences("ibans", MODE_PRIVATE)
val editor = sharedPreferences.edit()
fun saveData() {
val gson = Gson()
val json = gson.toJson(ibanList)
editor.putString("ibans", json)
editor.apply()
}
binding.ibanSaveBttn.setOnClickListener {
val ibanOwner = binding.ibanOwner.text.toString()
val bankName = binding.bankName.text.toString()
val ibanAdress = binding.ibanAdress.text.toString()
if (ibanOwner.isEmpty() || bankName.isEmpty() || ibanAdress.isEmpty()) {
Toast.makeText(this, "Lütfen tüm alanları doldurunuz.", Toast.LENGTH_LONG).show()
} else {
ibanList.add(IbanModel(ibanOwner, bankName, ibanAdress))
saveData()
Toast.makeText(this, "IBAN bilgileri başarıyla eklendi.", Toast.LENGTH_LONG).show()
finish()
}
}
}
}

If you save the data in SharedPrefferences, you can always retrieve it back in the other screen.
val sharedPref = activity?.getPreferences("ibans", Context.MODE_PRIVATE) ?: return
val myString = sharedPref.getString("ibans", defaultValue)
You can even set up a SharedPrefferences listener that will get notified whenever new data is added to it and act accordingly.
val sharedPreferencesListener =
SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
// code to execute on changes here
}
activity?.getPreferences("ibans", Context.MODE_PRIVATE)
?.registerOnSharedPreferenceChangeListener(sharedPreferencesListener )
Also don't forget to unregister using unregisterOnSharedPreferenceChangeListener
Or alternatively, use Intents as the comment suggests to pass data between Activities/Fragments.

Related

How to return a variable from inside coroutine scope in Kotlin

I have a jsoup function inside of a coroutine that scrapes information from a website and then gets a list of maps of all of the information it scraped. However, whenever I try to return the list, this is returned instead:
"Function0<java.util.List<java.util.Map<java.lang.String, ? extends java.lang.String>>>"
Here is the code for the function:
suspend fun popularHome(
pg: String
): Any = withContext(Dispatchers.IO) {
val table = mutableListOf<Map<String, String>>()
val doc: Document = Jsoup
.connect("https://www.novelupdates.com/novelslisting/?sort=2&order=1&status=1&pg=$pg")
.userAgent("Mozilla/5.0")
.referrer("http://www.google.com")
.ignoreContentType(true)
.get()
val imageLists = doc.getElementsByClass("search_img_nu")
val lists = doc.getElementsByClass("search_main_box_nu")
for ((list, imageList) in lists.zip(imageLists)) {
val searches: Elements = list.getElementsByClass("search_title")
val imageSearches: Elements = imageList.getElementsByTag("img")
for ((search, imageSearch) in searches.zip(imageSearches)) {
val titles = search.getElementsByTag("a")
val ranks = search.getElementsByClass("genre_rank")
for ((title, rank) in titles.zip(ranks)) {
val link: String = title.attr("href") // Book Link
val titleName: String = title.text() // Book Title
val imageLink: String = imageSearch.attr("src") // Book Image Link
val rankName: String =
rank.text().replace("#", "") // Book Popularity Rank
table.add(
mutableMapOf<String, String>(
"rank" to rankName,
"title" to titleName,
"link" to link,
"image" to imageLink
)
)
}
}
}
Log.i("tag", table.toString())
return#withContext { table }
}
Here is the code for Main Activity:
package com.example.sushi
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.lifecycle.lifecycleScope
import com.example.sushi.service.repos.novelupdates.com.NovelUpdatesScraper
import com.example.sushi.ui.styling.SushiTheme
import kotlinx.coroutines.*
class MainActivity : ComponentActivity() {
val scrape = NovelUpdatesScraper()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
SushiTheme {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "Hey")
}
}
}
lifecycleScope.launch {
Log.i("tag", scrape.popularHome("1").toString())
}
}
}
No matter where I put the return I can't get it to give me anything but an empty list. Yet when I log the list it gives me all of the information that was scraped.
I already tried this solution:
How to return a value inside a coroutine scope kotlin, android
and this solution:
How to return value from coroutine scope
In the code, when you call return#withContext { table } mean it will return () -> List instead of the List instance.
Just call return#withContext table and it should be fixed.
Btw, I believe you should not set the function return type to Any.
If you know exactly what you gonna do and you expect this function will return a List then the return type should be List<Map<String, String>>, there is no reason to set it as Any. The immediate benefits that can be seen is if you set the return type as List<Map<String, String>> and call return#withContext { table }, the Android Studio IDE will show you what went wrong.

Add button in recyclerview to edit or delete data from realtime database

i'm a beginner in programming so forgive me if my code is messy. I need some help to complete my program.
I'm using recyclerview to retrieve some data from realtime database and i want to add edit and delete button in the recyclerview to edit and delete some data.
I already create the button in the xml file, i just don't know how to code the button. I already tried some tutorial from youtube and refer to some code in some others post on stack overflow but most of the time the code will either give me an error or the button will not do anything. I've included my code and database structure below:
DoctorViewAdapter.kt
package com.example.patientmonitor
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import java.util.ArrayList
import kotlin.concurrent.fixedRateTimer
class DoctorViewAdapter(private val patientList : ArrayList<doctorViewPatient>) : RecyclerView.Adapter<DoctorViewAdapter.DoctorViewHolder>() {
//WebView
private lateinit var pulseGraph: WebView
private lateinit var temperatureGraph: WebView
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DoctorViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.patient_item,parent,false)
return DoctorViewHolder(itemView)
pulseGraph.webViewClient = WebViewClient()
temperatureGraph.webViewClient = WebViewClient()
pulseGraph.settings.javaScriptEnabled = true
temperatureGraph.settings.javaScriptEnabled = true
pulseGraph.settings.builtInZoomControls = true
temperatureGraph.settings.builtInZoomControls = true
}
override fun onBindViewHolder(holder: DoctorViewHolder, position: Int) {
val currentitem = patientList[position]
holder.userID.text = currentitem.userID
holder.fullName.text = currentitem.fullName
holder.userEmail.text = currentitem.email
holder.phoneNumber.text = currentitem.phoneNumber
var pulseValue = "null"
var temperatureValue = "null"
//get pulse value from thingspeak and set to text view
val pulsequeue = Volley.newRequestQueue(holder.pulseValue.context)
val temperaturequeue = Volley.newRequestQueue(holder.temperatureValue.context)
val pulseRequest = StringRequest(Request.Method.GET, currentitem.pulseValue as String?,
Response.Listener<String> { response ->
pulseValue = response
holder.pulseValue.text = pulseValue
}, Response.ErrorListener {
// didn't work
})
//get temperature value from thingspeak and set to text view
val tempRequest = StringRequest(Request.Method.GET, currentitem.temperatureValue as String?,
Response.Listener<String> { response ->
temperatureValue = response
holder.temperatureValue.text = temperatureValue
}, Response.ErrorListener {
// didn't work
})
//get thingspeak data every 1 second
fixedRateTimer("timer", false, 0L, 1000) {
pulsequeue.add(pulseRequest)
temperaturequeue.add(tempRequest)
}
}
override fun getItemCount(): Int {
return patientList.size
}
class DoctorViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val userID : TextView = itemView.findViewById(R.id.tvUserID)
val fullName : TextView = itemView.findViewById(R.id.tvFullName)
val userEmail : TextView = itemView.findViewById(R.id.tvEmail)
val phoneNumber : TextView = itemView.findViewById(R.id.tvPhoneNumber)
val pulseValue : TextView = itemView.findViewById(R.id.tvPulseValue)
val temperatureValue : TextView = itemView.findViewById(R.id.tvTemperatureValue)
}
}
PatientlistActivity.kt
package com.example.patientmonitor
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView
import androidx.appcompat.app.ActionBar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.firebase.database.*
class PatientListActivity : AppCompatActivity() {
private lateinit var dbref : DatabaseReference
private lateinit var userRecyclerview : RecyclerView
private lateinit var userArrayList : ArrayList<doctorViewPatient>
private lateinit var viewPatientBtn : FloatingActionButton
private lateinit var doctorViewAdapter : DoctorViewAdapter
//ActionBar
private lateinit var actionBar: ActionBar
//WebView
private lateinit var pulseView: WebView
private lateinit var tempView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_patient_list)
//configure Actionbar //enable back button
actionBar = supportActionBar!!
actionBar.title = "View Patients"
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setDisplayShowHomeEnabled(true)
userRecyclerview = findViewById(R.id.patientList)
userRecyclerview.layoutManager = LinearLayoutManager(this)
userRecyclerview.setHasFixedSize(true)
userArrayList = arrayListOf<doctorViewPatient>()
getUserData()
}
private fun getUserData() {
//get intent
val assignedDoctor = intent.getStringExtra("doctorID")
val currentUserAccess = intent.getStringExtra("currentUserAccess")
dbref = FirebaseDatabase.getInstance().getReference("Users")
dbref.orderByChild("assignedDoctor").equalTo(assignedDoctor).addListenerForSingleValueEvent(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
for (userSnapshot in snapshot.children){
val user = userSnapshot.getValue(doctorViewPatient::class.java)
userArrayList.add(user!!)
}
userRecyclerview.adapter = DoctorViewAdapter(userArrayList)
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
This is my data class
doctorViewPatient.kt
data class doctorViewPatient(val userID : String? =null,
val fullName : String? =null,
val email : String? =null,
val phoneNumber : String? =null,
val pulseValue : String? = null,
val temperatureValue : String? = null)
This is my Realtime Database Structure

kotlin firebase database won't upload

I've got a little project running for an app to keep track on my LP and cd's
thing is... I want to implement a Firebase database to store all the data in. It's not the first time I'm doing such a thing.. it is the first time i'm stuck with it tho.
here's the base code for the "add item" screen. The idea is that I'm able to attach a bit of data to the items, via textviews, spinners, images etc.
the script works flawless till the "upload image" part.. after that it'll run the firebase upload code... but nothing happens. both the succes and failure log's don't give any output.
could anybody help me with this?
package com.example.firebasic
import android.app.Activity
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import kotlinx.android.synthetic.main.activity_add.*
import java.util.*
class AddAlbum : AppCompatActivity(), AdapterView.OnItemSelectedListener {
private var spinner:Spinner ? = null
private var arrayAdapter:ArrayAdapter<String> ? = null
private var genres = arrayOf(
"Rock",
"Jazz",
"Soul",
"Metal",
"Punk",
"Pop",
"alt",
"classic",
"other",
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
spinner = findViewById(R.id.spinner4)
arrayAdapter = ArrayAdapter(applicationContext, R.layout.spinnerbg, genres)
spinner?.adapter = arrayAdapter
spinner?.onItemSelectedListener = this
//photo
Cover_photo.setOnLongClickListener {
Log.d("AddAlbum", "try to show album cover")
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, 0)
return#setOnLongClickListener true
}
accept_button.setOnClickListener {
UploadtoFirebase()
}
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
var genre:String = parent?.getItemAtPosition(position) as String
Toast.makeText(applicationContext, "$genre", Toast.LENGTH_SHORT).show()
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("Not yet implemented")
}
//uri kenmerk
var selectedphotouri: Uri? = null
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null){
//proceed and check image
Log.d("AddAlbum", "photo was selected")
selectedphotouri = data.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedphotouri)
val bitmapDrawable = BitmapDrawable(bitmap)
Cover_photo.setBackgroundDrawable(bitmapDrawable)
}
}
private fun UploadtoFirebase(){
if (selectedphotouri == null) return
val filename = UUID.randomUUID().toString()
val ref = FirebaseStorage.getInstance().getReference("/images/$filename")
ref.putFile(selectedphotouri!!)
.addOnSuccessListener {
Log.d("AddAlbum", "succesfuly uploaded")
ref.downloadUrl.addOnSuccessListener {
saveDataToDatabase(it.toString())
Log.d("AddAlbum", "File location: $it")
}
}
}
private fun saveDataToDatabase(Albumphoto: String){
//data input
val Artist = ArtistName.text.toString()
val Album = AlbumName.text.toString()
val Photo = Albumphoto
val data = User(Artist, Album, Photo)
//upload code
val uid = FirebaseAuth.getInstance().uid
val ref = FirebaseDatabase.getInstance().getReference("/album/$uid")
ref.child("01").setValue(data)
.addOnSuccessListener {
Log.d("addalbum", "succesfuly saved data")
}
.addOnFailureListener {
Log.d("addalbum", "still won't work")
}
}
}
class User(val Artist: String, val Albumname: String, val Albumphoto: String)

Kotlin code Send SMS from within App without using default app

I am trying to build an app whereby the user clicks a submit button which will send the contents of their input via SMS to a predefined number. Being very new to Kotlin, I have been helped with the code to send the data via SMS, however it opens up the default messaging app and the user has to interact with the messaging app and then navigate back to my app. What I would like is for this to happen in the background and send directly from my app. The code is below...Any help greatly appreciated, Many thanks
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val backbut = findViewById<Button>(R.id.backbut)
backbut.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
var spinner: Spinner? = null
spinner = this.spinner
val sub1: Button = findViewById<Button>(R.id.sub1)
sub1.setOnClickListener {
val cust: String = cust.text.toString()
val reg: String = reg.text.toString()
val pal: String = pal.text.toString()
val cont:String = cont.text.toString()
val data: String =
"CUSTOMER : ".plus(cust).plus("\n").plus("CONTAINER : ").plus(cont).plus("\n").plus("VEH
REG : ").plus(reg).plus("\n").plus("PALLETS : ")
.plus(pal)
startActivity(getSendSmsIntent("1234567", data))
}
}
// textview_selected!!.text = "Selected : "+ Spinner [position]
private fun getSendSmsIntent(phoneNumber: String, content: String?): Intent? {
val uri = Uri.parse("smsto:$phoneNumber")
val intent = Intent(Intent.ACTION_SENDTO, uri)
intent.putExtra("sms_body", content)
return getIntent(intent, true)
}
private fun getIntent(intent: Intent, isNewTask: Boolean): Intent? {
return if (isNewTask) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) else intent
}
}
After reading the documentation, I think you can achieve your needs using the following code :
private fun sendSMS(phoneNumber: String, message: String) {
val sentPI: PendingIntent = PendingIntent.getBroadcast(this, 0, Intent("SMS_SENT"), 0)
SmsManager.getDefault().sendTextMessage(phoneNumber, null, message, sentPI, null)
}
Add this permission to your AndroidManifest and make sure it's granted :
<uses-permission android:name="android.permission.SEND_SMS" />
Call sendSMS method as follows :
sendSMS("+2126000000", "Some text here")
Screenshot :

Retrieve display profiles using UID on a FirestoreRecycler Adapter using Kotlin?

I am having difficulties retrieving the information correctly from Firebase Firestore for my Recycler Adapter. I am not sure what I might be doing wrong but I used a Document Reference to get the required field but now it seems to just copy the same thing over and over, I want it to display each created users profile and display it on my RecyclerAdapter but am not sure what I should do and have tried different methods but get a
"No setter/field error" on my Model Class "Users".
This is my Firebase Schema
This is what it is outputting
This is what I have my code as so far
[Update]
This is what I have imported
import Models.User
import android.content.Intent
import android.content.res.Configuration
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.android.material.navigation.NavigationView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.*
import com.squareup.picasso.Picasso
import de.hdodenhof.circleimageview.CircleImageView
import kotlinx.android.synthetic.main.all_nearby_users.*
import kotlinx.android.synthetic.main.toolbar_layout.*
Oncreate
auth = FirebaseAuth.getInstance()
val customUserId = auth.currentUser!!.uid
val db = FirebaseFirestore.getInstance()
val userRef = db.collection("sUsers").document(customUserId)
val userQuery = db.collection("sUsers").orderBy("Full Name", Query.Direction.DESCENDING).limit(10)
//User List Layout
all_users_nearby_list.layoutManager = LinearLayoutManager(this)
//Firestore
val firestoreRecyclerOptions: FirestoreRecyclerOptions<Users> = FirestoreRecyclerOptions.Builder<Users>()
.setQuery(userQuery, Users::class.java)
.build()
adapter = UserFirestoreRecyclerAdapter(firestoreRecyclerOptions)
all_users_nearby_list.adapter = adapter
Firestore Recycler Adapter
private inner class UserFirestoreRecyclerAdapter internal constructor
(firestoreRecyclerOptions: FirestoreRecyclerOptions<Users>): FirestoreRecyclerAdapter<Users, UserViewHolder>(firestoreRecyclerOptions) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val userView = LayoutInflater.from(parent.context)
.inflate(R.layout.display_users_profile, parent, false)
return UserViewHolder(userView)
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int, model: Users) {
holder.setFullname(model.fullname)
holder.setProfileimage(model.profileImage)
}
}
UserViewHolder
private inner class UserViewHolder internal constructor (private val pView: View) : RecyclerView.ViewHolder(pView) {
internal fun setFullname(fullname: String) {
val username = pView.findViewById<TextView>(R.id.usernameTextView)
val db = FirebaseFirestore.getInstance()
val docRef = db.collection("sUsers").document(auth.currentUser!!.uid)
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d("HomeActivity", "DocumentSnapshot data: ${document.data}")
username.text = document.getString("Full Name")
} else {
Log.d("HomeActivity", "No such document")
}
}
.addOnFailureListener { exception ->
Log.d("HomeActivity", "get failed with ", exception)
}
username.text = fullname
Log.d("HomeActivity", "Current Data: " + fullname)
}
internal fun setProfileimage(profileImage: String) {
val userProfileImage = pView.findViewById<CircleImageView>(R.id.profileUserImage)
Picasso.get().load(profileImage).into(userProfileImage)
}
}
Model Class
package Models
class Users(
var fullname: String= "",
var profileImage: String= "",
var uid: String? = "",
var haircut: Boolean? = null,
var waxing: Boolean? = null,
var nails: Boolean? = null,
var profileRatingBar: Float? = 1.0f
)
My onStart and onStop
override fun onStart() {
super.onStart()
adapter!!.startListening()
}
override fun onStop() {
super.onStop()
if (adapter != null) {
adapter!!.stopListening()
}
}
This is how I would write your RecyclerView. Key points:
Don't make a 2nd FireStore query inside the ViewHolder
Your Firestore schema must exactly match your model
Use lifecycle owner instead of onStart/onStop
Firebase UI doesn't capture the uid; so do this manually (see apply)
ViewHolder must "hold" the views as fields (to avoid calling find every time)
Model represents 1 object, so I name it "User" not "Users"
Set layoutManager in XML to reduce boilerplate in onCreate
Layout XML
<androidx.recyclerview.widget.RecyclerView
...
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:itemCount="5"
tools:listitem="#layout/display_users_profile"
... />
Activity onCreate
val query = FirebaseFirestore.getInstance()
.collection("sUsers") // Why not "users" ?
.orderBy("fullname", Query.Direction.DESCENDING)
.limit(10)
val options = FirestoreRecyclerOptions.Builder<User>()
.setLifeCycleOwner(this)
.setQuery(query) { it.toObject(User::class.java)!!.apply { uid = it.id } }
.build()
all_users_nearby_list.adapter = UserFirestoreRecyclerAdapter(options)
Adapter
internal class UserFirestoreRecyclerAdapter(options: FirestoreRecyclerOptions<User>) :
FirestoreRecyclerAdapter<User, UserViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
LayoutInflater.from(parent.context)
.inflate(R.layout.display_users_profile, parent, false)
.let { UserViewHolder(it) }
override fun onBindViewHolder(holder: UserViewHolder, position: Int, model: Users) =
holder.bind(model)
}
ViewHolder
internal class UserViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView) {
// Hold view refs
private val usernameTextView: TextView = itemView.userNameTextView
private val profileUserImage: ImageView = itemView.profileUserImage
internal fun bind(model: User) {
model.apply {
usernameTextView.text = fullname
Picasso.get().load(profileImage).into(profileUserImage)
}
}
}
Model
// Set sensible defaults here (or null if no sensible default)
data class User(
var uid: String = "",
var fullname: String= "",
var profileImage: String= "",
var haircut: Boolean = false,
var waxing: Boolean = false,
var nails: Boolean = false,
var profileRatingBar: Float? = null
)