user7810601
user7810601

Reputation:

Upload Multiple Images on Firebase - Android Studio

Hi guys im trying to upload 3 images on firebase with captions but it only uploads the first successfully then the field for image 2 and 3 it copies the download url for image 1 on the database. Can someone help me fix this so that each image to get its own download url

Here is my XML

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ke.co.tapeli.tapeli.UploadActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textView2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Image 1" />

            <ImageButton
                android:id="@+id/imageSelect"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:adjustViewBounds="true"
                android:background="@android:color/white"
                android:scaleType="centerCrop"
                app:srcCompat="@drawable/add_btn" />

            <TextView
                android:id="@+id/textView4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Image 2" />

            <ImageButton
                android:id="@+id/imageSelect1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:adjustViewBounds="true"
                android:background="@android:color/white"
                android:scaleType="centerCrop"
                app:srcCompat="@drawable/add_btn" />

            <TextView
                android:id="@+id/textView5"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Image 3" />

            <ImageButton
                android:id="@+id/imageSelect2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:adjustViewBounds="true"
                android:background="@android:color/white"
                android:scaleType="centerCrop"
                app:srcCompat="@drawable/add_btn" />

            <EditText
                android:id="@+id/titleField"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="20dp"
                android:background="@drawable/input_outline"
                android:drawableLeft="@drawable/ic_con_name"
                android:ems="10"
                android:hint="Conman's Name"
                android:inputType="textPersonName"
                android:padding="7dp"
                android:singleLine="true"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/descField"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="10dp"
                android:background="@drawable/input_outline"
                android:drawableLeft="@drawable/ic_con_desc"
                android:ems="10"
                android:hint="Crime Description"
                android:inputType="textMultiLine"
                android:padding="7dp"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/phoneField"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="20dp"
                android:background="@drawable/input_outline"
                android:drawableLeft="@drawable/ic_con_phone"
                android:ems="10"
                android:hint="Conman's Number"
                android:inputType="textMultiLine"
                android:padding="7dp"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/passField"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="20dp"
                android:background="@drawable/input_outline"
                android:drawableLeft="@drawable/ic_con_pass"
                android:ems="10"
                android:hint="Conman's ID Number/ Passport "
                android:inputType="textMultiLine"
                android:padding="7dp"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/otherField"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="20dp"
                android:background="@drawable/input_outline"
                android:drawableLeft="@drawable/ic_con_info"
                android:ems="10"
                android:hint="Any other Information"
                android:inputType="textMultiLine"
                android:padding="7dp"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/stepsField"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="20dp"
                android:background="@drawable/input_outline"
                android:drawableLeft="@drawable/ic_con_steps"
                android:ems="10"
                android:hint="Steps Taken (Eg. Went to court)"
                android:inputType="textMultiLine"
                android:padding="7dp"
                android:textSize="14sp" />

            <EditText
                android:id="@+id/policeField"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="20dp"
                android:background="@drawable/input_outline"
                android:drawableLeft="@drawable/ic_con_police"
                android:ems="10"
                android:hint="Police Station Reported To"
                android:inputType="textMultiLine"
                android:padding="7dp"
                android:textSize="14sp" />

            <Button
                android:id="@+id/submitBtn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="20dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="50dp"
                android:background="@color/colorPrimary"
                android:text="Report a Tapeli"
                android:textColor="@android:color/white" />

        </LinearLayout>

    </ScrollView>

</FrameLayout>

Here is my Java Code

package ke.co.tapeli.tapeli;

import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import ke.co.tapeli.tapeli.Auths.Login;

public class UploadActivity extends AppCompatActivity {

    private ImageButton mSelectImage;
    private ImageButton mSelectImage1;
    private ImageButton mSelectImage2;

    private EditText mPostTitle;
    private EditText mPostDesc;

    private EditText mPostNumber;
    private EditText mPostPass;
    private EditText mPostInfo;
    private EditText mPostSteps;
    private EditText mPostPolice;

    private Button mSubmitBtn;
    private Uri mImageUri = null;

    private Uri mImageUri1 = null;
    private Uri mImageUri2 = null;

    private StorageReference mStorage;
    private DatabaseReference mDatabase;

    private ProgressDialog mProgress;

    private static final int GALLERY_REQUEST = 1;
    private static final int GALLERY_REQUEST2 = 2;
    private static final int GALLERY_REQUEST3 = 3;


    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        mAuth = FirebaseAuth.getInstance();
        mAuthListner = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                if(firebaseAuth.getCurrentUser() == null){

                    Intent loginIntent = new Intent(UploadActivity.this, Login.class);
                    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(loginIntent);

                }

            }
        };


        mStorage = FirebaseStorage.getInstance().getReference();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Matapeli");

        mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
        mSelectImage1 = (ImageButton) findViewById(R.id.imageSelect1);
        mSelectImage2 = (ImageButton) findViewById(R.id.imageSelect2);
        mPostTitle = (EditText) findViewById(R.id.titleField);
        mPostDesc = (EditText) findViewById(R.id.descField);

        mPostNumber = (EditText) findViewById(R.id.phoneField);
        mPostPass = (EditText) findViewById(R.id.passField);
        mPostInfo = (EditText) findViewById(R.id.otherField);
        mPostSteps = (EditText) findViewById(R.id.stepsField);
        mPostPolice = (EditText) findViewById(R.id.policeField);

        mProgress = new ProgressDialog(this);

        mSubmitBtn = (Button) findViewById(R.id.submitBtn);

        mSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                galleryIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                startActivityForResult(galleryIntent, GALLERY_REQUEST);
            }
        });

        mSelectImage1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                galleryIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                startActivityForResult(galleryIntent, GALLERY_REQUEST2);
            }
        });

        mSelectImage2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                galleryIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                startActivityForResult(galleryIntent, GALLERY_REQUEST3);
            }
        });

        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                startPosting();
            }
        });
    }

    private void startPosting() {

        mProgress.setMessage("Adding a Tapeli...");


        final String title_val = mPostTitle.getText().toString().trim();
        final String desc_val = mPostDesc.getText().toString().trim();

        final String namba_val = mPostNumber.getText().toString().trim();
        final String pass_val = mPostPass.getText().toString().trim();
        final String info_val = mPostInfo.getText().toString().trim();
        final String steps_val = mPostSteps.getText().toString().trim();
        final String police_val = mPostPolice.getText().toString().trim();

        if(!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri !=null){

            mProgress.show();

            StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());
            StorageReference filepath1 = mStorage.child("Blog_Images").child(mImageUri1.getLastPathSegment());
            StorageReference filepath2 = mStorage.child("Blog_Images").child(mImageUri2.getLastPathSegment());

            filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    Uri downloadurl = taskSnapshot.getDownloadUrl();

                    DatabaseReference newPost = mDatabase.push();
                    newPost.child("title").setValue(title_val);
                    newPost.child("desc").setValue(desc_val);

                    newPost.child("number").setValue(namba_val);
                    newPost.child("passport").setValue(pass_val);
                    newPost.child("info").setValue(info_val);
                    newPost.child("steps").setValue(steps_val);
                    newPost.child("police").setValue(police_val);

                    newPost.child("image").setValue(downloadurl.toString());
                    newPost.child("image1").setValue(downloadurl.toString());
                    newPost.child("image2").setValue(downloadurl.toString());


                    mProgress.dismiss();

                    finish();



                }
            });

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){

            mImageUri = data.getData();


            mSelectImage.setImageURI(mImageUri);

        }

        if(requestCode == GALLERY_REQUEST2 && resultCode == RESULT_OK){


            mImageUri1 = data.getData();


            mSelectImage1.setImageURI(mImageUri1);

        }

        if(requestCode == GALLERY_REQUEST3 && resultCode == RESULT_OK){



            mImageUri2 = data.getData();

            mSelectImage2.setImageURI(mImageUri2);
        }
    }
}

Upvotes: 0

Views: 2771

Answers (3)

Ros&#225;rio P. Fernandes
Ros&#225;rio P. Fernandes

Reputation: 11326

That's because you're only calling putFile() with the first image. Which means the first image will be the only one uploaded. You need to call putFile() on the other images as well:

    StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());
    StorageReference filepath1 = mStorage.child("Blog_Images").child(mImageUri1.getLastPathSegment());
    StorageReference filepath2 = mStorage.child("Blog_Images").child(mImageUri2.getLastPathSegment());
    final DatabaseReference newPost = mDatabase.push();

    filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            Uri downloadurl = taskSnapshot.getDownloadUrl();
            newPost.child("title").setValue(title_val);
            newPost.child("desc").setValue(desc_val);
            newPost.child("number").setValue(namba_val);
            newPost.child("passport").setValue(pass_val);
            newPost.child("info").setValue(info_val);
            newPost.child("steps").setValue(steps_val);
            newPost.child("police").setValue(police_val);
            newPost.child("image").setValue(downloadurl.toString());
        }
    });
    filepath1.putFile(mImageUri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            Uri downloadurl = taskSnapshot.getDownloadUrl();
            newPost.child("image1").setValue(downloadurl.toString());
        }
    });
    filepath2.putFile(mImageUri2).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            Uri downloadurl = taskSnapshot.getDownloadUrl();
            newPost.child("image2").setValue(downloadurl.toString());
            mProgress.dismiss();
            finish();
        }
    });

Upvotes: 2

Alex Mamo
Alex Mamo

Reputation: 138824

Your filepath is always the same for your photos, that's why you are uploading only the fist one. So to solve this, you need to use different paths of each photo like this:

filepath1.putFile(mImageUri1).addOnSuccessListener(/* ... */);
filepath2.putFile(mImageUri2).addOnSuccessListener(/* ... */);
filepath3.putFile(mImageUri3).addOnSuccessListener(/* ... */);

Upvotes: 1

HarshitG
HarshitG

Reputation: 2827

You are only saving image to

filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Uri downloadurl = taskSnapshot.getDownloadUrl();

                DatabaseReference newPost = mDatabase.push();
                newPost.child("title").setValue(title_val);
                newPost.child("desc").setValue(desc_val);

                newPost.child("number").setValue(namba_val);
                newPost.child("passport").setValue(pass_val);
                newPost.child("info").setValue(info_val);
                newPost.child("steps").setValue(steps_val);
                newPost.child("police").setValue(police_val);

                newPost.child("image").setValue(downloadurl.toString());
                newPost.child("image1").setValue(downloadurl.toString());
                newPost.child("image2").setValue(downloadurl.toString());


                mProgress.dismiss();

                finish();



            }
        });

Use same function for uploading other imagestoo ..

filepath1.putFile(mImageUri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Uri downloadurl = taskSnapshot.getDownloadUrl();

                DatabaseReference newPost = mDatabase.push();
                newPost.child("title").setValue(title_val);
                newPost.child("desc").setValue(desc_val);

                newPost.child("number").setValue(namba_val);
                newPost.child("passport").setValue(pass_val);
                newPost.child("info").setValue(info_val);
                newPost.child("steps").setValue(steps_val);
                newPost.child("police").setValue(police_val);

                newPost.child("image").setValue(downloadurl.toString());
                newPost.child("image1").setValue(downloadurl.toString());
                newPost.child("image2").setValue(downloadurl.toString());


                mProgress.dismiss();

                finish();



            }
        });

filepath2.putFile(mImageUri2).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Uri downloadurl = taskSnapshot.getDownloadUrl();

                DatabaseReference newPost = mDatabase.push();
                newPost.child("title").setValue(title_val);
                newPost.child("desc").setValue(desc_val);

                newPost.child("number").setValue(namba_val);
                newPost.child("passport").setValue(pass_val);
                newPost.child("info").setValue(info_val);
                newPost.child("steps").setValue(steps_val);
                newPost.child("police").setValue(police_val);

                newPost.child("image").setValue(downloadurl.toString());
                newPost.child("image1").setValue(downloadurl.toString());
                newPost.child("image2").setValue(downloadurl.toString());


                mProgress.dismiss();

                finish();



            }
        });

Upvotes: 1

Related Questions