Can not get a key value from Firebase storage in kotlin - android

I cannot get a key value from firebase storage while datas exist in storage.
key = intent.getStringExtra("key").toString()
and they return null
binding.writebtn.setOnClickListener {
val title = binding.titleArea.text.toString()
val contents = binding.contentArea.text.toString()
val uid = FBAuth.getUid()
val time = FBAuth.getTime()
val key = FBRef.boardRef.push().key.toString()
FBRef.boardRef
.child(key)
.setValue(BoardModel(uid, title, contents, time))
and this is my saving function.
and as u can see, all datas are saved properly. But still I cannot get a key value.

If you want to get data from any database you need to use any clinter (Retrofit) if you have this code please share otherwise check this thread. The GetStringExtra() you are currently using is for getting shared data between android core components and it has nothing to do with firebase database.

Related

Saving user list data in android compose

So im trying to understand how data is saved on android. I am currently working on a simple notes app. How it currently works, is the user creates a new note, types whatever they want, and once they hit the back button that entry is saved in to a list. I am using compose viewmodel so the entries are saved up until the point the app is destroyed. what is the best way to save the list entries so they are pemenantly saved on the phone. This is also just a general question on how apps generally save user input data that is not saved in the cloud.
here is some example of the code.
data class NotesBlueprint(
val header: String,
val note: String,
val key: Int
)
data class NotesVars(
val header:String = "", <<<< instance of header and the note
val note: String = "" <<<<
var list: List<NotesBlueprint> = mutableListOf() <<< list that the Notes are saved in to
)
You can store the data on android via Shared Preference, Database, and Files. This storage overview guide gives the idea regarding different types of the storage system and how they are saved on android.
In your case, if you want to save notes which user has written, it would be better to go with the database.
Android provides the Room library for storing data in the local database. You can check out the guide here.

Read Map Values within Array Firestore Kotlin

I'm trying to retrieve and store the values within this Map in my Firestore. The way I have my Firestore set up is like so:
I've found a way to retrieve other fields within my Firestore database but when trying to access map values like so:
horsepowerTextView.text = result.data?.getValue("Horsepower").toString()
it crashes the application and gives me an error saying that "Key Horsepower is missing in the map".
Can you please tell me how I would be able to get the values within Cars?
The following picture shows Firestore layout and code:
I've tried this link (how to read mapped data from firestore in kotlin) but when creating the map it only retrieves the topmost variable in the document NOT a part of the Map which would be the values firstName and lastName:
I actually answered that question, but your use case is totally different than the linked one. Why? Simply because "Cars" is an array of maps (custom objects). If you only want to get the value of the "Horsepower" field, then simply use the following lines of code:
val db = Firebase.firestore
val usersRef = db.collection("users")
usersRef.document("TwbJb27eFL3HAS1xLhP1").get().addOnCompleteListener {
if (it.isSuccessful) {
val data = it.result.data
data?.let {
val cars = data["Cars"] as List<*>
for (car in cars) {
val carMap = car as Map<*, *>
val horsepower = carMap["Horsepower"]
Log.d(TAG, "$horsepower")
}
}
}
}
The result in the logcat will be:
120
If you want however to map the "Cars" array into a list of custom objects, then I recommend reading the following resource:
How to map an array of objects from Cloud Firestore to a List of objects?

Import JSON in Realtime Database programmatically, not manually

I want to be able to import a JSON file to Firebase with a button in my app. I know that you can add a JSON file manually in the Firebase Console, but in this case, I want to let my user import a JSON file with a button and update the info in Realtime Database. Can someone help me?
You would need first to convert the json to a map and then save it directly to the path you want:
val jsonMap = Gson().fromJson<Any>(stringJson, object : TypeToken<HashMap<String, Any>>() {}.type)
Firebase ref = new Firebase(YOUR_FIREBASE_PATH);
ref.setValue(jsonMap );
I want to be able to import a JSON file to Firebase manually
There is no API for doing that. If you want to let the user the possibility to add the content of a JSON file to the Realtime Database, then you should write some code for that. Meaning that you need to implement an option in which the user can upload the JSON file to the local storage, then in your app's code, you should read the file and get the data as JSON String. To convert it to a Map, you can simply use:
val jsonObj = JSONObject(jsonString)
val map = jsonObj.toMap()
Now, to write this Map object into the Realtime Database, in a location that corresponds only to a specific user, assuming that you are using Firebase Authentication, please use the following lines of code:
val uid = FirebaseAuth.getInstance().currentUser?.uid
val rootRef = FirebaseDatabase.getInstance()
val uidRef = rootRef.child("users").child(uid)
uidRef.setValue(map).addOnCompleteListener(/* ... /*)

Is there a better way of retriving Document Refernce?

I am new to Firestore and I am developing an android app where I am loading comments in Recycler View.
Below is sample data class for comment.
data class Comment(
val id: String,
val text: String,
val user: DocumentReference
)
Currently I am using this below code in onBindViewHolder in adapter
comment.userId.get()
.addOnCompleteListener {
if (it.isSuccessful) {
val u = it.result.toObject(User::class.java)
user = u.name
binding.userTv.text = user
}
}
binding.commentTv.text = comment.text
I have to explicitally run Task<TResult> every time to fetch the user in adapter.
I am looking for a better way to retrieve user from comment to display username is a single query.
Typically when dealing with usernames that may update regularly, traditionally you would store the raw user name string in each document which requires heavy read/writes to keep it updated. Instead, it has been found better to store them in a master document/collection that assigns all user UID's with the display name as the value, allowing you to look up any user UID and know it from one source of truth.
This has been made easier with the new Bundle Feature which allows all apps to preload documents in your app to prevent the need to fetch them every time. The only catch is you will need to retrieve the data when a new user isn't in their cached data yet or have a dedicated source for all new users to reduce overhead in those situations.
Source: Data Bundles

How can I get values of a child whose key is known to me?

I've got the key of specific child using snapshot.getkey(); and stored it in a string and now I want to access that child's values at other location.
Please check whether this may be useful.
You can get the collection object from firebase with the specific child key which you have stored in a string.
The following function will fetch the child object based on the key.You can implement this in javascript function at any point so that you can retrieve the data.
var firebaseRef = firebase.database().ref('CollectionName/' + key );
starCountRef.on('value', function(snapshot) {
var collectionObj = snapshot.val();
})

Categories

Resources