代码之家  ›  专栏  ›  技术社区  ›  Eoghan Casey

Firebase在Android中,存储正常,但数据库不正常

  •  0
  • Eoghan Casey  · 技术社区  · 7 年前

    我正在尝试在Firebase中存储一个包含有关该图像的一些相关数据的图像。当我按下保存按钮时,图像会保存到我的存储文件夹中没有问题,但数据库属性没有被保存,我不知道为什么。 这是我的代码:

    String Storage_Path = "All_Book_Images";
    
    String Database_Path = "All_Books";
    
    Uri FilePathUri;
    
    StorageReference storageReference;
    DatabaseReference databaseReference;
    
    int Image_Request_Code = 71;
    
    ProgressDialog progressDialog;
    
    Button imageButton, saveButton;
    EditText title, author, price, category, additionalInfo;
    
    ImageView SelectImage;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bookupload);
    
        SelectImage = (ImageView) findViewById(R.id.book_image);
    
        title = (EditText) findViewById(R.id.title_text);
        author = (EditText) findViewById(R.id.author_text);
        price = (EditText) findViewById(R.id.price_text);
        category = (EditText) findViewById(R.id.category_text);
        additionalInfo = (EditText) findViewById(R.id.info_text);
    
        storageReference = FirebaseStorage.getInstance().getReference();
        databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
    }
    
    public void imageButton(View view){
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select Image"),0);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0 && resultCode == RESULT_OK){
            FilePathUri = data.getData();
    
            try{
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
                SelectImage.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public String getActualImage(Uri uri){
        ContentResolver contentResolver = getContentResolver();
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        return  mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
    }
    
    public void uploadData(View view){
    
        if(FilePathUri != null){
    
    
            final ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("Uploading");
            progressDialog.show();
    
            StorageReference reference = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + getActualImage(FilePathUri));
    
    
            reference.putFile(FilePathUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
    
    
    
                    String Title = title.getText().toString();
                    String Author = author.getText().toString();
                    String Price = price.getText().toString();
                    String Category = category.getText().toString();
                    String AdditionalInfo = additionalInfo.getText().toString();
    
                    Book book = new Book(taskSnapshot.getDownloadUrl().toString(), Title, Author, Price, Category, AdditionalInfo);
    
                    String id = databaseReference.push().getKey();
    
                    databaseReference.child(id).setValue(book);
    
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(),"Data uploaded",Toast.LENGTH_LONG).show();
                }
            })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
    
                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @SuppressWarnings("VisibleForTests")
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            double totalProgress = (100*taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                            progressDialog.setMessage("Uploaded % " + (int)totalProgress);
                        }
                    });
    
    
        } else {
            // show message
            Toast.makeText(getApplicationContext(),"Please select data first",Toast.LENGTH_LONG).show();
        }
    
    }
    

    是什么导致它与Firebase fine的存储方面交互,而不是与数据库交互?

    2 回复  |  直到 7 年前
        1
  •  0
  •   Gastón Saillén Michael Lehenbauer    7 年前

    查看Firebase官方文件中的这段代码,我已经在里面写下了你的一些要求,但你明白了

    private void writeNewPost(String Title, String Price, String Author) {
    
        String key = databaseReference.push().getKey();
        Post post = new Post(Title, Price, Author);
        Map<String, Object> postValues = post.toMap();
    
        Map<String, Object> books = new HashMap<>();
        books.put(Title, postValues);
        books.put(Price, postValues);
        books.put(Author, postValues);
    
        mDatabase.child(key).updateChildren(books);
    }
    

    有关详细信息: https://firebase.google.com/docs/database/android/read-and-write

    PS:您可以使用 updateChildren() setValue() ,这取决于你需要哪一个。

    如果您使用 setValue() 这样,在指定的位置(包括辅助节点)覆盖数据。

    只需调用一个 updateChildren()

        2
  •  0
  •   Eoghan Casey    7 年前

    事实证明,我的代码实际上运行正常,只是Firebase数据库的规则设置不正确。我在问题中发布的代码应该适用于任何试图实现此功能的人。