I want to show a data whose values I have determined myself in text - android

calculateButton.setOnClickListener {
val panelC = binding.panelCount.text.toString()
val panelS = binding.panelSize.text.toString()
val landS = binding.landSlope.text.toString()
val landSi = binding.landSize.text.toString()
val cit = binding.city.text.toString()
val sun = (1000).toInt()
val air = (1.25).toFloat()
val cel = (25).toInt()
val verim = ((sun * air)/ cel).toString().toDouble()
if (panelC.equals("") || panelS.equals("")|| landS.equals("")|| landSi.equals("")||cit.equals("")){
Toast.makeText(requireContext(),"Alanları Doldurunuz.", Toast.LENGTH_SHORT).show()
}
else{
val action = SignUpCalculateFragmentDirections.actionSignUpCalculateFragmentToDataFragment()
Navigation.findNavController(view).navigate(action)
}
val postMap = hashMapOf<String, Any>()
postMap.put("Panel Sayisi",binding.panelCount.text.toString())
postMap.put("Panel Boyutu",binding.panelSize.text.toString())
postMap.put("Arazi Eğimi",binding.landSlope.text.toString())
postMap.put("Arazi Boyutu",binding.landSize.text.toString())
postMap.put("Şehir",binding.city.text.toString())
postMap.put("date", Timestamp.now())
postMap.put("verim",verim.toString().toDouble())
firestore.collection("Posts").add(postMap).addOnFailureListener {
}.addOnFailureListener {
Toast.makeText(requireContext(),it.localizedMessage,Toast.LENGTH_SHORT).show()
}
There is a calculatePage Fragment Codes. On this page, I am trying to make a yield calculation based on the data I receive from the user. However, I need to add the values that are kept constant in the efficiency calculation, such as "sun", "cel", "air" that I defined in the code. I wrote a random operation there as an example. To see if I can write inside the text I'm trying to print without getting any errors. But the app crashed.
private fun getData(){
firestore.collection("Posts").addSnapshotListener { value, error ->
if (error!=null){
Toast.makeText(requireContext(),error.localizedMessage,Toast.LENGTH_SHORT).show()
}else{
if (value !=null){
if (!value.isEmpty){
val documents = value.documents
for (document in documents){
val pc = document.get("Panel Sayisi") as String
val ps = document.get("Panel Boyutu") as String
val ls = document.get("Arazi Eğimi") as String
val lsi = document.get("Arazi Boyutu") as String
val c = document.get("Şehir") as String
val v = document.get("verim") as Double
val post = Post(pc,ps,ls,lsi,c,v)
postArrayList.add(post)
}
}
}
}
val db = FirebaseFirestore.getInstance()
db.collection("Posts").orderBy("date",Query.Direction.DESCENDING).limit(1)
.get()
.addOnCompleteListener {
val result : StringBuffer = StringBuffer()
if (it.isSuccessful){
for (document in it.result){
result.append(document.data.getValue("verim"))
}
verimText.setText(result)
}
}
On this page, I added the values I defined in my class named 'post' to the postList and added them to Firestore.
data class Post(val pc: String, val ps: String, val ls: String, val lsi: String, val c: String, val v : Double)
#ServerTimestamp
var date: Date? = null
This is my post class
The error is like this: java.lang.NullPointerException: null cannot be cast to non-null
type kotlin.Double
As I explained at the beginning of my question, what I am trying to do is using both the data such as "panelCount", "panelSize" that I get from the user and the "sun", "cel", "air" values that are defined as constants, using the "verimText.setText(result)" in the DataFragment page. I need to show this calculation to the user.
The user enters values such as 'Panel Sayisi', 'Panel Boyutu' that should be used while calculating on the calculation page. I need to show this to the user in verimText using both this data and the 'cel', 'sun', 'air' constants that I wrote in the first code.
PS: verim: 20000 value is the result of hypothetical values that I wrote in the first code. In this part, I need to make a calculation using the other data entered by the user and these constant values and show it in the verimText.

Related

The data I get from Firebase does not enter the if else control

val energy = enerjiText.text.toString()
if (energy < 50 .toString()){
progressBar.max = 1000
val currentProgress = 900
ObjectAnimator.ofInt(progressBar,"progress",currentProgress)
.setDuration(2000)
.start()
progressBar2.max = 1000
val currentProgress2 = 700
ObjectAnimator.ofInt(progressBar2,"progress",currentProgress2)
.setDuration(2000)
.start()
}
else{
progressBar.max = 1000
val currentProgress = 600
ObjectAnimator.ofInt(progressBar,"progress",currentProgress)
.setDuration(2000)
.start()
progressBar2.max = 1000
val currentProgress2 = 300
ObjectAnimator.ofInt(progressBar2,"progress",currentProgress2)
.setDuration(2000)
.start()
}
The id of the textView circled in black is enerjiText. In this textView I am printing the data that I have saved in firestore. But without checking the values ​​in the if-else loop you see in the code, the progress bars inside the if push the screen. I gave the value of energy < 50 in the if, the answer is 227, but it shows the progress bar values ​​in the if without going into the else loop. If I don't convert the enerjiText and the energy < 50 control to string I get the error "java lang numberformatexception For input string"
val panelC = binding.panelCount3.text.toString()
val landSl = binding.landSlope.text.toString()
val landS = binding.landSize3.text.toString()
val billT = binding.bill.text.toString()
if (panelC.isEmpty() || landSl.isEmpty() || landS.isEmpty() || billT.isEmpty()){
Toast.makeText(requireContext(),"Alanları Doldurun",Toast.LENGTH_LONG).show()
}
else{
val pco = panelC.toInt()
val lsl = landSl.toInt()
val ls = landS.toInt()
val b = billT.toInt()
val enerji = Math.round((((ls * pco) + (lsl * b)) / 100).toDouble())
val postMap = hashMapOf<String,Any>()
postMap.put("Panel Sayisi",binding.panelCount3.text.toString())
postMap.put("Arazi Eğimi",binding.landSlope.text.toString())
postMap.put("Arazi Boyutu",binding.panelCount3.text.toString())
postMap.put("Fatura",binding.bill.text.toString())
postMap.put("Enerji",enerji.toDouble())
postMap.put("date",com.google.firebase.Timestamp.now())
firestore.collection("Enerji").add(postMap).addOnSuccessListener {
}.addOnFailureListener {
Toast.makeText(requireContext(),it.localizedMessage,Toast.LENGTH_LONG).show()
}
These codes are the codes where the calculations of the number that should be written in enerjiText are made and saved in firestore.
private fun getData(){
db.collection("Enerji").addSnapshotListener { value, error ->
if (error!=null){
Toast.makeText(requireContext(),error.localizedMessage,Toast.LENGTH_LONG).show()
}else{
if (value !=null){
if (!value.isEmpty){
val documents = value.documents
for (document in documents){
val panelSayisi = document.get("Panel Sayisi") as String
val araziEgimi = document.get("Arazi Eğimi") as String
val araziBoyutu = document.get("Arazi Boyutu") as String
val faturaDegeri = document.get("Fatura") as String
val enerji = Enerji(panelSayisi, araziEgimi, araziBoyutu, faturaDegeri)
postArrayList.add(enerji)
}
}
}
}
val db = FirebaseFirestore.getInstance()
db.collection("Enerji").orderBy("date", Query.Direction.DESCENDING).limit(1)
.get()
.addOnCompleteListener {
val result : StringBuffer = StringBuffer()
if (it.isSuccessful){
for (document in it.result){
result.append(document.data.getValue("Enerji"))
}
enerjiText.setText(result)
}
}
}
These are the codes that I get the data I saved in firebase above and wrote into EnerjiText.
data class Enerji (val panelSayisi : String, val araziEgimi : String, val araziBoyutu : String, val faturaDegeri : String)
Finally, the Enerji class defined inside the postArrayList, which I think might be the source of the error.

What should I do to print only the last data entered in Text?

private fun getData(){
firestore.collection("Posts").addSnapshotListener { value, error ->
if (error!=null){
Toast.makeText(requireContext(),error.localizedMessage,Toast.LENGTH_SHORT).show()
}else{
if (value !=null){
if (!value.isEmpty){
val documents = value.documents
for (document in documents){
val pc = document.get("Panel Sayisi") as String
val ps = document.get("Panel Boyutu") as String
val ls = document.get("Arazi Eğimi") as String
val lsi = document.get("Arazi Boyutu") as String
val c = document.get("Şehir") as String
val post = Post(pc,ps,ls,lsi,c)
postArrayList.add(post)
}
}
}
}
val db = FirebaseFirestore.getInstance()
db.collection("Posts").orderBy("Panel Sayisi",Query.Direction.DESCENDING).limit(1)
.get()
.addOnCompleteListener {
val result : StringBuffer = StringBuffer()
if (it.isSuccessful){
for (document in it.result){
result.append(document.data.getValue("Panel Sayisi"))
}
verimText.setText(result)
}
}
}
}
It shows all the data I have added to Cloud Firestore that has the keyword "Panel Sayisi" in verimText. I only want the last data entered to be displayed.
Here is the problem. The last file I added is added in the middle. That's why the value I call last or the first call doesn't change. So it always calls the same value. This middle value should be written at the end or at the beginning. So I can get this data by calling ASCENDING or DESCENDING method.
When you are using the following call to:
.orderBy("Panel Sayisi",Query.Direction.DESCENDING)
It means that are only ordering the documents according to the "Panel Sayisi" field, which doesn't actually solve the problem. The problem is that you don't know that the "c4Q5...q4vP" document is the last document that was added. To solve this issue, you have to add an additional field of type Firestore Timestamp, as explained in my answer from the following post:
How to add Firebase Timestamp when adding an object of a data class to the Firestore in Kotlin?
And then use the following query:
val db = FirebaseFirestore.getInstance()
val query = db.collection("Posts").orderBy("timestamp", Query.Direction.DESCENDING).limit(1)

Type mismatch: inferred type is com.google.firebase.firestore.auth.User but com.example.socialmediaapp.model.User was expected

Error is showing for the user when passed in post i.e val post = Post(text, user, currentTime)
class PostDao {
private val db = FirebaseFirestore.getInstance()
private val postCollection = db.collection("posts")
private val auth = Firebase.auth
fun addPost(text:String){
val currentUserId = auth.currentUser!!.uid
GlobalScope.launch {
val userDao = UserDao()
//getting actual user document from the task through user id
val user = userDao.getUserById(currentUserId).await().toObject(User::class.java)!!
val currentTime = System.currentTimeMillis()
val post = Post(text, user, currentTime)
}
}
}
Here is the Post data class :
data class Post(
val text:String = "",
val createdBy: User = User(),
val createdAt:Long = 0L,
val likedBy: ArrayList<String> = ArrayList()
)
Please help me solve this issue.
Thank you !
This is because you are not using same user object at both of the places. You need to declare and get same type of USER class in your code.
You are trying to get the value of com.google.firebase.firestore.auth.User but com.example.socialmediaapp.model.User is expected as per your code.

how to get position of deleted Firestore Data that have been deleted from console (outside source) to update Or notify the adapter

I have this app that someone can delete his document at any time so if he deletes the document I want every other user to get updated the document has been removed and remove the document from the listView, it's more like a Food Ordering app so the user order could be taking by another Driver so the document will no longer be available for other users, I want to update the recyclerView Whenever a user deletes a document, so how to get the position without clicking how to detect that change to get the position, Sorry if I couldn't explain much I'm Using Groupie Adapter
val ref = firestore.collection("orders").whereNotEqualTo("userUid", uid)
val adapter = GroupAdapter<GroupieViewHolder>()
ref.addSnapshotListener { value, error ->
if (error != null){
return#addSnapshotListener
}
value?.documentChanges?.forEach {
if (it.type == DocumentChange.Type.ADDED) {
val userUid = it.document.data.get("userUid") as String
val userPhone = it.document.data.get("phone") as String
val userName = it.document.data.get("name") as String
val time = it.document.data.get("time") as String
val marketName = it.document.data.get("marketName") as String
val amount = it.document.data.get("amount") as String
val storeimgUrl = it.document.data.get("storeImg") as String
val order = it.document.data.get("order") as String
val userImg = it.document.data.get("userImg") as String
adapter.add(DriverOrders(userUid, userPhone, userName, time, marketName, amount, storeimgUrl, order, userImg))
adapter.notifyDataSetChanged()
}
if(it.type == DocumentChange.Type.REMOVED){
// here Wher I'm trying to get the position of deleted Or removed data
if (it.document.id == DriverOrders.docId){
adapter.notifyItemRemoved(it.oldIndex)
}
}
}
recyclerview_driverorders.adapter = adapter
}
class DriverOrders(val userUid: String, val userPhone: String,
val userName: String, val time: String,
val marketName: String, val amount: String, val storeimgUrl: String, val order: String,
val userImg: String):Item<GroupieViewHolder>() {
override fun getLayout(): Int {
return R.layout.driver_row
}
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
viewHolder.itemView.driverorders_sName.text = marketName
viewHolder.itemView.driverorders_order.text = order
viewHolder.itemView.driverorders_time.text = Date
Picasso.get().load(storeimgUrl).fit().into(viewHolder.itemView.driverorders_sImg)
}
}

HashMap is null so i cant get my data shown in the emulator from Firebase database

Android studio showed a warning so with ALT + ENTER the code
val name = data[USERNAME] as String
became
val name = data?.get(USERNAME) as String
but my emulator is still crashing
thoughtsCollectionRef.get()
.addOnSuccessListener { snapshot ->
for(document in snapshot.documents){
val data = document.data
//this is my code after listening to android studio
val name = data?.get(USERNAME) as String
val timestamp = data?.get(TIMESTAMP) as Date
val thoughtTxt = data?.get(THOUGHT_TXT) as String
val numLikes = data?.get(NUM_LIKES) as Long
val numComments = data?.get(NUM_COMMENTS) as Long
val documentId = document.id
//I edited every other variable with the safecall ?.get() and its still crashing
val newThought = Thought(name,timestamp,thoughtTxt,numLikes.toInt(),numComments.toInt(),
documentId)
thoughts.add(newThought)
}
thoughtsAdapter.notifyDataSetChanged()
The data?.get(TIMESTAMP) call returns a Firebase Timestamp object. So instead of casting it to Date, you should cast it to com.google.firebase.Timestamp:
// imports
import com.google.firebase.Timestamp
...
// rest of the code
val timestamp = data?.get(TIMESTAMP) as? Timestamp
If you want to end up with a Date object, you can use the Timestamp method toDate():
val date = timestamp?.toDate()
Also note that you should use a safe casting operator as? instead of as in this case:
val name = data?.get(USERNAME) as? String
val timestamp = data?.get(TIMESTAMP) as? Timestamp
val thoughtTxt = data?.get(THOUGHT_TXT) as? String
val numLikes = data?.get(NUM_LIKES) as? Long
val numComments = data?.get(NUM_COMMENTS) as? Long
The data?.get(KEY) may produce a null object, which can't be cast to any type and the operation will result in a crash.

Categories

Resources