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.
- <ItemGroup>
- <GoogleServicesJson Include="google-services.json" />
- </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
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:padding="16dp">
- <ImageView
- android:id="@+id/imgView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- />
- <LinearLayout
- android:layout_above="@id/imgView"
- android:orientation="horizontal"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:weightSum="2">
- <Button
- android:id="@+id/btnChoose"
- android:text="Choose"
- android:layout_width="0dp"
- android:layout_weight="1"
- android:layout_height="wrap_content" />
- <Button
- android:id="@+id/btnUpload"
- android:text="Upload"
- android:layout_width="0dp"
- android:layout_weight="1"
- android:layout_height="wrap_content" />
- </LinearLayout>
- </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
- using Android.App;
- using Android.Content;
- using Android.Gms.Tasks;
- using Android.Graphics;
- using Android.OS;
- using Android.Provider;
- using Android.Runtime;
- using Android.Widget;
- using Firebase;
- using Firebase.Storage;
- using System;
- using System.IO;
- namespace XamarinFirebaseUpload
- {
- [Activity(Label = "XamarinFirebaseUpload", MainLauncher = true)]
- public class MainActivity : AppCompatActivity, IOnProgressListener, IOnSuccessListener, IOnFailureListener
- {
- private Button btnUpload, btnChoose;
- private ImageView imgView;
- private Android.Net.Uri filePath;
- private const int PICK_IMAGE_REQUSET = 71;
- ProgressDialog progressDialog;
- FirebaseStorage storage;
- StorageReference storageRef;
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
-
- SetContentView(Resource.Layout.Main);
-
- FirebaseApp.InitializeApp(this);
- storage = FirebaseStorage.Instance;
- storageRef = storage.GetReferenceFromUrl("gs://xamarin-firebase-upload.appspot.com");
-
- btnChoose = FindViewById<Button>(Resource.Id.btnChoose);
- btnUpload = FindViewById<Button>(Resource.Id.btnUpload);
- imgView = FindViewById<ImageView>(Resource.Id.imgView);
-
- btnChoose.Click += delegate
- {
- ChooseImage();
- };
- btnUpload.Click += delegate
- {
- UploadImage();
- };
- }
- private void UploadImage()
- {
- if (filePath != null)
- progressDialog = new ProgressDialog(this);
- progressDialog.SetTitle("Uploading...");
- progressDialog.Window.SetType(Android.Views.WindowManagerTypes.SystemAlert);
- progressDialog.Show();
- var images = storageRef.Child("images/"+Guid.NewGuid().ToString());
- images.PutFile(filePath)
- .AddOnProgressListener(this)
- .AddOnSuccessListener(this)
- .AddOnFailureListener(this);
- }
- private void ChooseImage()
- {
- Intent intent = new Intent();
- intent.SetType("image/*");
- intent.SetAction(Intent.ActionGetContent);
- StartActivityForResult(Intent.CreateChooser(intent, "Select Picture"), PICK_IMAGE_REQUSET);
- }
- protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
- {
- base.OnActivityResult(requestCode, resultCode, data);
- if(requestCode == PICK_IMAGE_REQUSET &&
- resultCode == Result.Ok &&
- data != null &&
- data.Data != null)
- {
- filePath = data.Data;
- try
- {
- Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, filePath);
- imgView.SetImageBitmap(bitmap);
- }
- catch (IOException ex)
- {
- Console.WriteLine(ex);
- }
- }
- }
- public void OnProgress(Java.Lang.Object snapshot)
- {
- var taskSnapShot = (UploadTask.TaskSnapshot)snapshot;
- double progress = (100.0* taskSnapShot.BytesTransferred / taskSnapShot.TotalByteCount);
- progressDialog.SetMessage("Uploaded " + (int)progress + " %");
- }
- public void OnSuccess(Java.Lang.Object result)
- {
- progressDialog.Dismiss();
- Toast.MakeText(this, "Uploaded Successful", ToastLength.Short).Show();
- }
- public void OnFailure(Java.Lang.Exception e)
- {
- progressDialog.Dismiss();
- Toast.MakeText(this, ""+e.Message, ToastLength.Short).Show();
- }
- }
- }
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
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
- <uses-permission android:name="android.permission.INTERNET" />
- <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.