Friday, 9 September 2016

Firebase in Android - Storage

With reference from my last blog here, now we go forward towards the next step i.e learning the concept of Storage in Firebase.
Firebase Storage lets you upload and share user generated content, such as images and video, which allows you to build rich media content into your apps. Firebase Storage stores this data in a Google Cloud Storage bucket. Firebase Storage lets you securely upload these files directly from mobile devices and web browsers, handling spotty networks with ease.

-Prerequisites:
Install the Firebase SDK.
Add your app to your Firebase project in the Firebase console.

-Add Firebase Storage to your app:
 Add the dependencies for Firebase Storage to your build.gradle file:

compile 'com.google.firebase:firebase-storage:9.4.0'
compile 'com.google.firebase:firebase-auth:9.4.0'

-Set up Firebase Storage:
The first step in accessing your storage bucket is to create an instance of FirebaseStorage:

FirebaseStorage storage = FirebaseStorage.getInstance();

-Create a Reference:
Create a reference to upload, download, or delete a file, or to get or update its metadata. A reference can be thought of as as pointer to a file in the cloud. References are lightweight, so you can create as many as you need. They are also reusable for multiple operations. You can create a reference as follows:

// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>");

gs://<your-firebase-storage-bucket> You can find this URL the Storage section of the Firebase console.
You can create a reference to a location lower in the tree, say 'images/space.jpg' by using the getChild() method on an existing reference.

// Create a child reference
// imagesRef now points to "images"
StorageReference imagesRef = storageRef.child("images");

// Child references can also take paths
// spaceRef now points to "users/me/profile.png
// imagesRef still points to "images"
StorageReference spaceRef = storageRef.child("images/space.jpg");

-Limitations on References:
Reference paths and names can contain any sequence of valid Unicode characters, but certain restrictions are imposed including:
  • Total length of reference.fullPath must be between 1 and 1024 bytes when UTF-8 encoded.
  • No Carriage Return or Line Feed characters.
  • Avoid using #, [, ], *, or ?, as these do not work well with other tools such as the Firebase Realtime Database or gsutil.
-Upload Files:
To upload a file to Firebase Storage, you first create a reference to the full path of the file, including the file name.

// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>");
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = storageRef.child("images/mountains.jpg");

-Upload from data in memory:
The putData() method is the simplest way to upload a file to Firebase Storage. putData() takes a byte[] and returns an UploadTask that you can use to manage and monitor the status of the upload.

// Get the data from an ImageView as bytes
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();

UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.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) {
        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
        Uri downloadUrl = taskSnapshot.getDownloadUrl();
    }
});

-Upload from a local file:
You can upload local files on the device, such as photos and videos from the camera, with the putFile() method. putFile() takes a File and returns an UploadTask which you can use to manage and monitor the status of the upload.

Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = riversRef.putFile(file);

// 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
    }
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        Uri downloadUrl = taskSnapshot.getDownloadUrl();
    }
});

-Download files:
Download to a local file
The getFile() method downloads a file directly to a local device. Use this if your users want to have access to the file while offline or to share the file in a different app. getFile() returns a DownloadTask which you can use to manage your download and monitor the status of the download.

// Create a storage reference from our app to the image
StorageReference islandRef = storageRef.child("images/island.jpg");

File localFile = File.createTempFile("images", "jpg");

islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
        // Local temp file has been created
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle any errors
    }
});

That's all of this tutorial. Try this and wait for the next one to proceed further.

22 comments:

  1. A mini excavator is a compact and versatile piece of construction equipment designed for small to medium-sized projects. Despite its smaller size, it is powerful and efficient, capable of digging, trenching, and demolishing tasks in tight spaces where larger machines can't operate.
    https://asianexcavators.com/

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete

  3. A Bangkok VPS is a virtual private server located in Bangkok, Thailand. This means it's a type of online computer that you can use to store files, run applications, or host websites. It's like having your own private space on a powerful computer that is shared with others. By choosing a server in Bangkok,

    ReplyDelete
  4. ​VBlink is a popular online gaming platform offering a wide range of casino games, including slots, table games, and fish games. To access these games on your Android device, you'll need to download and install the VBlink APK.

    ReplyDelete
  5. Free MilkyWay App is an exciting online gaming platform that lets players enjoy a variety of casino-style games, including slots, fish table games, and more. With a smooth interface and high-quality graphics, the app provides a thrilling gaming experience anytime, anywhere. Players can access free gameplay, enjoy special bonuses, and participate in engaging challenges without spending real money.

    ReplyDelete
  6. Education is the cornerstone of personal and societal development, providing individuals with the knowledge, skills, and values needed to succeed in life.https://chipotlemenuus.com/chipotle-catering-menu/

    ReplyDelete
  7. Education is the foundation of personal and societal growth, shaping individuals into knowledgeable, skilled, and responsible members of society. It provides people with the ability to think critically, solve problems, and adapt to an ever-changing world.https://chipotlemenuus.com/chipotle-nutrition/

    ReplyDelete
  8. Firebase Storage is such a powerful tool for managing and storing data in Android apps! It makes handling media files and user-generated content so much easier. If you're into exploring different digital experiences, you might also want to check out cash machine slot for some exciting entertainment. Looking forward to more great discussions on Firebase!

    ReplyDelete
  9. Android Castle is a great place to explore new apps and tools for Android users. If you’re looking for a reliable way to store large files without limits, check out Terabox Mod APK Unlimited Storage for free cloud storage with extra features

    ReplyDelete


  10. Android Castle, if you're looking for an action-packed open-world game, check out Gangstar Vegas Mod APK Unlimited Money and Diamonds Old Version ! Enjoy unlimited resources and experience the classic gameplay with all unlocked features. Give it a try

    ReplyDelete
  11. Firebase Storage is a great tool for managing data in Android apps. If you're interested in gaming, you might also want to check out S9 Game login for a seamless gaming experience. Definitely worth exploring.

    ReplyDelete
  12. Firebase Storage is a powerful tool for managing data in Android apps. If you’re into gaming, you might also want to check out Dude Theft Wars Iron Man Mod APK for a fun and action-packed experience. Worth exploring!

    ReplyDelete
  13. Firebase storage is such a powerful tool for Android development! By the way, if you're interested in exploring something exciting, check out cash machine online !

    ReplyDelete
  14. Education is the foundation of a brighter future, equipping individuals with the knowledge, skills, and values needed to succeed in life. It fosters critical thinking, creativity, and problem-solving abilities, preparing students for both personal and professional growth.
    https://chipotlemenuus.com/

    ReplyDelete
  15. Speaking of which, if anyone's looking for a more stable or lightweight cloud storage option, I’d recommend checking out terabox mod apk old version . It still has the premium perks without the extra bloat or updates that slow things down.

    ReplyDelete
  16. Great post about Android apps! If you're into action-packed open-world games, you should definitely check out the gangstar vegas mod apk latest version . It’s loaded with all the premium features, and the gameplay is seriously addictive. Perfect for some downtime after exploring Android's best apps!

    ReplyDelete
  17. If you’re looking for a great alternative to Android Castle, I highly recommend checking out b9game . It offers a variety of exciting games and a smooth user experience on Android. Definitely worth a try!








    ReplyDelete
  18. Great post about Android Castle! It’s always interesting to learn about new Android games and apps. If you're looking for something fun to try, you can Panda Master Download APK and enjoy a great gaming experience. Keep the awesome content coming!

    ReplyDelete
  19. Thanks for the insights on Firebase Storage in Android—really helpful stuff! I was recently working on a project where I needed to handle media uploads efficiently, and this post cleared up a lot. If you're into app development and testing real-world implementations, you might want to check out s9 game download .

    ReplyDelete
  20. Great post on Firebase Storage in Android—super useful for developers working with real-time data and media! If you're into testing apps with cool backend features, check out dude theft wars unlimited money. It's a fun way to see game mechanics in action!

    ReplyDelete
  21. Android Castle looks like a fun and creative concept—love seeing how Android-based projects are pushing boundaries! If you're into mobile gaming and based in South Asia, definitely check out b9 game download in Pakistan for a great way to level up your game time!

    ReplyDelete
  22. I love the concept of Android Castle! It’s a great game, and I think a lot of people would enjoy it. By the way, if you're interested in trying out something similar or want to check out other cool features, you can grab the panda master download ios . It works smoothly and has some awesome features too!

    ReplyDelete