Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaHow to Retrieve Image from Firebase in Realtime in Android?

How to Retrieve Image from Firebase in Realtime in Android?

When we are creating an android app then instead of inserting an image manually we want to get that from the internet and using this process the app size will become less. So, using firebase we can do this. We can create our storage bucket and we can insert our image there and get it directly into our app. But what if we want to change that image and instead of that image we want to insert the new one then for doing this we have to do change in our code but here our solution comes we can get that image in realtime in our app using realtime database then we can change that image from firebase and in realtime, our app image will also change we don’t have to do changes in our code. Note that we are going to implement this project using the Java language. 

Steps to Retrieve Image from Firebase in Realtime

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Connect your app to firebase 

In the android studio, go to the Tools option in the topmost bar then click on the firebase option then click the connect to firebase button. Refer to know how to connect the app to firebase.

Step 3: Add dependency to build.gradle(Module:app)

Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.

implementation ‘com.google.firebase:firebase-database:20.0.6’

implementation ‘com.squareup.picasso:picasso:2.71828’

Now sync the project from the top right corner option of Sync now.

Step 4: Add Internet permission in AndroidManifest.xml file

Navigate to the AndroidManifest.xml file and add the below permission for getting internet permission in the app.

<uses-permission android:name="android.permission.INTERNET"/>

Step 5: Add image on firebase storage and copy the link of that image 

In firebase go to the storage option then click on Get Started button 

After that click on the Upload file option to insert an image on firebase storage. 

After that click on the image inserted then the image details come in the right section then click on the access token and copy the image URL.

Step 6: Add that image URL to the Realtime database 

Go to the Realtime database option then click on the create database button.

After clicking on the getting started button select the option locked mode for database security rule. After that click on the + option to create a child node for the database.

After that name, that child node and insert the image URL in the value section then click on the Add button.

Then go to the rule section because we created this database in locked mode but we have to read the database in our app. In the rule section go to the read section row and change that from false to true.

Step 7: Working with the activity_main.xml and MainActivity.java file

Go to the activity_main.xml and MainActivity.java file and refer to the following code. Below is the code for activity.main.xml and MainActivity.java file.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!-- we are using ImageView for displaying image-->
    <ImageView
        android:id="@+id/rImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp" />
 
</LinearLayout>


Step 8:  Source code of Mainactivity.java

Go to the existing Mainactivity.java and refer to the following code.

Java




import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
 
public class MainActivity extends AppCompatActivity {
 
    // Initializing the ImageView
    ImageView rImage;
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // getting ImageView by its id
        rImage = findViewById(R.id.rImage);
 
        // we will get the default FirebaseDatabase instance
        FirebaseDatabase firebaseDatabase
            = FirebaseDatabase.getInstance();
 
        // we will get a DatabaseReference for the database
        // root node
        DatabaseReference databaseReference
            = firebaseDatabase.getReference();
 
        // Here "image" is the child node value we are
        // getting child node data in the getImage variable
        DatabaseReference getImage
            = databaseReference.child("image");
 
        // Adding listener for a single change
        // in the data at this location.
        // this listener will triggered once
        // with the value of the data at the location
        getImage.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(
                    @NonNull DataSnapshot dataSnapshot)
                {
                    // getting a DataSnapshot for the
                    // location at the specified relative
                    // path and getting in the link variable
                    String link = dataSnapshot.getValue(
                        String.class);
 
                    // loading that data into rImage
                    // variable which is ImageView
                    Picasso.get().load(link).into(rImage);
                }
 
                // this will called when any problem
                // occurs in getting data
                @Override
                public void onCancelled(
                    @NonNull DatabaseError databaseError)
                {
                    // we are showing that error message in
                    // toast
                    Toast
                        .makeText(MainActivity.this,
                                  "Error Loading Image",
                                  Toast.LENGTH_SHORT)
                        .show();
                }
            });
    }
}


Output:

RELATED ARTICLES

Most Popular

Recent Comments