单个照片路径进入多个HashMap元素

时间:2018-05-31 12:15:21

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

我想将多张照片上传到Firebase存储,每张照片都应该有一个独特的路径存储在一个独特的HashMap元素中,该元素将上传到Firebase数据库。

出于某种原因,每次将HashMap上传到Firebase数据库时,所有HashMap元素都将包含相同的照片路径。

This is a photo of the problem that I'm facing

此主要活动代码:

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
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 java.util.HashMap;

public class MainActivity extends AppCompatActivity {
    private Button mSelectimage;
    private StorageReference mStorage;
    private DatabaseReference mDatabase;
    private Uri image;
    private String photoPath;
    final static int GALLERY_INTENT = 2;
    int i;
    int j;
    int totalItelmsSelected;
    String push_id;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSelectimage = (Button) findViewById(R.id.button2);
        mStorage = FirebaseStorage.getInstance().getReference();
        mDatabase = FirebaseDatabase.getInstance().getReference();
        push_id = mDatabase.child("users").push().getKey();


        mSelectimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                startActivityForResult(intent, GALLERY_INTENT);
            }
        });

    }


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

        final HashMap <String,Object> datamap = new HashMap<String, Object>();;
        datamap.put("image "+0,0);
        datamap.put("image "+1,0);
        datamap.put("image "+2,0);
        datamap.put("image "+3,0);


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

            totalItelmsSelected = data.getClipData().getItemCount();

            if (totalItelmsSelected <= 4) {

            for (i = 0; i < totalItelmsSelected; i++) {
                image = data.getClipData().getItemAt(i).getUri();
                final StorageReference filepath = mStorage.child("photos").child(image.getLastPathSegment() + ".jpg");
                filepath.putFile(image).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                     photoPath = filepath.getPath();
                     datamap.put("image " + i, photoPath);
                     mDatabase.child("users").child(push_id).updateChildren(datamap);
                        Toast.makeText(MainActivity.this, i + " Photos has been uploaded.", Toast.LENGTH_SHORT).show();

                    }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(MainActivity.this, "Problem in Uploading " + i + " Photos.", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                datamap.put("Name","Kamil");
                datamap.put("Email", "Kamil@gmail.com");
                mDatabase.child("users").child(push_id).setValue(datamap).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(MainActivity.this, "Uploading to the database is done", Toast.LENGTH_SHORT).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(MainActivity.this, "Problem in registuring the information", Toast.LENGTH_SHORT).show();
                    }
                });
            }else if (totalItelmsSelected >4){
                Toast.makeText(MainActivity.this, "Please Choose only 4 photos ot less", Toast.LENGTH_SHORT).show();
            }
        }


    }

}

这是build.gradle应用程序代码:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.mohammed.storemultipleimages"
        minSdkVersion 26
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.google.firebase:firebase-database:16.0.1'
    implementation 'com.google.firebase:firebase-storage:16.0.1'
    implementation 'com.google.firebase:firebase-auth:16.0.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

apply plugin: 'com.google.gms.google-services'

This is the result after removing the for loop containing j

1 个答案:

答案 0 :(得分:0)

for (j=0; j<i; j++) {
     photoPath = filepath.getPath();
     datamap.put("image " + j, photoPath);

此处photoPath与整个循环相同,因此您的datamap包含相同的路径。

解决方案是删除代码中的for循环:for (j=0; j<i; j++) {

public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
    photoPath = filepath.getPath();
    datamap.put("image " + i, photoPath);    
    mDatabase.child("users").child(push_id).updateChildren(datamap);
    Toast.makeText(MainActivity.this, i + " Photos has been uploaded.", Toast.LENGTH_SHORT).show();
}