【问题标题】:Uploading Hashmap Variable to Firebase Database将 Hashmap 变量上传到 Firebase 数据库
【发布时间】:2018-11-08 23:45:05
【问题描述】:

我正在我的 Hashmap 中创建一个元素,其中包含从手机存储上传到 Firebase 存储的照片的照片路径。如果我上传了多张照片,我的 Hashmap 中应该有一个元素(图像 1、图像 2、图像 3……),它根据上传的照片数量保存照片路径。

每次我运行程序时,Hashmap“姓名,电子邮件”的其他元素都会被上传,但照片路径(“图像”+i)不会上传。

我希望最终结果在数据库中如下所示: the end result in Firebase Database

我的工作有什么错误吗?有什么方法可以使这项工作吗?

这是我的代码:

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.util.Log;
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.ArrayList;
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;

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

        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, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        final HashMap <Object,Object> datamap = new HashMap<Object, Object>();

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

            if(data.getClipData() != null){

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

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

这是我的 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'])
    //noinspection GradleCompatible
    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:11.8.0'
    implementation 'com.google.firebase:firebase-storage:11.8.0'
    implementation 'com.google.firebase:firebase-auth:11.8.0'
    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'

【问题讨论】:

  • 请给我们grandle文件,可能是firebase版本的问题
  • 尝试 .push().updateChildren(datamap) 而不是 setValue()
  • @ParaskevasNtsounos 完成
  • @KamilAhmed 试试我的答案并告诉我它是否有效
  • @JinsonPaul 同样的问题,当我上传 2 张照片时,它只需要一张照片的路径。它没有放置 2 条路径。

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


【解决方案1】:

尝试使用最新版本的谷歌服务,例如(项目级别):

classpath 'com.google.gms:google-services:4.0.1'

并用以下代码替换您现有的代码:

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'])
    //noinspection GradleCompatible
    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'

【讨论】:

    【解决方案2】:

    这里的问题是,当您将图像放入存储中时,此过程是异步发生的。因此,在将图像存储并在 hashmap 中添加 uri 之前,将调用 firebase 数据库上的方法:

    所以你必须确保在调用firebase上的方法之前你已经完成了hashmap过程:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        final HashMap <Object,Object> datamap = new HashMap<Object, Object>();
    
        if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
    
            if(data.getClipData() != null){
    
                totalItelmsSelected = data.getClipData().getItemCount();
    
                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);
                            datamap.put("Name", "Kamil");
                            datamap.put("Email", "Kamil@gmail.com");
    
                          mDatabase.child("users").push().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();
                               }
                           });
                            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();
                        }
                    });
                }
            }
        }
    }
    

    【讨论】:

    • 如果我在循环内或循环外完成 Hashmap 会有所不同吗?在将其上传到 Firebase 数据库之前,我应该将所有元素一个接一个地添加到 Hashmap 吗?我不能随机添加数据到Hashmap然后一起上传吗?
    • 你没有明白我的意思。我的意思是在运行datamap.put("image "+i , photoPath) 之前,您的应用程序正在运行datamap.put("Name", "Kamil")datamap.put("Email", "Kamil@gmail.com") 和`mDatabase.child("users")........`。因此,在您调用 firebase 数据库后,您的照片路径将被放入 hashmap 中。掌握一下java异步,你就会明白了。
    【解决方案3】:
    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, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        final HashMap <Object,Object> datamap = new HashMap<Object, Object>();
    
        if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
    
            if(data.getClipData() != null){
    
                totalItelmsSelected = data.getClipData().getItemCount();
    
                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);
                            Toast.makeText(MainActivity.this, i+" Photos has been uploaded.", 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();
                            }
                            });
    
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(MainActivity.this, "Problem in Uploading "+i+" Photos.", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
    
    
            }
        }
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2019-06-07
      • 2021-01-31
      • 2017-10-19
      • 1970-01-01
      相关资源
      最近更新 更多