Can we use firebase console to upload images manually? - android

In my app , I have to display images in RecyclerView from Firebase database but the problem is I don't want to upload images using my app but I want them to be manually added using console of Firebase storage and later use their location to be added in Firebase database. I tried doing this way but glide is not loading the images. So is there any way to upload images manually and load images in app ?
Edited :
enter image description here
Look at my image, I have simply added the storage location of image in my database table. After then I am using those functions to get the image location and loading them with the help of glide library.
Here is my code of retrieving categories from Firebase database.
fun getCategories() : List<Categories>{
val categoriesList = mutableListOf<Categories>()
CoroutineScope(IO).launch {
databaseReference.child("categories")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (postSnapshot in dataSnapshot.children) {
val categories = postSnapshot.getValue(Categories::class.java)
categoriesList.add(categories!!)
}
}
override fun onCancelled(p0: DatabaseError) {
}
})
}
return categoriesList
}
And after retrieving categories list ,I am loading my Images in Adapter class. Here is my Adapter class code
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val model = modelList[position]
holder.nameOfFruit?.text = model.name
holder.nameOfFruit?.setOnClickListener {
it.findNavController().navigate(R.id.action_mainFragment_to_choiceSelectedFragmentModel)
}
Glide.with(myContext!!).load(model.url).into(holder.imageOfFruit)
}
Edited : It is my image URL stored in my database.
enter image description here

You've stored a "gs://" URL in your database. This is a special Cloud Storage URL that only works with Google infrastructure. It will not work in browsers or applications.
You will have to instead store a download URL in the database. If you've done it correctly, it will start with "https://".

Related

Firebase Storage. Is it possible to parallelize queries when upload an image?

I want to upload user avatar into Firebase Storage. When I do this, I remove all previous avatars.
Also I need to keep user updated with my local storage and Realtime Database.
Is it possible to do it in faster way?
override suspend fun uploadImage(uri: Uri) = withContext(dispatchers.io) {
val user = remoteRepository.getUser() // I do several parallel queries when save edited user info
clearPreviousImages(user.id) // so, I guess, I need remote user below
val fileName = "${user.id}/${uri.lastPathSegment}"
val uploadReference = referencesRepository.getImagesStorageReference().child(fileName)
uploadReference.putFile(uri).await()
val link = uploadReference.downloadUrl.await().toString()
val updatedUser = user.copy(avatar = link) // save image url in Realtime Database
remoteRepository.updateUser(updatedUser) // and return updated user
}
private suspend fun clearPreviousImages(userId: String) {
referencesRepository.getImagesStorageReference().child(userId).listAll().await()
.items
.forEach { it.delete().await() }
}
If I try to put clearPreviousImages in async block and remove await() inside forEach, I get the following error
Task is not yet complete
Can I speed up the upload?

how to get some child list from Firebase android kotlin?

How i can read just color item in the image with out all data sub child?
I try this
val database = FirebaseDatabase.getInstance()
val personalDataReference = database.getReference("user personal data")
val messageList = ArrayList<String>()
personalDataReference.addValueEventListener(object : ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot){
messageList.add(dataSnapshot.value.toString())
}
override fun onCancelled(error: DatabaseError) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException())
}
})
but it get all the data
Consider using the Firebase Kotlin SDK by GitLive.
This library is also multi-platform, so the same code can be used on both Android and on iOS via Kotlin Multiplatform Mobile.
The code to read the keys from Firebase realtime database would look like this:
val keys = db.reference("/path/to/user personal data")
.valueEvents
.first()
.children
.mapNotNull { it.key }
Note here that valueEvents is a Kotlin Flow of DataSnapshot, therefore you can do more than simply taking the first snapshot and mapping it to a list as shown above. See the Flow documentation.
The things you've marked yellow are known as keys in Firebase terms.
To get a list of only the keys, you can do:
personalDataReference.addValueEventListener(object : ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot){
for (childSnapshot in dataSnapshot.children) {
messageList.add(childSnapshot.key)
}
}
Note that this will still read all JSON from the database, but the list will only contain the keys.

How can I get data from firebase to data model?

I'm quite new at Kotlin. I have data class which hold image urls named testModel. I need to add data to model from firebase with that code:
Here my data model: class testModel(val imageLinks: List<String>)
private val dbRef = FirebaseDatabase.getInstance().reference.child("categories").child("1").child("top")
fun readDataFromFirebase(){
dbRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
var list = ArrayList<testModel>()
for (e in dataSnapshot.children){
println(e.value)
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.e("DB", "loadPost:onCancelled", databaseError.toException())
}
})
}
Actually this block can get value from firebase I can see in run console my image urls but I can't add these on my testModel. How can I make it? Also I need good tutorials for these kind of works, like data models, read and write data with Kotlin. I am waiting for your advice.
PS: I already tried getValue method but is give error java.lang.
In your dataclass, change List<String> with ArrayList<String>, because the type List<E> does not exist in firebase, but arrays do.
Save your data as an Array<String> in firebase and then when you retrieve your snapshot, do snapshot.toObject(TestModel::class)

How to store multiple images in one document(Firestore) Android

User should be able to upload multiple images in one post.
I tried to add all urls to a ArrayList and then to store them to firestore.
All I get are errors.
"imageList" returns always null
Here is my code:
fun uploadPost(images:ArrayList<Uri>, imageCount: Int, description:String){
images.forEach { image->
val imageRef = storageReferenence.child(System.currentTimeMillis().toString()
+"."+ image.lastPathSegment)
val uploadTask = imageRef.putFile((image))
uploadTask.addOnSuccessListener {
val downloadUrl = imageRef.downloadUrl
downloadUrl.addOnSuccessListener {uri->
Log.d("IMAGES", uri.toString())
imageList!!.add(uri.toString())
count++
}
}
}
//firebaseRepository.firestoreDB.collection("post").document(firebaseRepository.userid.toString()).update(post)
}
You can see that the Log has the url but when I try to add it to the imageList
it fails to do so.
THIS CAUSES THE ERROR: imageList!!.add(uri.toString())
ERROR MSG: AddViewModel$uploadPost$$inlined$forEach$lambda$1$1.onSuccess
I don`t really know what is better to store the images as an array or to store each image like this: image1:url... , image2: url..
I need them to be part of the same document.

Get random user from Firebase

I'm working on an application in kotlin for sending an image to a random user or to multiple user from firebase. My database is structured like this :
Users
bVk3KBL81AY2LUVUbC6G1qcLAcl2
username : test
uid : bVk3KBL81AY2LUVUbC6G1qcLAcl2
And I don't know how to get a random user from firebase, I searched but I don't find the best solution for my structure.
I try with this post : How to get unique random product in node Firebase?
But the code doesn't work I have multiple errors
Thank you in advance to any one who may be able to give me some solutions.
Edit #1
I've worked on it and it's working, but I don't know how limit the random to 3 users for example.
In my application the user can change the limit of user so I need to change the random limit.
My code :
fun chooseRandomUser() {
val rootRef = FirebaseDatabase.getInstance().getReference()
val productsRef = rootRef.child("users")
val valueEventListener: ValueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val productList = ArrayList<String?>()
for (ds in dataSnapshot.children) {
val name = ds.child("username").getValue(String::class.java)
productList.add(name)
Log.d("FragmentActivity", "usernames : $name")
}
val productListSize = productList.size
val randomProductList = ArrayList<kotlin.Int>()
randomProductList.add(Random().nextInt(productListSize))
Log.d("FragmentActivity", "list : $randomProductList")
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("FragmentActivity", "Error: ${databaseError.message}")
}
}
productsRef.addListenerForSingleValueEvent(valueEventListener)
}
As far as I could understand, you want to pick a random user from all the list of users that you have in your firebase database. You can simply do that on the android side.
I think you already know how to get all the users from the firebase database. Store the users in a list. Then I would try to come up with a random function which could give me an index of the list randomly and I could pick that user from the list based on that random index.
The same implementation can go for selecting multiple users from that list as well.
I hope that helps.

Categories

Resources