I'm new to Firestore. I need to show two of the values of the fields, "category" and "title" 3, of documents in Firestore in one row of LazyColumn like this 1. I tried some codes as below but they are shown like this 2. Is it possible?
My code of MainActivity
var t = mutableListOf<String>()
db.collection("posts")
.get()
.addOnSuccessListener { result ->
for (document in result) {
val category = document.data["category"].toString()
val title = document.data["title"].toString()
t.add(category)
t.add(title)
Log.d("black", "${document.id} => ${category}")
Log.d("red", "${document.id} => ${title}")
}
}
.addOnFailureListener { exception ->
Log.w("gray", "Error getting documents.", exception)
}
My code of View
LazyColumn(
modifier = Modifier.background(Beige),
verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(5.dp)
) {
items(posts) { post ->
Row(
modifier = Modifier
.fillMaxWidth()
.selectable(
selected = true,
onClick = { navController.navigate("PostContent") }
)
.background(Color.White, RoundedCornerShape(5.dp))
) {
Text(
text = "$post/category\n$post/title",
color = Brown,
modifier = Modifier
.padding(40.dp)
)
}
Thank you.
CodePudding user response:
You have a bad implementation of the storing mechanism.
In the class where you are calling the database, add this line of code
data class Post(category: String, title: String)
Then, update the t
variable like so
var t = mutableStateListOf<Post>()
Then, update the storing mechanism
db.collection("posts")
.get()
.addOnSuccessListener { result ->
for (document in result) {
val category = document.data["category"].toString()
val title = document.data["title"].toString()
t.add(Post(category, title))
Log.d("black", "${document.id} => ${category}")
Log.d("red", "${document.id} => ${title}")
}
}
.addOnFailureListener { exception ->
Log.w("gray", "Error getting documents.", exception)
}
Now, I assume it is the same t
variable you are somehow accessing in your LazyColumn
as posts
, so update that code like this
LazyColumn {
items(posts) { post ->
Row(
modifier = Modifier
.fillMaxWidth()
.selectable(
selected = true,
onClick = { navController.navigate("PostContent") }
)
.background(Color.White, RoundedCornerShape(5.dp))
) {
Text(
text = "${post.category}\n${post.title}",
color = Brown,
modifier = Modifier
.padding(40.dp)
)
}
All done, modify the design however you like, the logic is good like this.