Take Picture and Upload to Firebase Kotlin
Read Time: 8 mins Languages:
Firebase is a mobile and spider web application development platform, and Firebase Storage provides secure file uploads and downloads for Firebase apps. In this post, you'll build an Android application with the power to upload images to Firebase Storage.
        
Firebase Setup
If you don't have a Firebase account even so, y'all can create 1 at the Firebase dwelling page.
In one case your account is set up, go to your Firebase console, and click the Add Project button to add a new project.
 
           
           
        Enter your projection details and click theCreate Project button when done. On the next folio, click on the link to Add Firebase to your Android app.
 
           
           
        Enter your application bundle proper 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 visitor. An easy way to discover this is to open your          MainActivity file and re-create the package proper noun from the top.
 
           
           
        When done, click on Register App. On the side by side page, you will be given a google-services.json to download to your figurer. Copy and paste that file into the app folder of your application. (The path should be something like TutsplusUpload/app.)
Gear up Firebase Permissions
To permit your app access to Firebase Storage, you demand to gear up permissions in the Firebase console. From your console, click on Storage, and and so click on Rules.
 
           
           
        Paste the rule below and publish.
        
service firebase.storage {   match /b/{saucepan}/o {     match /{allPaths=**} {       permit read, write: if truthful;     }   } }        This will allow read and write access to your Firebase storage.
Create the Application
Open up Android Studio, and create a new project. You lot can telephone call your project anything y'all desire. I called mine TutsplusUpload.
Before y'all continue, you'll need to add a couple of dependencies. On the left console of your Android Studio, click on Gradle Scripts.
 
           
           
        Open build. gradle (Projection: TutsplusUpload), and add this line of code in the dependencies block.
classpath 'com.google.gms:google-services:3.0.0'
Next, open build. gradle (Module: app) to add the dependencies for Firebase. These go in the dependencies cake also.
compile 'com.google.firebase:firebase-storage:nine.two.1' compile 'com.google.firebase:firebase-auth:9.ii.1'
Finally, outside the dependencies block, add together the plugin for Google Services.
use plugin: 'com.google.gms.google-services'
Relieve when washed, and it should sync.
Prepare theMainActivity          Layout
        The application volition demand one activity layout. Two buttons will be needed—one to select an prototype from your device, and the other to upload the selected image. After selecting the image yous want to upload, the image will be displayed in the layout. In other words, the image volition not exist set from the layout just from the activity.
In your          MainActivity          layout, yous will utilize two layouts—nesting the linear layout inside the relative layout. Start by calculation the code for your relative layout.
<?xml version="1.0" encoding="utf-viii"?> <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 space provided past the device. The          LinearLayout          will live inside the          RelativeLayout, and will take the 2 buttons. The buttons should be placed side past side, thus the orientation to be used for the          LinearLayout          will be horizontal.
Here is the code for the linear layout.
<LinearLayout android:id="@+id/layout_button" android:orientation="horizontal" android:layout_alignParentTop="true" android:weightSum="2" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/btnChoose" android:text="Cull" android:layout_weight="ane" android:layout_width="0dp" android:layout_height="wrap_content" /> <Button 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, yous can see that both buttons have ids assigned. The ids volition be used to target the push button from the chief activity such that when the button gets clicked, an interaction is initiated. You will run into that soon.
Below the          LinearLayout, add together the lawmaking for the          ImageView.
<ImageView android:id="@+id/imgView" android:layout_width="match_parent" android:layout_height="match_parent" />
Y'all tin also see that the          ImageView          has an          id; you lot will apply this to populate the layout of the selected image. This volition be done in the principal action.
GetMainActivity          Upward        
        Navigate to your          MainActivity, and start by declaring fields. These fields volition be used to initialize your views (the buttons and          ImageView), besides as the URI indicating where the prototype will be picked from. Add this to your main activity, above the          onCreate          method.
private Button btnChoose, btnUpload; individual ImageView imageView; private Uri filePath; private last int PICK_IMAGE_REQUEST = 71;
          PICK_IMAGE_REQUEST          is the request code divers as an instance variable.
Now you can initialize your views similar so:
//Initialize Views btnChoose = (Button) findViewById(R.id.btnChoose); btnUpload = (Button) findViewById(R.id.btnUpload); imageView = (ImageView) findViewById(R.id.imgView);
In the above code, you lot are creating new instances of          Button          and          ImageView. The instances betoken to the buttons you lot created in your layout.
You have to set a listener that listens for interactions on the buttons. When an interaction happens, you lot want to telephone 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, prepare the listener for both buttons. The listener looks like this.
          btnChoose.setOnClickListener(new View.OnClickListener() {       @Override       public void onClick(View five) {         chooseImage();       }     });      btnUpload.setOnClickListener(new View.OnClickListener() {       @Override       public void onClick(View 5) {         uploadImage();       }     });        This should be in the          onCreate()          method. As I mentioned in a higher place, both buttons phone call a unlike method. The          Cull          button calls the          chooseImage()          method, while the          Upload          button calls the          uploadImage()          method. Allow'southward add those methods. Both methods should be implemented outside the          onCreate()          method.
Let's outset with the method to choose an image. Here is how it should look:
          individual void chooseImage() {     Intent intent = new Intent();     intent.setType("paradigm/*");     intent.setAction(Intent.ACTION_GET_CONTENT);     startActivityForResult(Intent.createChooser(intent, "Select Flick"), PICK_IMAGE_REQUEST);   }        When this method is called, a new          Intent          instance is created. The intent type is set to epitome, and its action is gear up to get some content. The intent creates an epitome chooser dialog that allows the user to browse through the device gallery to select the prototype.          startActivityForResult          is used to receive the upshot, which is the selected epitome. To display this paradigm, you'll make use of a method chosen          onActivityResult.
          onActivityResult          receives a request code, result code, and the data. In this method, you will check to see if the request code equals          PICK_IMAGE_REQUEST, with the upshot lawmaking equal toRESULT_OK          and the data available. If all this is true, you want to brandish the selected prototype in the          ImageView.
Below the          chooseImage() method, add the following code.
          @Override   protected void onActivityResult(int requestCode, int resultCode, Intent data) {     super.onActivityResult(requestCode, resultCode, data);     if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK             && data != nada && 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 nosotros tin implement the method for uploading the image to Firebase. First, declare the fields needed for Firebase. Do this below the other fields you declared for your class.
//Firebase FirebaseStorage storage; StorageReference storageReference;
          storage          will be used to create a          FirebaseStorage          instance, while          storageReference          will point to the uploaded file. Inside your          onCreate()          method, add the code to exercise that—create a          FirebaseStorage          instance and go the storage reference. References can be seen as pointers to a file in the cloud.
storage = FirebaseStorage.getInstance(); storageReference = storage.getReference();
Here is what the          uploadImage()          method should look like.
          private void uploadImage() {      if(filePath != zero)     {       concluding ProgressDialog progressDialog = new ProgressDialog(this);       progressDialog.setTitle("Uploading...");       progressDialog.prove();        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).show();                 }               })               .addOnFailureListener(new OnFailureListener() {                 @Override                 public void onFailure(@NonNull Exception e) {                   progressDialog.dismiss();                   Toast.makeText(MainActivity.this, "Failed "+east.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 called, a new instance of          ProgressDialog          is initialized. A text find 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          binder. This binder gets created automatically when the image is uploaded. Listeners are also added, with toast messages. These messages go displayed depending on the state of the upload.
Set Permission in the App
Finally, you demand to request permission that your awarding volition make use of. Without this, users of your application will non be able to browse their device gallery and connect to the internet with your application. Doing this is easy—just paste the following in yourAndroidManifest file. Paste it only above theapplication 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 internet and read external storage.
Testing the App
Now go ahead and run your application! You should be able to select an epitome and successfully upload it to Firebase. To confirm the image uploaded, get back to your panel and check in the Files part of your storage.
 
           
           
        Conclusion
        
        Firebase provides developers with lots of benefits, and file upload with storage is one of them. Uploading images from your Android application requires you to piece of work with Activities and Intents. Past following forth with this tutorial, your understanding of Activities and Intents has deepened. I hope you enjoyed information technology!
Check out some of our other posts for more than groundwork about Activities and Intents, or take a look at some of our other tutorials on using Firebase with Android!
Did y'all notice this mail useful?
Source: https://code.tutsplus.com/tutorials/image-upload-to-firebase-in-android-application--cms-29934
 
          
0 Response to "Take Picture and Upload to Firebase Kotlin"
Post a Comment