In Android, Firebase is actually a cloud that provides the backend. Some of those are might know about the backend and some of are not. A backend is basically a database storage to store files and data on the server by using application programming interface.
So Here Firebase is a cloud database storage that stores your data and files. To Storing those data or files it provides the API for pushing and pulling these data.
Today in this tutorial we will learn how to upload the file into our firebase storage? Ok Now, let’s see what is Firebase Storage? Firebase Storage is built for app developers who need to store and serve user-generated content, such as photos or videos.
Firebase Storage is a stand-alone solution for uploading user-generated content like images and videos from an iOS and Android device, as well as the Web.
To using the Firebase you need to follow few step of configuration. These are very simple steps.
- Please go to Firebase console to create the project. Here you can pass the project name and enter your country name etc.
- You have to choose which platform do you want to use. Here we are configuring for Android platform, so I am choosing an option for Android app.
- Now you need to enter your package name of your project. Ex: Here my package name is “com.sunil.firebasedatabasetest” . Other fields are optional for debug mode. But if you want to release your app that time you need to pass the SHA-1 key.
- Once you have done your step.4 You will get downloaded one google-services.json file. You have to copy this file and paste into the app folder.
Great done well so far. Now you need to add Firebase dependencies to your Gradle file.
compile 'com.google.firebase:firebase-database:9.8.0' compile 'com.google.firebase:firebase-storage:9.8.0' compile 'com.firebaseui:firebase-ui-database:0.6.2' compile 'com.google.firebase:firebase-auth:9.8.0'
I will select an image from sd card and upload on firebase storage and after I will show those file from firebase store to inflate on view. Here is written my tutorial about upload file on Firebase Storage.
Here you need to get the instances of Database reference, Firebase Authentication, and Firebase storage reference in your onCreateView if you are using fragment or onCreate in the case of Activity.
databaseRef = FirebaseDatabase.getInstance().getReference(); mFirebaseAuth = FirebaseAuth.getInstance(); // creating an instance of Firebase Storage FirebaseStorage firebaseStorage = FirebaseStorage.getInstance(); storageRef = firebaseStorage.getReference().child("photos");
OK, All are ready now then good to go for upload.
@OnClick(R.id.uplaod) public void uploadClick(){ if (mFile != null && mFile.exists()) { uploadFile(mFile, selectedImageUri ); }else { Toast.makeText(getActivity(), "File does not exist", Toast.LENGTH_LONG).show(); } }
private void uploadFile(File file, Uri fileUri){ showProgressDialog(); InputStream stream = null; try { stream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } if(stream != null){ // Create a reference to "file" storageRef = storageRef.child(fileUri.getLastPathSegment()); UploadTask uploadTask = storageRef.putStream(stream); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { hideProgressDialog(); Toast.makeText(getActivity(), "Uploading failed", Toast.LENGTH_LONG).show(); // Handle unsuccessful uploads } }).addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { hideProgressDialog(); // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL. Uri downloadUrl = taskSnapshot.getDownloadUrl(); Log.e("Url", "DownloadUrl: "+downloadUrl); setUserProfile(downloadUrl.toString()); uplaod.setEnabled(false); mListener.updateProfileDone(); } }); } else{ Toast.makeText(getActivity(), "Getting null file", Toast.LENGTH_LONG).show(); } }
Ok, You have uploaded a file to the Firebase storage and got the downloaded URL to load on view. Now How can get the file by using Freebase API?
DatabaseReference usernameRef = databaseRef.child(userId); Query queryRef = usernameRef.orderByKey(); queryRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String userProfileUrl = (String) dataSnapshot.child("userProfileUrl").getValue(); Log.e(TAG, "Profile Url: "+ userProfileUrl); if (userProfileUrl != null && !userProfileUrl.isEmpty()){ Glide.with(getActivity()).load(userProfileUrl).into(profileImage); } } @Override public void onCancelled(DatabaseError databaseError) { Log.e(TAG, databaseError.getMessage()); } });
Wrapping Up: As we have seen that Firebase is awesome for instant building the app. Even if you do not have any backend ready till now then you can use the Firebase cloud for a backend to quick start your idea into the Android application. You can learn some of the good articles to avoid memory leak in Android.
Please do subscribe email to get all newsletters of this blog and if you feel that this post will help you to understand then do not forget to subscribe, share and comment below.
Happy Coding 🙂
I am a very enthusiastic Android developer to build solid Android apps. I have a keen interest in developing for Android and have published apps to the Google Play Store. I always open to learning new technologies. For any help drop us a line anytime at contact@mobologicplus.com