Xamarin.Android - Upload An Image To Firebase Storage

Introduction
 
Today, I am going to show you how to upload an image to Firebase storage and then show that uploaded image in Firebase Storage. 
 
Prerequisites
  • Xamarin Firebase Storage
  • Registered Firebase App
  • Before you can start uploading Image to Firebase, make sure your Android app is connected to Firebase.
  • Authentication system is added to your app.
Note
 
If you don’t want to add authentication to your app now and plan to add it later, you can change the Firebase storage rules to public so that you can access Firebase storage for uploading Image. For this, go to Firebase console and select your project. Now, click on Storage and then select RULES tab. Replace the line allow read, write: if request.auth != null; with allow read, write: if true;
 
 
What is Firebase?
 
FireBase is a NoSQL Real-time Database that helps you store data of your app on the Cloud devoid of any irritation of creating and sustaining the server.
 
Connect an Android app to FireBase
 
Step 1 

If you already have an existing Android app, open it in Visual Studio or create a new Android project. Open Visual Studio and go to New Project-> Templates-> Visual C#-> Android-> Blank app. Give it a name, like XamarinFirebaseUpload.

 
 
Step 2
 
Go to firebase by using this link "https://console.firebase.google.com/u/0/", then go to the console and click on Add Project. Select Add Firebase to your Android App.
 
 
 
Enter Project name and Country as shown below and then click on Create Project.
 
 
  
Step 3

Now click on ‘Add Firebase to your Android App’ and copy the package name of your app. All other fields are optional and can be left blank for now.

 
Step 4

Now download the google-services.json file and copy it to the app folder of your Android project.

 
If everything goes well, you will see your project added in the Firebase Console.

 
Step 5
 
Go to Visual Studio -> Solution Explorer-> Project Name-> right click and select "Open Folder in File Explorer" .
 
 
Step 6
 
Edit your *.csproj file add the following code in to it and save it.
  1. <ItemGroup>  
  2.    <GoogleServicesJson Include="google-services.json" />  
  3. </ItemGroup>  
 
Visual studio will show you a notification with four options select to Reload Solution.
 
 

Step 7

Add firebase storage reference to your project, go to Solution Explorer-> Project Name-> References. Then, right-click to "Manage NuGet Packages" and search for Firebase Storage. Install the Xamarin.Firebase.Storage Packages. 

 
 
Step 8
 
Open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml and add the following code. The layout will have a ImageView in order to display the preview of uploading image. I also added two buttons to select image from gallery and upload to firebase storage.
(FileName: Main.axml)

XAML Code
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:padding="16dp">  
  7.   <ImageView  
  8.         android:id="@+id/imgView"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent"  
  11.         />  
  12.     <LinearLayout  
  13.         android:layout_above="@id/imgView"  
  14.         android:orientation="horizontal"  
  15.         android:layout_width="match_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:layout_alignParentBottom="true"  
  18.         android:weightSum="2">  
  19.         <Button  
  20.             android:id="@+id/btnChoose"  
  21.             android:text="Choose"  
  22.             android:layout_width="0dp"  
  23.             android:layout_weight="1"  
  24.             android:layout_height="wrap_content" />  
  25.         <Button  
  26.             android:id="@+id/btnUpload"  
  27.             android:text="Upload"  
  28.             android:layout_width="0dp"  
  29.             android:layout_weight="1"  
  30.             android:layout_height="wrap_content" />  
  31.     </LinearLayout>  
  32. </RelativeLayout>  
 
Step 9
 
Open Solution Explorer-> Project Name-> MainActivity and add the following code to main activity and use appropriate namespaces.
 
Complete Code of Main Activity
  1. using Android.App;  
  2. using Android.Content;  
  3. using Android.Gms.Tasks;  
  4. using Android.Graphics;  
  5. using Android.OS;  
  6. using Android.Provider;  
  7. using Android.Runtime;  
  8. using Android.Widget;  
  9. using Firebase;  
  10. using Firebase.Storage;  
  11. using System;  
  12. using System.IO;  
  13. namespace XamarinFirebaseUpload  
  14. {  
  15.     [Activity(Label = "XamarinFirebaseUpload", MainLauncher = true)]  
  16.     public class MainActivity : AppCompatActivity, IOnProgressListener, IOnSuccessListener, IOnFailureListener  
  17.     {  
  18.         private Button btnUpload, btnChoose;  
  19.         private ImageView imgView;  
  20.         private Android.Net.Uri filePath;  
  21.         private const int PICK_IMAGE_REQUSET = 71;  
  22.         ProgressDialog progressDialog;  
  23.         FirebaseStorage storage;  
  24.         StorageReference storageRef;  
  25.         protected override void OnCreate(Bundle savedInstanceState)  
  26.         {  
  27.             base.OnCreate(savedInstanceState);  
  28.             // Set our view from the "main" layout resource  
  29.             SetContentView(Resource.Layout.Main);  
  30.             //Firebase Init  
  31.             FirebaseApp.InitializeApp(this);  
  32.             storage = FirebaseStorage.Instance;  
  33.             storageRef = storage.GetReferenceFromUrl("gs://xamarin-firebase-upload.appspot.com");  
  34.             //Init View  
  35.             btnChoose = FindViewById<Button>(Resource.Id.btnChoose);  
  36.             btnUpload = FindViewById<Button>(Resource.Id.btnUpload);  
  37.             imgView = FindViewById<ImageView>(Resource.Id.imgView);  
  38.             //Events  
  39.             btnChoose.Click += delegate   
  40.             {  
  41.                 ChooseImage();  
  42.             };  
  43.             btnUpload.Click += delegate   
  44.             {  
  45.                 UploadImage();  
  46.             };  
  47.         }  
  48.         private void UploadImage()  
  49.         {  
  50.             if (filePath != null)  
  51.                 progressDialog = new ProgressDialog(this);  
  52.             progressDialog.SetTitle("Uploading...");  
  53.             progressDialog.Window.SetType(Android.Views.WindowManagerTypes.SystemAlert);  
  54.             progressDialog.Show();  
  55.             var images = storageRef.Child("images/"+Guid.NewGuid().ToString());  
  56.             images.PutFile(filePath)  
  57.                 .AddOnProgressListener(this)  
  58.                 .AddOnSuccessListener(this)  
  59.                 .AddOnFailureListener(this);  
  60.         }  
  61.         private void ChooseImage()  
  62.         {  
  63.             Intent intent = new Intent();  
  64.             intent.SetType("image/*");  
  65.             intent.SetAction(Intent.ActionGetContent);  
  66.             StartActivityForResult(Intent.CreateChooser(intent, "Select Picture"), PICK_IMAGE_REQUSET);  
  67.         }  
  68.         protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)  
  69.         {  
  70.             base.OnActivityResult(requestCode, resultCode, data);  
  71.             if(requestCode == PICK_IMAGE_REQUSET &&  
  72.                 resultCode == Result.Ok &&  
  73.                 data != null &&  
  74.                 data.Data != null)  
  75.             {  
  76.                 filePath = data.Data;  
  77.                 try  
  78.                 {  
  79.                     Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, filePath);  
  80.                     imgView.SetImageBitmap(bitmap);  
  81.                 }  
  82.                 catch (IOException ex)  
  83.                 {  
  84.                     Console.WriteLine(ex);  
  85.                 }  
  86.             }  
  87.         }  
  88.         public void OnProgress(Java.Lang.Object snapshot)  
  89.         {  
  90.             var taskSnapShot = (UploadTask.TaskSnapshot)snapshot;  
  91.             double progress = (100.0* taskSnapShot.BytesTransferred / taskSnapShot.TotalByteCount);  
  92.             progressDialog.SetMessage("Uploaded " + (int)progress + " %");  
  93.         }  
  94.         public void OnSuccess(Java.Lang.Object result)  
  95.         {  
  96.             progressDialog.Dismiss();  
  97.             Toast.MakeText(this"Uploaded Successful", ToastLength.Short).Show();  
  98.         }  
  99.         public void OnFailure(Java.Lang.Exception e)  
  100.         {  
  101.             progressDialog.Dismiss();  
  102.             Toast.MakeText(this""+e.Message, ToastLength.Short).Show();  
  103.         }  
  104.     }  
  105. }  
Step 10
 
Now, Add the Internet permission in your Android Manifest file. Let's open Solution Explorer-> Properties-> AndroidManifest and let's add the code inside application tags.
 
Permissions 
  1. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  2. <uses-permission android:name="android.permission.INTERNET" />  
  3. <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />  
Output
 
Now when you run the app and upload the Image to Firebase, you will see that image gets uploaded to Firebase storage inside images folder. 
 

Up Next
    Ebook Download
    View all
    Learn
    View all