Cannot upload multiple files when using the firebase emulator
I have an angular web application that can upload multiple files to firebase storage. It works fine with the production server, but when I try to upload using the firebase emulator I get this error if I upload more that 2 files simultaneously (it works fine with 1 og 2 files):
> /Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:10960
> throw new Error(errorPrefix +
> ^
> Error: transaction failed: Data returned contains NaN in property 'files.referenceCount'
> at validateFirebaseData (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:10960:15)
> at /Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:11001:13
> at each (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:525:13)
> at validateFirebaseData (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:10984:9)
> at _loop_2 (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:11977:21)
> at repoRerunTransactionQueue (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:12030:9)
> at repoRerunTransactions (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:11929:5)
> at /Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:11910:13
> at /Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:3711:17
> at PersistentConnection.onDataMessage_ (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:3738:17)
> at Connection.onDataMessage_ (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:2532:14)
> at Connection.onPrimaryMessageReceived_ (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:2526:18)
> at WebSocketConnection.onMessage (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:2428:27)
> at WebSocketConnection.appendFrame_ (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:1141:18)
> at WebSocketConnection.handleIncomingFrame (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:1189:22)
> at Client.mySock.onmessage (/Users/jr/projects/docavea/functions/node_modules/@firebase/database/dist/index.standalone.js:1088:19)
My code to upload:
private pushFile(storageReference: firebase.storage.Reference, upload: Upload, uid: string) {
// set metadata when writing file so only the uploading user have read access to get the downloadURL
const metadata = {
customMetadata: {
uid
}
}
const uploadTask = storageReference.put(upload.file, metadata);
const startUploadProgress = this.uploadProgress;
let progressLastUpdated = 0;
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
(snapshot: any) => {
// upload in progress
// due to the way mat progress bar is made it causes flicker to update more often than every 250ms
// using 1000ms seems to make it fairly smooth
// https://github.com/angular/components/issues/15138
if (Date.now() - progressLastUpdated > 1000) {
progressLastUpdated = Date.now();
upload.progress = snapshot.bytesTransferred;
this.uploadBytesTransferred = 0;
this.uploads.forEach(upl => this.uploadBytesTransferred += upl.progress)
this.uploadProgress = startUploadProgress + (this.uploadBytesTransferred / this.uploadTotalSize) * (100 - startUploadProgress);
}
},
(error) => {
// upload failed
console.error(error);
},
() => {
// console.log('storage.service.ts:pushFile() Upload complete');
}
);
return uploadTask;
}
Is this a limitation in the storage emulator, or am I doing something wrong?
do you know?
how many words do you know
See also questions close to this topic
-
how to change prettier format for react native
my code formatting prettier didn't works well for react native, i don't understand where to config it but it works well with flutter
from this code
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( <View> <Text>Apps</Text> </View> ) }
it's formatted to this
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( < View > < Text > Apps < /Text> < /View> ) }
-
MarkLogic server-side JavaScript and XQuery
I am just starting using NoSQL MarkLogic DB and trying to choose for me the best query language to learn and use in future. On server side MarkLogic provides the possibility to use JavaScript API or XQuery API.
I want to receive an advice. Which language is better to concentrate on and learn? JavaScript or XQuery?
- Popover in chrome extension using js
-
StorageReference getFile doesn't work properly
I have a text file I'm storing on the Firebase database and I'm trying to retrieve the text as following:
File tempFile = File.createTempFile("tempfile", ".txt"); Path filename = tempFile.toPath(); FileDownloadTask fdt = gsReference.getFile(tempFile); fdt.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { @Override public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) { try { wholeFile = new String(Files.readAllBytes(filename), StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { Toast.makeText(MainActivity.this, "failed to read", Toast.LENGTH_LONG); } });
it worked once but now when debugging I see that the onSuccessListener is never called anymore, it skips right over to the next part of the code. I've seen a similiar question where someone said the getFile method doesn't work properly with SDK 29 so I tried limiting mine to 28 but still no luck.
EDIT: I added onFailure and put a breakpoint there, it skips over that part too (didn't stop at the breakpoint)
my build.gradle:
dependencies { implementation 'androidx.appcompat:appcompat:1.4.1' implementation 'com.google.android.material:material:1.5.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.3' implementation 'com.google.firebase:firebase-storage:20.0.1' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' implementation platform('com.google.firebase:firebase-bom:29.3.1') implementation 'com.google.firebase:firebase-analytics'}
-
Profile Pic not displaying on Card View in Andorid Studio Kotlin
I am trying to get a users profile pic to be displayed beside their booking on a card in my recyclerview. The profile pic is displaying in my nav drawer, a default one for non-google users, or the profile pic of the Google user. However imageUri appears empty when I call it and the images are not being stored in my firebase storage bucket. I have linked my firebase and implemented the relevant SDK.
Here is my model.
@Parcelize data class BookModel( // var id : Long = 0, var uid: String? = "", var name: String = "N/A", var phoneNumber: String = "N/A", var email: String? = "N/A", var date: String = "", var bike: Int = 0, var profilepic: String = "", /*var lat: Double = 0.0, var longitude: Double = 0.0, var zoom: Float = 0f,*/ var pickup: String = "", var dropoff: String = "", var price: Double = 20.0, /*var amount: Int = 0*/ ) : Parcelable { @Exclude fun toMap(): Map<String, Any?> { return mapOf( // "id" to id, "uid" to uid, "name" to name, "phoneNumber" to phoneNumber, "email" to email, "date" to date, "bike" to bike, "profilepic" to profilepic, "pickup" to pickup, "dropoff" to dropoff, "price" to price ) } } @Parcelize data class Location( var lat: Double = 0.0, var longitude: Double = 0.0, var zoom: Float = 0f, var depot: String = "Waterford" ) : Parcelable
Here is my FirebaseImageManager
package com.wit.mad2bikeshop.firebase import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.net.Uri import android.widget.ImageView import androidx.lifecycle.MutableLiveData import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.UploadTask import com.squareup.picasso.MemoryPolicy import com.squareup.picasso.Picasso import com.wit.mad2bikeshop.utils.customTransformation import timber.log.Timber import java.io.ByteArrayOutputStream import com.squareup.picasso.Target object FirebaseImageManager { var storage = FirebaseStorage.getInstance().reference var imageUri = MutableLiveData<Uri>() fun checkStorageForExistingProfilePic(userid: String) { val imageRef = storage.child("photos").child("${userid}.jpg") val defaultImageRef = storage.child("ic_book_nav_header.png") imageRef.metadata.addOnSuccessListener { //File Exists imageRef.downloadUrl.addOnCompleteListener { task -> imageUri.value = task.result!! } //File Doesn't Exist }.addOnFailureListener { imageUri.value = Uri.EMPTY } } fun uploadImageToFirebase(userid: String, bitmap: Bitmap, updating : Boolean) { // Get the data from an ImageView as bytes val imageRef = storage.child("photos").child("${userid}.jpg") //val bitmap = (imageView as BitmapDrawable).bitmap val baos = ByteArrayOutputStream() lateinit var uploadTask: UploadTask bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos) val data = baos.toByteArray() imageRef.metadata.addOnSuccessListener { //File Exists if(updating) // Update existing Image { uploadTask = imageRef.putBytes(data) uploadTask.addOnSuccessListener { ut -> ut.metadata!!.reference!!.downloadUrl.addOnCompleteListener { task -> imageUri.value = task.result!! } } } }.addOnFailureListener { //File Doesn't Exist uploadTask = imageRef.putBytes(data) uploadTask.addOnSuccessListener { ut -> ut.metadata!!.reference!!.downloadUrl.addOnCompleteListener { task -> imageUri.value = task.result!! } } } } fun updateUserImage(userid: String, imageUri : Uri?, imageView: ImageView, updating : Boolean) { Picasso.get().load(imageUri) .resize(200, 200) .transform(customTransformation()) .memoryPolicy(MemoryPolicy.NO_CACHE) .centerCrop() .into(object : Target { override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom? ) { Timber.i("DX onBitmapLoaded $bitmap") uploadImageToFirebase(userid, bitmap!!,updating) imageView.setImageBitmap(bitmap) } override fun onBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) { Timber.i("DX onBitmapFailed $e") } override fun onPrepareLoad(placeHolderDrawable: Drawable?) {} }) } fun updateDefaultImage(userid: String, resource: Int, imageView: ImageView) { Picasso.get().load(resource) .into(object : Target { override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom? ) { Timber.i("DX onBitmapLoaded $bitmap") uploadImageToFirebase(userid, bitmap!!,false) imageView.setImageBitmap(bitmap) } override fun onBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) { Timber.i("DX onBitmapFailed $e") } override fun onPrepareLoad(placeHolderDrawable: Drawable?) {} }) } }
My FirebaseAuthManager...
package com.wit.mad2bikeshop.firebase import android.app.Application import androidx.lifecycle.MutableLiveData import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.GoogleAuthProvider import com.wit.mad2bikeshop.R import timber.log.Timber class FirebaseAuthManager(application: Application) { private var application: Application? = null var firebaseAuth: FirebaseAuth? = null var liveFirebaseUser = MutableLiveData<FirebaseUser>() var loggedOut = MutableLiveData<Boolean>() var errorStatus = MutableLiveData<Boolean>() var googleSignInClient = MutableLiveData<GoogleSignInClient>() init { this.application = application firebaseAuth = FirebaseAuth.getInstance() if (firebaseAuth!!.currentUser != null) { liveFirebaseUser.postValue(firebaseAuth!!.currentUser) loggedOut.postValue(false) errorStatus.postValue(false) FirebaseImageManager.checkStorageForExistingProfilePic( firebaseAuth!!.currentUser!!.uid) } configureGoogleSignIn() } fun login(email: String?, password: String?) { firebaseAuth!!.signInWithEmailAndPassword(email!!, password!!) .addOnCompleteListener(application!!.mainExecutor, { task -> if (task.isSuccessful) { liveFirebaseUser.postValue(firebaseAuth!!.currentUser) errorStatus.postValue(false) } else { Timber.i("Login Failure: $task.exception!!.message") errorStatus.postValue(true) } }) } fun register(email: String?, password: String?) { firebaseAuth!!.createUserWithEmailAndPassword(email!!, password!!) .addOnCompleteListener(application!!.mainExecutor, { task -> if (task.isSuccessful) { liveFirebaseUser.postValue(firebaseAuth!!.currentUser) errorStatus.postValue(false) } else { Timber.i("Registration Failure: $task.exception!!.message") errorStatus.postValue(true) } }) } fun logOut() { firebaseAuth!!.signOut() Timber.i( "firebaseAuth Signed out") googleSignInClient.value!!.signOut() Timber.i( "googleSignInClient Signed out") loggedOut.postValue(true) errorStatus.postValue(false) } private fun configureGoogleSignIn() { val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(application!!.getString(R.string.default_web_client_id)) .requestEmail() .build() googleSignInClient.value = GoogleSignIn.getClient(application!!.applicationContext,gso) } fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) { Timber.i( "DonationX firebaseAuthWithGoogle:" + acct.id!!) val credential = GoogleAuthProvider.getCredential(acct.idToken, null) firebaseAuth!!.signInWithCredential(credential) .addOnCompleteListener(application!!.mainExecutor) { task -> if (task.isSuccessful) { // Sign in success, update with the signed-in user's information Timber.i( "signInWithCredential:success") liveFirebaseUser.postValue(firebaseAuth!!.currentUser) } else { // If sign in fails, display a message to the user. Timber.i( "signInWithCredential:failure $task.exception") errorStatus.postValue(true) } } } }
My Home activity
package com.wit.mad2bikeshop.ui.home import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.drawerlayout.widget.DrawerLayout import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.* import com.google.firebase.auth.FirebaseUser import com.squareup.picasso.Picasso import com.wit.mad2bikeshop.R import com.wit.mad2bikeshop.databinding.HomeBinding import com.wit.mad2bikeshop.databinding.NavHeaderBinding import com.wit.mad2bikeshop.firebase.FirebaseImageManager import com.wit.mad2bikeshop.ui.auth.LoggedInViewModel import com.wit.mad2bikeshop.ui.auth.Login import com.wit.mad2bikeshop.utils.customTransformation import timber.log.Timber class Home : AppCompatActivity() { private lateinit var drawerLayout: DrawerLayout private lateinit var homeBinding: HomeBinding private lateinit var navHeaderBinding: NavHeaderBinding private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var loggedInViewModel: LoggedInViewModel private lateinit var headerView : View override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) homeBinding = HomeBinding.inflate(layoutInflater) setContentView(homeBinding.root) drawerLayout = homeBinding.drawerLayout val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment val navController = navHostFragment.navController // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration( setOf( R.id.bookFragment, R.id.bookingListFragment ), drawerLayout ) setupActionBarWithNavController(navController, appBarConfiguration) val navView = homeBinding.navView navView.setupWithNavController(navController) initNavHeader() } public override fun onStart() { super.onStart() loggedInViewModel = ViewModelProvider(this).get(LoggedInViewModel::class.java) loggedInViewModel.liveFirebaseUser.observe(this, Observer { firebaseUser -> if (firebaseUser != null) updateNavHeader(firebaseUser) }) loggedInViewModel.loggedOut.observe(this, Observer { loggedout -> if (loggedout) { startActivity(Intent(this, Login::class.java)) } }) } private fun initNavHeader() { Timber.i("DX Init Nav Header") headerView = homeBinding.navView.getHeaderView(0) navHeaderBinding = NavHeaderBinding.bind(headerView) } private fun updateNavHeader(currentUser: FirebaseUser) { FirebaseImageManager.imageUri.observe(this, { result -> if(result == Uri.EMPTY) { Timber.i("DX NO Existing imageUri") if (currentUser.photoUrl != null) { //if you're a google user FirebaseImageManager.updateUserImage( currentUser.uid, currentUser.photoUrl, navHeaderBinding.navHeaderImage, false) } else { Timber.i("DX Loading Existing Default imageUri") FirebaseImageManager.updateDefaultImage( currentUser.uid, R.drawable.ic_book_nav_header, navHeaderBinding.navHeaderImage) } } else // load existing image from firebase { Timber.i("DX Loading Existing imageUri") FirebaseImageManager.updateUserImage( currentUser.uid, FirebaseImageManager.imageUri.value, navHeaderBinding.navHeaderImage, false) } }) navHeaderBinding.navHeaderEmail.text = currentUser.email if(currentUser.displayName != null) navHeaderBinding.navHeaderName.text = currentUser.displayName } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } fun signOut(item: MenuItem) { loggedInViewModel.logOut() //Launch Login activity and clear the back stack to stop navigating back to the Home activity val intent = Intent(this, Login::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } }
My BookViewModel
package com.wit.mad2bikeshop.ui.book import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.google.firebase.auth.FirebaseUser import com.wit.mad2bikeshop.firebase.FirebaseDBManager import com.wit.mad2bikeshop.firebase.FirebaseImageManager import com.wit.mad2bikeshop.model.BookManager import com.wit.mad2bikeshop.model.BookModel class BookViewModel : ViewModel() { private val status = MutableLiveData<Boolean>() val observableStatus: LiveData<Boolean> get() = status fun addBook(firebaseUser: MutableLiveData<FirebaseUser>, booking: BookModel) { status.value = try { booking.profilepic = FirebaseImageManager.imageUri.value.toString() FirebaseDBManager.create(firebaseUser,booking) true } catch (e: IllegalArgumentException) { false } } // fun updateBook(booking: BookModel){ // status.value = try { // BookManager.update(booking) // true // } catch (e: IllegalArgumentException) { // false // } // } }
My BookAdapter
package com.wit.mad2bikeshop.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.net.toUri import androidx.recyclerview.widget.RecyclerView import com.squareup.picasso.MemoryPolicy import com.squareup.picasso.Picasso import com.wit.mad2bikeshop.R import com.wit.mad2bikeshop.databinding.CardBookBinding import com.wit.mad2bikeshop.model.BookModel import com.wit.mad2bikeshop.utils.customTransformation interface BookListener { // fun onDeleteBooking(booking: BookModel) // fun onUpdateBooking(booking: BookModel) fun onBookingClick(booking: BookModel) } class BookAdapter constructor( private var bookings: ArrayList<BookModel>, private val listener: BookListener, private val readOnly: Boolean) : RecyclerView.Adapter<BookAdapter.MainHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainHolder { val binding = CardBookBinding .inflate(LayoutInflater.from(parent.context), parent, false) return MainHolder(binding, readOnly) } override fun onBindViewHolder(holder: MainHolder, position: Int) { val booking = bookings[holder.adapterPosition] holder.bind(booking, listener) } fun removeAt(position: Int) { bookings.removeAt(position) notifyItemRemoved(position) } override fun getItemCount(): Int = bookings.size inner class MainHolder(val binding: CardBookBinding,private val readOnly : Boolean) : RecyclerView.ViewHolder(binding.root) { val readOnlyRow = readOnly fun bind(booking: BookModel, listener: BookListener) { binding.root.tag = booking binding.booking = booking binding.imageIcon.setImageResource(R.mipmap.ic_launcher_round) Picasso.get().load(booking.profilepic.toUri()) .resize(200, 200) .transform(customTransformation()) .centerCrop() .into(binding.imageIcon) // // binding.name.text = booking.name // binding.phoneNumber.text = booking.phoneNumber // binding.date.text = booking.date binding.root.setOnClickListener { listener.onBookingClick(booking) } // binding.buttonDelete.setOnClickListener { listener.onDeleteBooking(booking) } // binding.buttonUpdate.setOnClickListener { listener.onUpdateBooking(booking) } binding.executePendingBindings() /* binding.imageIcon.setImageResource(R.mipmap.ic_launcher_round)*/ } } }
I believe the problem stems from the (FirebaseImageManager.imageUri.value.toString()) on my BookAdapter, as if I run a Timber.I statement it doesn't return anything at all. If I run Timber.i(FirebaseImageManager.imageUri.value.toString()+ "test"), it only returns test.
Here is a link to the full project https://github.com/foxxxxxxx7/MAD2bikeshop
Apologies if I wasn't clear enough, I am a novice.
-
Data not coming to Firebase
When submitting to Firebase, only photos are sent, without text and database as such. I do according to the guide, but I don’t understand what is the reason.
The guide probably uses the deprecated
getDownloadUrl()
method, but the photo does not suffer from this. I do not understand the reason for this, since I am still new in this area, please help, I no longer understand what to do. To understand something, look at Maineenter image description herepublic class MainActivity extends AppCompatActivity { private static final int PICK_IMAGE_REQUEST = 1; private Button mButtonChooseImage; private Button mButtonUpload; private TextView mTextViewShowUploads; private EditText mEditTextFileName; private ImageView mImageView; private ProgressBar mProgressBar; private Uri mImageUri; private StorageReference mStorageRef; private DatabaseReference mDatabaseRef; private StorageTask mUploadTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButtonChooseImage = findViewById(R.id.button_choose_im); mButtonUpload = findViewById(R.id.button_upload); mTextViewShowUploads = findViewById(R.id.text_view_show); mEditTextFileName = findViewById(R.id.edit_text_file_name); mImageView = findViewById(R.id.image_view); mProgressBar = findViewById(R.id.progress_bar); mStorageRef = FirebaseStorage.getInstance().getReference("uploads"); mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads"); mButtonChooseImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openFileChooser(); } }); mButtonUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mUploadTask != null && mUploadTask.isInProgress()) { Toast.makeText(MainActivity.this, "Upload in progress", Toast.LENGTH_SHORT).show(); } else { uploadFile(); } } }); mTextViewShowUploads.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } private void openFileChooser() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, PICK_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { mImageUri = data.getData(); Picasso.get().load(mImageUri).into(mImageView); } } private String getFileExtension(Uri uri) { ContentResolver cR = getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); return mime.getExtensionFromMimeType(cR.getType(uri)); } private void uploadFile() { if (mImageUri != null) { StorageReference fileReference = mStorageRef.child(System.currentTimeMillis() + "." + getFileExtension(mImageUri)); mUploadTask = fileReference.putFile(mImageUri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mProgressBar.setProgress(0); } }, 500); Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_LONG).show(); Upload upload = new Upload(mEditTextFileName.getText().toString().trim(), taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()); String uploadId = mDatabaseRef.push().getKey(); mDatabaseRef.child(uploadId).setValue(upload); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount()); mProgressBar.setProgress((int) progress); } }); } else { Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show(); } } }
Класс Upload
public class Upload { private String mName; private String mImageUrl; public Upload(){ } public Upload(String name, String imageUrl) { this.mName = name; this.mImageUrl = imageUrl; } public String getName() { return mName; } public void setName(String name) { this.mName = mName; } public String getImageUrl() { return mImageUrl; } public void setImageUrl(String imageUrl) { this.mImageUrl = mImageUrl; } }
activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity"> <Button android:id="@+id/button_choose_im" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Choose" /> <EditText android:id="@+id/edit_text_file_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_toEndOf="@+id/button_choose_im" android:hint="Enter" android:minHeight="48dp" /> <ImageView android:id="@+id/image_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/progress_bar" android:layout_below="@id/edit_text_file_name" android:layout_marginTop="16dp" /> <ProgressBar android:id="@+id/progress_bar" style="@style/Widget.AppCompat.ProgressBar.Horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@id/button_upload" android:layout_alignParentStart="true" android:layout_marginBottom="16dp" /> <Button android:id="@+id/button_upload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="16dp" android:text="Upload" /> <TextView android:id="@+id/text_view_show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/button_upload" android:layout_alignBottom="@+id/button_upload" android:layout_marginStart="25dp" android:layout_toEndOf="@+id/button_upload" android:gravity="center" android:text="Show" android:textSize="16sp" /> </RelativeLayout>
-
Firebase database emulator not starting (other emulators are working)
I'm trying to get the database emulator working.
Running
firebase emulators:start --only auth,hosting
works fine an give the following output:i emulators: Starting emulators: auth, hosting i hosting: Serving hosting files from: dist/spa ✔ hosting: Local server: http://localhost:5000 i ui: Emulator UI logging to ui-debug.log ┌─────────────────────────────────────────────────────────────┐ │ ✔ All emulators ready! It is now safe to connect your app. │ │ i View Emulator UI at http://localhost:4000 │ └─────────────────────────────────────────────────────────────┘ ┌────────────────┬────────────────┬────────────────────────────┐ │ Emulator │ Host:Port │ View in Emulator UI │ ├────────────────┼────────────────┼────────────────────────────┤ │ Authentication │ localhost:9099 │ http://localhost:4000/auth │ ├────────────────┼────────────────┼────────────────────────────┤ │ Hosting │ localhost:5000 │ n/a │ └────────────────┴────────────────┴────────────────────────────┘ Emulator Hub running at localhost:4400 Other reserved ports: 4500
However, as soon as I include emulation of the database the only thing I get is:
i emulators: Starting emulators: auth, database, hosting i database: Database Emulator logging to database-debug.log i emulators: Shutting down emulators. i database: Stopping Database Emulator i hub: Stopping emulator hub Error: TIMEOUT: Port 9000 on localhost was not active within 60000ms
Going to
http://localhost:9000
does give a response from the database so it seems to be running. But it hangs and does not allow the other emulators or the UI to start and will eventually time out.This is the contents of the database-debug.log
08:23:16.050 [NamespaceSystem-akka.actor.default-dispatcher-4] INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger started 08:23:16.247 [main] INFO com.firebase.server.forge.App$ - Listening at localhost:9000 08:24:14.144 [Thread-0] INFO com.firebase.server.forge.App$ - Attempting graceful shutdown. 08:24:14.156 [NamespaceSystem-akka.actor.default-dispatcher-4] INFO com.firebase.core.namespace.Terminator$Terminator - 1 actors left to terminate: fake-server 08:24:14.163 [NamespaceSystem-akka.actor.default-dispatcher-5] INFO com.firebase.core.namespace.NamespaceActor - Stopping namespace actor for fake-server 08:24:14.164 [NamespaceSystem-akka.actor.default-dispatcher-5] INFO com.firebase.core.namespace.NamespaceActor - Gauges removed for fake-server 08:24:14.170 [Thread-0] INFO com.firebase.server.forge.App$ - Graceful shutdown complete.
Update
I have:
- created a new project using firebase init just to try the emulator and I get the same behaviour.
- configured the database emulator to run on a different port. No avail.
- upgraded java to openjdk version 18... (initially I had a very old version of java on my mac)
-
Firebase Tools and Java 11
This question falls somewhere between Firebase Tools, MacOS and Java. Probably 75% Java, 20% Firebase Tools and 5% MacOS.
Starting with v10.5, firebase-tools started stating that 'Support for Java version <= 10 will be dropped soon in firebase-tools@11. Please upgrade to Java version 11 or above to continue using the emulators.'
I run macOS v11.6.5 on a Macbook Pro from mid-2014. When I go to Java's Downloads page, it recommends Java 'Version 8 Update 331'. Not Java 11.
Information on downloading Java 11 seems to be scarce. Oracle's page of certified configurations includes MacOS 11, but I can't find anywhere obvious where Java 11 can be readily downloaded.
A big part of the problem seems to be the terminology used. If I run
java -version
, I get:java version "1.8.0_331" Java(TM) SE Runtime Environment (build 1.8.0_331-b09) Java HotSpot(TM) 64-Bit Server VM (build 25.331-b09, mixed mode)
Okay, I have build 1.8 of the Java Runtime Environment, aka the JRE if you are a Java enthusiast. That is apparently what is triggering the warning in Firebase Tools.
There is also a Java product out there called 'Java SE 11'. The product itself is ambiguous, but the checksums all say 'SDK'. (A Software Development Kit: a thing that enables developers to develop Java programs. The name doesn't imply a Runtime Environment: a thing that enables Java to run on an operating system.) There is an article out there which claims that, if you install Java SE 11 and run
java -version
, it will spit outjava version "11.0.7"
. That will probably satisfy Firebase Tools.But Oracle's release notes say: 'In Windows and macOS, installing the JDK in previous releases optionally installed a JRE. In JDK 11, this is no longer an option.' No longer an option... as in now you implicitly get JRE 11 with SDK 11? Or as in the SDK and JRE are now fully divorced, and the JRE must be ferreted out of its hiding like a wild beast?
-
Firebase functions failing to start with Nuxt3 ERR_REQUIRE_ESM
I am trying to run my nuxt3 application on the firebase emulator on my local machine, but its, however, failing with the following error
Error: Error occurred while parsing your function triggers.
Error [ERR_REQUIRE_ESM]: require() of ES Module <my_project_dir>.output\server\node_modules\node-fetch\src\index.js from <my_project_dir>.output\server\node_modules\firebase-functions\lib\common\providers\identity.js not supported. Instead change the require of index.js in C:\Users\Christian\vscode\nuxt3-starter.output\server\node_modules\firebase-functions\lib\common\providers\identity.js to a dynamic import() which is available in all CommonJS modules.
I am using the following command to build my application
npx cross-env NITRO_PRESET=firebase npm run build
My nuxt3 build version is v3.0.0-rc.1-27510703.46ecbc5 and my firebase library versions are
"firebase-admin": "^10.1.0", "firebase-functions": "^3.20.0", "firebase-functions-test": "^0.3.3"