How To Upload Image To Firebase From Java
Read Time: eight mins Languages:
Firebase is a mobile and web application development platform, and Firebase Storage provides secure file uploads and downloads for Firebase apps. In this mail service, you'll build an Android application with the ability to upload images to Firebase Storage.
Firebase Setup
If yous don't have a Firebase business relationship yet, you can create one at the Firebase habitation page.
Once your account is set up, become to your Firebase console, and click the Add Project button to add a new projection.
Enter your projection details and click theCreate Project push when done. On the adjacent page, click on the link to Add together Firebase to your Android app.
Enter your application package name. My application package iscom.tutsplus.code.android.tutsplusupload. Note that the package name is namespaced with a unique string that identifies you or your company. An like shooting fish in a barrel way to find this is to open your MainActivity
file and re-create the package name from the top.
When done, click on Annals App. On the side by side page, you lot will exist given a google-services.json to download to your computer. Copy and paste that file into the app folder of your application. (The path should be something similar TutsplusUpload/app.)
Set Firebase Permissions
To permit your app access to Firebase Storage, you need to set upwards permissions in the Firebase panel. From your console, click on Storage, and then click on Rules.
Paste the rule below and publish.
service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { permit read, write: if true; } } }
This will allow read and write access to your Firebase storage.
Create the Application
Open upwardly Android Studio, and create a new project. You lot can phone call your project anything you want. I called mine TutsplusUpload.
Before you lot go along, y'all'll need to add together a couple of dependencies. On the left console of your Android Studio, click on Gradle Scripts.
Open build. gradle (Project: TutsplusUpload), and add this line of code in the dependencies block.
classpath 'com.google.gms:google-services:iii.0.0'
Adjacent, open build. gradle (Module: app) to add the dependencies for Firebase. These go in the dependencies block likewise.
compile 'com.google.firebase:firebase-storage:9.2.1' compile 'com.google.firebase:firebase-auth:9.ii.i'
Finally, exterior the dependencies block, add the plugin for Google Services.
apply plugin: 'com.google.gms.google-services'
Save when done, and it should sync.
Set Up theMainActivity
Layout
The awarding volition need one activity layout. Two buttons will be needed—ane to select an image from your device, and the other to upload the selected epitome. After selecting the image you want to upload, the epitome will exist displayed in the layout. In other words, the paradigm will not be prepare from the layout but from the action.
In your MainActivity
layout, you will use two layouts—nesting the linear layout within the relative layout. Beginning by adding the code for your relative layout.
<?xml version="1.0" encoding="utf-eight"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context="com.tutsplus.code.android.tutsplusupload.MainActivity"> </RelativeLayout>
The RelativeLayout
takes up the whole infinite provided by the device. The LinearLayout
will alive inside the RelativeLayout
, and will have the two buttons. The buttons should be placed next, thus the orientation to be used for the LinearLayout
volition exist horizontal.
Here is the code for the linear layout.
<LinearLayout android:id="@+id/layout_button" android:orientation="horizontal" android:layout_alignParentTop="true" android:weightSum="two" android:layout_width="match_parent" android:layout_height="wrap_content"> <Push button android:id="@+id/btnChoose" android:text="Choose" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <Push android:id="@+id/btnUpload" android:text="Upload" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> </LinearLayout>
From the above lawmaking, you can encounter that both buttons have ids assigned. The ids volition exist used to target the button from the principal activity such that when the button gets clicked, an interaction is initiated. You will encounter that shortly.
Below the LinearLayout
, add the code for the ImageView
.
<ImageView android:id="@+id/imgView" android:layout_width="match_parent" android:layout_height="match_parent" />
You can also meet that the ImageView
has an id
; y'all volition use this to populate the layout of the selected paradigm. This will be washed in the main activity.
GetMainActivity
Up
Navigate to your MainActivity
, and start by declaring fields. These fields will be used to initialize your views (the buttons and ImageView
), too as the URI indicating where the image will be picked from. Add this to your main activity, above the onCreate
method.
private Button btnChoose, btnUpload; individual ImageView imageView; private Uri filePath; individual final int PICK_IMAGE_REQUEST = 71;
PICK_IMAGE_REQUEST
is the asking lawmaking divers as an instance variable.
Now y'all can initialize your views like so:
//Initialize Views btnChoose = (Button) findViewById(R.id.btnChoose); btnUpload = (Button) findViewById(R.id.btnUpload); imageView = (ImageView) findViewById(R.id.imgView);
In the in a higher place lawmaking, you are creating new instances of Button
and ImageView
. The instances point to the buttons yous created in your layout.
Y'all accept to set a listener that listens for interactions on the buttons. When an interaction happens, you want to call a method that triggers either the selection of an image from the gallery or the uploading of the selected image to Firebase.
Underneath the initialized views, set the listener for both buttons. The listener looks like this.
btnChoose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { chooseImage(); } }); btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View five) { uploadImage(); } });
This should be in the onCreate()
method. Equally I mentioned above, both buttons telephone call a unlike method. The Choose push button calls the chooseImage()
method, while the Upload push button calls the uploadImage()
method. Allow'due south add together those methods. Both methods should be implemented outside the onCreate()
method.
Let's start with the method to cull an paradigm. Here is how it should expect:
individual void chooseImage() { Intent intent = new Intent(); intent.setType("paradigm/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Moving-picture show"), PICK_IMAGE_REQUEST); }
When this method is called, a new Intent
instance is created. The intent type is fix to prototype, and its action is gear up to get some content. The intent creates an image chooser dialog that allows the user to browse through the device gallery to select the image. startActivityForResult
is used to receive the result, which is the selected image. To brandish this prototype, y'all'll make use of a method called onActivityResult
.
onActivityResult
receives a request lawmaking, result code, and the data. In this method, you will check to see if the request code equals PICK_IMAGE_REQUEST
, with the consequence code equal toRESULT_OK
and the data available. If all this is truthful, you lot desire to display the selected image in the ImageView
.
Below the chooseImage()
method, add together the post-obit code.
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, information); if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null ) { filePath = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); imageView.setImageBitmap(bitmap); } catch (IOException e) { east.printStackTrace(); } } }
Uploading the File to Firebase
Now we can implement the method for uploading the image to Firebase. Kickoff, declare the fields needed for Firebase. Do this below the other fields you declared for your form.
//Firebase FirebaseStorage storage; StorageReference storageReference;
storage
will exist used to create a FirebaseStorage
example, while storageReference
will point to the uploaded file. Inside your onCreate()
method, add the code to practice that—create a FirebaseStorage
example and get the storage reference. References can exist seen as pointers to a file in the deject.
storage = FirebaseStorage.getInstance(); storageReference = storage.getReference();
Here is what the uploadImage()
method should look like.
individual void uploadImage() { if(filePath != null) { concluding ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setTitle("Uploading..."); progressDialog.show(); StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString()); ref.putFile(filePath) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { progressDialog.dismiss(); Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).bear witness(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception east) { progressDialog.dismiss(); Toast.makeText(MainActivity.this, "Failed "+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()); progressDialog.setMessage("Uploaded "+(int)progress+"%"); } }); } }
When the uploadImage()
method is chosen, a new instance of ProgressDialog
is initialized. A text notice showing the user that the paradigm is being uploaded gets displayed. Then a reference to the uploaded image, storageReference.child()
, is used to access the uploaded file in the images folder. This folder gets created automatically when the paradigm is uploaded. Listeners are also added, with toast letters. These messages get displayed depending on the state of the upload.
Ready Permission in the App
Finally, you lot need to request permission that your awarding will brand use of. Without this, users of your application will non be able to browse their device gallery and connect to the net with your awarding. Doing this is piece of cake—simply paste the following in yourAndroidManifest file. Paste information technology just above theawarding
element tag.
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
This requests for permission to use the cyberspace and read external storage.
Testing the App
Now get ahead and run your application! You should exist able to select an prototype and successfully upload it to Firebase. To confirm the image uploaded, get dorsum to your console and check in the Files part of your storage.
Determination
Firebase provides developers with lots of benefits, and file upload with storage is i of them. Uploading images from your Android application requires you to work with Activities and Intents. By following along with this tutorial, your agreement of Activities and Intents has deepened. I promise yous enjoyed it!
Check out some of our other posts for more than background nigh Activities and Intents, or take a expect at some of our other tutorials on using Firebase with Android!
Did you discover this post useful?
Source: https://code.tutsplus.com/tutorials/image-upload-to-firebase-in-android-application--cms-29934
Posted by: neighborsbabsizarly.blogspot.com
0 Response to "How To Upload Image To Firebase From Java"
Post a Comment