在Firebase上上传多个图片 - Android Studio

时间:2018-01-18 11:15:54

标签: java android firebase firebase-realtime-database firebase-storage

大家好我试图在firebase上上传3张图片并加上字幕,但它只上传第一张成功然后上传图片2和3的字段,它会复制数据库中图片1的下载网址。有人可以帮我解决这个问题,以便每个图像都能获得自己的下载URL

这是我的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>

这是我的Java代码

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);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

那是因为您只使用第一张图片调用putFile()。这意味着第一张图片将是唯一上传的图片。您还需要在其他图片上调用putFile()

    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();
        }
    });

答案 1 :(得分:1)

您的filepath对于您的照片始终是相同的,这就是为什么您只上传第一个照片的原因。因此,要解决此问题,您需要使用每张照片的不同路径:

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

答案 2 :(得分:1)

您只是将图片保存到

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();



            }
        });

使用相同的功能上传其他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();



            }
        });