Firebase : Video storage - android

Does Google's Firebase support video storage ? Am planning to upload video and want to download on-demand. I started with Firebase. Are there any other APIs or services that give a similar functionality ?

Of course you can upload video or any files on firebase.
btnupload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_GET_CONTENT);
myIntent.setType("*/*");
startActivityForResult(Intent.createChooser(myIntent,"Select File:-"),101);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode==RESULT_CANCELED)
{
// action cancelled
}
if(resultCode==RESULT_OK)
{
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://<<Your App Bucket Address>>");
Uri uri = data.getData();
StorageReference riversRef = storageRef.child("files/"+uri.getLastPathSegment());
UploadTask uploadTask = riversRef.putFile(uri);
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Toast.makeText(MainActivity.this, "Upload Success", Toast.LENGTH_SHORT).show();
}
});
}
}

Firebase has a Firebase Storage offering that allows you to store any arbitrary files.
It doesn't offer any video-specific features or functionality, but it will work if you simply want to have a place to store and retrieve your video files.

Related

Unable to save image to Firebase

In my android app i am using Firebase Storage to save images i have set security rules to null then too i am not able to upload images and getting error.
Below are my error ,security rules and android code.Please let me know what i did wrong in code.
Logcat error : StorageException has occurred.
User does not have permission to access this object.
Code: -13021 HttpResult: 403
Security rules:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth == null;
}
}
}
Java code:
galleryFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(SetAvatar.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
}
else{
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i,GALLERY_INTENT);
}
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
uri = data.getData();
cv.setImageURI(uri);
final StorageReference filepath = sRef.child("Profile
Images").child(uri.getLastPathSegment());
UploadTask uploadTask = filepath.putFile(uri);
uploadTask.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(SetAvatar.this, "Upload
successful",Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SetAvatar.this, "Upload Failed -> " + e,
Toast.LENGTH_SHORT).show();
}
});
}
}
Thanks
change your security rules to:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
But this will make your Bucket to be modified by anyone and I don't recommend it. However, you may use it for testing purposes.

Upload profile image for a user Firebase

I am trying to add an image to the user information in the real time database(firebase) for android. I have uploaded the image on the firebase storage but how will I be able to add the image in the database for that user?
Code Below:
//inside onCreate() method
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i,request_code);
}
});
Here I am clicking on the imageview, so I will be able to change it and get an image from the gallery.
Here I authenticate the user and send data to the database:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(StudentSignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(getApplicationContext(), "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(StudentSignUpActivity.this, HomeActivity.class));
finish();
}
}
});
mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference newStudent=mDatabase.push();
newStudent.child("email").setValue(email);
newStudent.child("password").setValue(password);
newStudent.child("name").setValue(name);
newStudent.child("date").setValue(dates);
newStudent.child("phone").setValue(number);
newStudent.child("uid").setValue(mCurrentUser.getUid());
//outside of onCreate()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request_code&&resultCode==RESULT_OK){
Uri uri=data.getData();
StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
}
In the above code I have uploaded the image to the firebase storage. Now how will i be able to add that image as a child for a specific user.
I think I need to do something like this:
newStudent.child("image").setValue(uri_here);
But I am unable to figure how to get the uri of the image and how to add that uri in the setValue() since its in another method.
You can use the method getDownloadUrl() in the success listener to access the download URL:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request_code&&resultCode==RESULT_OK){
Uri uri=data.getData();
StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
newStudent.child("image").setValue(downloadUrl);
}
});
}
}
As an aside, instead of using push(), I recommend storing the user's data with the uid as the key. This will make your data easier to find.
private DatabaseReference newStudent;
mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
newStudent=mDatabase.child(mCurrentUser.getUid());
newStudent.child("email").setValue(email);
// etc
Just to update because I spent sometime to find this answer, getDownloadUrl() is NOT a function of taskSnapshot anymore. So in order to get the image URL from Firebase Storage you need to add a listener to
taskSnapshot.getMetadata().getReference().getDownloadUrl()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request_code&&resultCode==RESULT_OK){
Uri uri=data.getData();
StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getMetadata().getReference().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
newStudent.child("image").setValue(uri);
}
});
}
});
}
}
Now it's safe to use uri to whatever you want

Show seekbar when video is uploaded to firebase in android

floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
// progressBar.setVisibility(View.VISIBLE);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
Video video = new Video(downloadUrl.toString());
mMessagesDatabaseReference.push().setValue(video);
}
});
}
}
I want to show progress on seekbar when image is uploading as a notification. How do I do that? I have created an object of Seekbar in my onCreate. How to get duration of the video which I am uploading and show the seekbar in notification and the user should not be able to swipe notification when upload starts? Please help.
you can do that by using addOnProgressListener
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int progress = (int) ((100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
try {
yourSeekBar.setProgress(progress);
} catch (Exception e) {
e.printStackTrace();
}
}
})

I am trying to upload an image to firebase using android studio but its not working, what is wrong with my code?

I have not use authentication yet, in the screen i can see the progress dialog working but its not getting stop. I think there is a problem.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==GALLERY_INTENT&&resultCode==RESULT_OK){
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = mStorageRef;
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Uploading Finished",Toast.LENGTH_LONG).show();
}
});
}
}
//firebase storage rule
service firebase.storage {
match /b/csapplication-b6e5e.appspot.com/o {
match /{allPaths=**} {
allow read, write: if request.auth == null;
}
}
}
Its because of if your file upload to firebase was successful means your ProgressDialog will be dismissed ,if not in the case of failure you have to dismiss (ProgressDialog) in the OnFailure method in the code below .
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Uploading Finished",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads - Dismiss the ProgressDialog here
progressDialog.dismiss();
Toast.makeText(Profile.this, "Unable to Uploaded Error in Firebase",Toast.LENGTH_LONG).show();
}});

Unable to Show Image In ImageView From Firebase Storage

I have an app which allows the users to upload the images to a Firebase bucket,then I get the download URL of the image file and add it to a firebase database.The URL is in the form :- https://firebasestorage.googleapis.com/v0/b/bucket_name.appspot.com/o/filename?alt=media&token=token
Then I try to load the images into an RecyclerView using Glide but I am unable to do so and It fails to display the image.
How can I get an absolute Image URL which ends in .png or .jpeg etc which can be easily used to load the image.As far as I know the problem is with the url
To get Images form Camera
Intent i = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 3);
To get the filepath of an Image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FILE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
String path=String.valueOf(data.getData());
file = Uri.fromFile(new File(path));
Create the file metadata
metadata = new StorageMetadata.Builder()
.setContentType("image/jpeg")
.build();
Upload file and metadata to the path 'images/avator.jpg'
uploadTask = storageRef.child("images/"+file.getLastPathSegment()).putFile(file, metadata);
Listen for state changes, errors, and completion of the upload.
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
System.out.println("Upload is " + progress + "% done");
}
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
#Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("Upload is paused");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Handle successful uploads on complete
Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
}
});
To load the Image using Glide Library
Glide.with(getActivity())
.load(new File(downloadUrl)) // Uri of the picture
.into(Imageview);
With Picasso you can load a simple image using:
Picasso.with(Activity.this).load("your url image").into(imageView);
Need add in Glade:
compile 'com.squareup.picasso:picasso:2.5.2'

Categories

Resources