I am exploring Firebase Storage and have created a new folder named "data" on my app's firebase console, with a file inside named "info.json".
Since it's a new project and I don't have authentication setup, I copied the public security rules and applied them for the app:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
So far, I have only been using firebase-core for analytics, so I added firebase-storage. Firebase dependencies:
dependencies {
api 'com.google.firebase:firebase-storage:15.0.0'
api 'com.google.firebase:firebase-core:15.0.0'
}
Here's my code, copied from Firebase samples:
val storage = FirebaseStorage.getInstance()
val storageRef = storage.reference
val pathReference = storageRef.child("data/info.json")
val ONE_MEGABYTE = (1024 * 1024).toLong()
val task = pathReference.getBytes(ONE_MEGABYTE).addOnSuccessListener {
d { it.toString() }
}.addOnFailureListener {
it.printStackTrace()
d { it.toString() }
}
I am getting this error from last couple of hours:
E/StorageUtil: error getting token
java.util.concurrent.ExecutionException:
com.google.firebase.FirebaseApiNotAvailableException: firebase-auth is
not linked, please fall back to unauthenticated mode.
Related
I'm new to Android development and I have a direct question. I'm trying to save multiple images in Firebase storage in one task and get the respective DownlaodUrl. When I apply the code below, I get an error message.
java.lang.ClassCastException: com.google.firebase.storage.UploadTask$TaskSnapshot cannot be cast to com.google.firebase.storage.UploadTask
Follow implementation I use
import com.google.firebase.storage.UploadTask
val tasks = mutableListOf<UploadTask>()
var uploadTask = spaceRef.putBytes(data)
tasks.add(uploadTask)
Tasks.whenAllSuccess<UploadTask>(tasks).addOnSuccessListener { uploadTasks ->
val downloadUrls = mutableListOf<Uri>()
lifecycleScope.launch {
uploadTasks.forEach {
downloadUrls.add(it.await().storage.downloadUrl.await())
}
}
}
i trying to make application with google calendar api and following google documentation.
but I found this error and showed it to AuthorizationCodeInstalledApp function
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/sun/net/httpserver/HttpServer;
can someone tell me how this can happen and how to solve it?
this is my code
#Throws(IOException::class)
private fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): Credential? {
// Load client secrets.
val `in`: InputStream = assets.open(CREDENTIALS_FILE_PATH)
val clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(`in`))
// Build flow and trigger user authorization request.
val tokenFolder = File(
"${getExternalFilesDir(null)}${File.separator.toString() + TOKENS_DIRECTORY_PATH}"
)
if (!tokenFolder.exists()) {
tokenFolder.mkdirs()
}
val acct = GoogleSignIn.getLastSignedInAccount(this)
val username = acct?.id
val flow = (GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES
)
.setDataStoreFactory(FileDataStoreFactory(tokenFolder))
.setAccessType("offline")).build()
val receiver = (LocalServerReceiver.Builder().setPort(8888)).build()
//returns an authorized Credential object.
return AuthorizationCodeInstalledApp(flow, receiver).authorize(username)
}
From what I found by looking at other similar issues is that its a dependency version issue, I switched to an older version of dependencies and got a bit further than this.
the the dependencies i used:
implementation 'com.google.api-client:google-api-client:1.32.1'
implementation 'com.google.oauth-client:google-oauth-client-jetty:1.30.4'
implementation 'com.google.apis:google-api-services-sheets:v4-rev20220927-2.0.0'
I followed the procedure on Google Cloud to register my application by package name with Firebase, installed the resulting google-services.json file in the project’s app folder, and selected the bucket listed in that JSON file with the Kotlin sequence:
val firebaseStorage = Firebase.storage("gs://my-buckets-name.appspot.com")
val pictureRef = firebaseStorage.getReference("first_picture.jpg")
Note: my-buckets-name is not the name of my bucket.
But the upload task fails with a Permisson Denied exception, as shown in the LogCat subwindow.
I have no problem uploading files with the gsutil command on Windows 10 to the same bucket.
I tried making my bucket (briefly!) available allUsers, with NO SUCCESS. Any suggestions for how to debug this would be appreciated. Thanks.
Per a request, here are what I believe are the rules from the Firebase web-based console:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
And what is this "if request.auth != null" all about? What if request.auth is NULL? Where is this set in the Android programming?
The URL is:
https://console.firebase.google.com/project/my-buckets-name/storage/my-buckets-name.appspot.com/rules
Where again I substituted the fake "my-buckets-name" for the real name of the bucket.
And here is the file upload programming from my Android app. Parameter "thePath" is the path to the .JPG I want to upload; path has been verified:
private fun uploadToGoogleCloud(thePath : String)
{
val firebaseStorage = Firebase.storage("gs://my-buckets-name.appspot.com")
val pictureRef = firebaseStorage.getReference("first_picture.jpg")
val theFile = File(thePath)
val uriFile = Uri.fromFile(theFile)
if (uriFile == null) {
display.text = "Failed to get a URI file from " + thePath
return
}
var uploadTask = pictureRef.putFile(uriFile)
uploadTask.addOnFailureListener {
display.text = "Upload to Google Cloud failed: " + it.message //always comes here
}.addOnSuccessListener {
display.text = "Upload to Google Cloud completed"
}
}
I have an android application which uses Firebase Authentication via Facebook. A user can delete their account in the application using the following function:
override fun deleteUserAcc() {
val user = FirebaseAuth.getInstance().currentUser
val userToken = FacebookAuthProvider.getCredential(authTokenProvider.provideToken())
user?.reauthenticate(userToken)?.addOnCompleteListener { task ->
user.delete()
}
}
After this a user really gets deleted on the Firebase servers. However when they try to access the application again and log in one more time, they are not able to do this (their account with uid had been deleted and somehow they are not assigned a new one uid).
The login function and the onSuccess callback are both implemented and called.
override fun login(): Completable {
LoginManager.getInstance().logInWithReadPermissions(
activityReference.get(),
listOf("public_profile", "user_birthday", "user_location")
)
return CompletableSubject.create().apply {
loginSubject = this
}
}
override fun onSuccess(result: LoginResult) {
val credential = FacebookAuthProvider.getCredential(result.accessToken.token)
authTokenProvider.saveToken(result.accessToken.token)
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
getInfoOnFirestore(loginSubject)
} else {
loginSubject.onError(task.exception!!)
}
}
}
What can possibly be the cause of the following issue?
A little late to the party but I know what the issue is. Firebase deletes only the authentication, which means that the real-time database is still there with the same uid. In order to delete the database entry as well, you need to upgrade to the blaze program and add the extension.
I have an App with Firestore. I have a lot of Repositories. They work from Firestore. When I call 2 method in same time then I got an error.
class CommentRepository : CommentRepositoryInterface {
val firebaseFirestore = FirebaseFirestore.getInstance()
companion object {
const val COLLECTION_NAME = "post_comments"
const val COMMENT_POST_ID_KEY = "postid"
}
override fun getPostCommentsById(postId: String): Observable<CommentModel> {
return Observable.create { subscriber ->
firebaseFirestore.collection(COLLECTION_NAME)
.whereEqualTo(COMMENT_POST_ID_KEY, postId)
.get()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
for (document in task.result) {
if (document.exists()) {
val documentModel = document.toObject(CommentModel::class.java)
subscriber.onNext(documentModel)
}
}
subscriber.onComplete()
} else {
subscriber.onError(task.exception!!) // TODO
}
}
}
}
}
The another one is almost same like that, but that one is using another collection.
So when I called these functions, then I got the next error:
Internal error in Firestore (0.6.6-dev).
Caused by: java.lang.RuntimeException: Failed to gain exclusive lock to the Firestore client's offline persistence. This generally means you are using Firestore from multiple processes in your app. Keep in mind that multi-process Android apps execute the code in your Application class in all processes, so you may need to avoid initializing Firestore in your Application class. If you are intentionally using Firestore from multiple processes, you can only enable offline persistence (i.e. call setPersistenceEnabled(true)) in one of them.
In the MyApplication class I tried to set the Singleton's of firestore settings.
val settings = FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(true)
.build()
FirebaseFirestore.getInstance().firestoreSettings = settings
I found it in Firestore's Doc:
For Android and iOS, offline persistence is enabled by default.
Anyone have idea to solve this problem?
I've cleared the App's Caching and the problem solved.
Do it or just remove from the phone! :)