Kotlin create email client (javamail, Google OAUTH, kotlin) - AUTHENTICATIONFAILED invalid credentials (failure) - kotlin

I'm trying to develop a small android email client in kotlin.
I use javanais api and google OAUTH but I got the following message.
-----TEST START-----
-----TEST BP1-----
-----TEST BP2-----
ERROR:javax.mail.AuthenticationFailedException: [AUTHENTICATIONFAILED] Invalid credentials (Failure)
ERROR MESSAGE : [AUTHENTICATIONFAILED] Invalid credentials (Failure)
ERROR MESSAGE : kotlin.Unit
The retrieval of the google oauth token works well but not the passing it to javanais api.
MainActivity.kt :
package fr.nothing.lab.emailtest
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.SignInButton
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
class MainActivity : AppCompatActivity() {
private var mGoogleSignInClient: GoogleSignInClient? = null
private val RC_SIGN_IN = 9001
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build()
mGoogleSignInClient = GoogleSignIn.getClient(this, gso)
}
public override fun onStart(){
super.onStart()
val mGmailSignIn = findViewById<SignInButton>(R.id.sign_in_button)
val account = GoogleSignIn.getLastSignedInAccount(this)
Log.w("MainActivity--Sign in 1:", account.toString())
mGmailSignIn.setOnClickListener {
signIn()
}
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == RC_SIGN_IN){
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)
}
}
private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>){
Log.w("MainActivity -- Sign in 2:", completedTask.toString())
try{
val account = completedTask.getResult(ApiException::class.java)
val idToken = getString(R.string.server_client_id)
val email = account!!.email
val ee = account!!.isExpired
Log.w("MainActivity -- Sign in 4 :","Token id :"+idToken.toString() + " | "+email)
Log.w("MainActivity -- Sign in 4 :","email :"+email)
Log.w("MainActivity -- Sign in 4 :","expried :"+ee)
if(idToken != null){
val pop3Host = "imap.gmail.com"
val mailStoreType = "imaps"
val username = email.toString()
val password = idToken
val tp = threadperso(true,pop3Host, mailStoreType, username, password)
tp.start()
}
}catch(e: ApiException){
Log.w("MainActivity--Sign in 3:","signInResult:failed open =" + e.statusCode)
}
}
private fun signIn(){
val signInIntent = mGoogleSignInClient!!.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
}
thradperso.kt
package fr.nothing.lab.emailtest
import android.os.AsyncTask
class threadperso(
private val google : Boolean,
private val pop3Host : String,
private val storeType : String,
private val user : String,
private val password : String
) : Thread(){
public override fun run(){
ReceiveEmail.receiveEmail(google, pop3Host, storeType, user, password)
}
}
ReceiveEmail.kt
package fr.nothing.lab.emailtest
import android.util.Log
import java.util.*
import javax.mail.Address
import javax.mail.Folder
import javax.mail.Message
import javax.mail.Session
class ReceiveEmail {
companion object{
fun receiveEmail(
google : Boolean,
pop3Host : String,
storeType : String,
user : String,
password : String
){
val TAG = "MainActivity"
var prop = Properties()
//prop.put("mail.imaps.host", pop3Host)
//prop.put("mail.imaps.port","993")
//prop.put("mail.imaps.socketFactory.class","javax.net.ssl.SSLSocketFactory")
prop.put("mail.imaps.starttls.enable", "true")
prop.put("mail.imaps.auth", "true")
prop.put("mail.imaps.ssl.enable","true")
prop.put("mail.imaps.ssl.trust","*")
prop.put("mail.imaps.auth.mechanisms","XOAUTH2")
prop.put("mail.store.protocol","imaps")
var session = Session.getInstance(prop)
Log.w(TAG,"-----TEST START-----")
try {
Log.w(TAG,"-----TEST BP1-----")
//var mailStore = session.getStore(storeType)
var mailStore = session.getStore(storeType)
Log.w(TAG,"-----TEST BP2-----")
mailStore.connect(pop3Host, 993, user, password.toString())
Log.w(TAG,"-----TEST BP3-----")
var folder : Folder = mailStore.getFolder("INBOX")
Log.w(TAG,"-----TEST BP4-----")
folder.open(Folder.READ_ONLY)
Log.w(TAG,"-----TEST BP5-----")
var emailMessage = folder.getMessages()
Log.w(TAG,"Total Message - " + emailMessage.size)
var i = 1
for(mess : Message in emailMessage){
var toAddSize : Int = mess.getRecipients(Message.RecipientType.TO).size
var toAdress = mess.getRecipients(Message.RecipientType.TO)
Log.w(TAG,"-----TEST BP6-----")
Log.w(TAG,"EMAIL : "+ i.toString() + "/"+emailMessage+1)
Log.w(TAG,"Subject : "+ mess.subject)
Log.w(TAG,"From : "+mess.from[0])
}
folder.close()
mailStore.close()
}catch(e : Exception ){
Log.w(TAG, "ERROR:"+e.toString())
Log.w(TAG, "ERROR MESSAGE : " + e.message.toString())
Log.w(TAG, "ERROR MESSAGE : " + e.printStackTrace())
}
}
}
}

Related

io.ktor.client.features.ClientRequestException: Client request invalid

When calling the getUser function, I make an HTTP request that retrieves information about a user.
If the user does not exist I get the error:
io.ktor.client.features.ClientRequestException: Client request(https://api.intra.chocolat.fr/v2/users/fff) invalid: 404 Not Found. Text: "{}"
I am unable to catch the error, and to continue the execution of the program.
package com.ksainthi.swifty.api
import android.util.Log
import androidx.annotation.Keep
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.features.*
import io.ktor.client.features.json.*
import io.ktor.client.features.json.serializer.*
import io.ktor.client.features.observer.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.serialization.*
class Api42Service {
#Keep
#Serializable
data class Token(
#SerialName("access_token") val accessToken: String,
#SerialName("token_type") val tokenType: String,
#SerialName("expires_in") val expiresIn: Int,
#SerialName("scope") val scope: String,
#SerialName("created_at") val createdAt: Int
)
#Keep
#Serializable
data class User(
#SerialName("id") val id: Int,
#SerialName("email") val email: String,
#SerialName("login") val login: String? = null,
#SerialName("first_name") val firstName: String? = null,
#SerialName("last_name") val lastName: String? = null,
)
private var accessToken: String? = null
private var client: HttpClient = HttpClient() {
install(JsonFeature) {
serializer = KotlinxSerializer(kotlinx.serialization.json.Json {
prettyPrint = true
isLenient = true
ignoreUnknownKeys = true
})
}
}
private val API_URL: String = "https://api.intra.chocolat.fr"
private val API_SECRET: String =
"<secret>"
private val API_UID: String =
"<api_uid>"
suspend fun requestAPI(
requestMethod: HttpMethod,
path: String,
params: MutableMap<String, String>?
): HttpResponse {
val urlString = API_URL
.plus(path)
return client.request(urlString) {
method = requestMethod
params?.forEach { (key, value) ->
parameter(key, value)
}
headers {
accessToken?.let {
println(it)
append(HttpHeaders.Authorization, "Bearer $it")
}
}
}
}
suspend fun getToken(): Token {
val params: MutableMap<String, String> = HashMap()
params["grant_type"] = "client_credentials";
params["client_secret"] = API_SECRET;
params["client_id"] = API_UID;
val response = requestAPI(HttpMethod.Post, "/oauth/token", params);
val token: Token = response.receive()
accessToken = token.accessToken
return token
}
suspend fun getUser(login: String): User? {
try {
val response = requestAPI(HttpMethod.Get, "/v2/users/$login", null);
val user: User = response.receive()
return user
} catch (cause: io.ktor.client.features.ClientRequestException) {
Log.d("wtf", "Catch your error here")
}
return null
}
}

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)

Add markers to a map with Firebase

I want to make an application with Kotlin and Google Maps in which the user can add markers on the Google Map and that these markers are sent to Firebase and other users can see those same markers on the map.
This is what I have done but it is not working well for me.
package com.racrapa.displayinglocationapp
import android.content.ContentValues
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.annotation.NonNull
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.firebase.database.*
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
private const val TAG = "MapsActivity"
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
public lateinit var databaseRef: DatabaseReference
private lateinit var database: DatabaseReference
private var markers: MutableList<Marker> = mutableListOf()
private var postListener: ValueEventListener? = null
var mDatabase: DatabaseReference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
databaseRef = Firebase.database.reference
mDatabase = FirebaseDatabase.getInstance().reference.child("userlocation")
database = Firebase.database.reference
}
This is to get the data from Firebase
public override fun onStart() {
super.onStart()
var postListener: ValueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
val locationlogging = dataSnapshot.child("userlocation").getValue(LocationLogging::class.java)
var driverLat=locationlogging?.Latitude
var driverLong=locationlogging?.Longitude
if (driverLat != null && driverLong != null) {
val driverLoc = LatLng(driverLat, driverLong)
val markerOptions = MarkerOptions().position(driverLoc).title("Driver")
mMap.addMarker(markerOptions)
Toast.makeText(applicationContext, "Locations accessed from the database", Toast.LENGTH_LONG).show()
}
}
}
override fun onCancelled(error: DatabaseError) {}
}
databaseRef.addValueEventListener(postListener)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
mMap.setOnMapLongClickListener { latLng ->
Log.i(TAG, "onMapLongClickListener")
setMapLongClick(latLng)
}
}
This is the function of sending coordinates to Firebase
private fun setMapLongClick(latLng: LatLng) {
if (latLng != null) {
Log.e("Latitude: ", latLng.latitude.toString() + "longitude: " + latLng.longitude)
val latlang: MutableMap<String, Double> = HashMap()
latlang["latitude"] = latLng.latitude
latlang["longitude"] = latLng.longitude
mDatabase!!.child("userlocation").push().setValue(latlang)
onStart()
}
}
}

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
)