简体   繁体   English

将图像上传到Firebase-Java

[英]Upload Image to Firebase - Java

i try to upload an image, unfortunately when i try to click button continue to upload it, the apk always crash, here's the log 我尝试上传图片,不幸的是,当我尝试单击按钮继续上传图片时,apk始终崩溃,这是日志

It says childName cannot be null or empty 它说childName不能为null或为空 错误记录

the java Java

Java映像

package com.example.firstapplication;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
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 com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class Register_two extends AppCompatActivity {

    LinearLayout btn_back;
    Button btn_continue, btn_upload_photo;
    ImageView prof_pic;
    EditText bio, nama_lengkap;

    Uri photo_location;
    Integer photo_max = 1;

    DatabaseReference reference;
    StorageReference storage;

    String USERNAME_KEY = "usernamekey";
    String username_key = "";
    String username_key_new = "";


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

        getUsernameLocal();

        btn_continue = findViewById(R.id.btn_continue);
        btn_back = findViewById(R.id.btn_back);
        btn_upload_photo = findViewById(R.id.btn_upload_photo);
        prof_pic = findViewById(R.id.prof_pic);


        btn_upload_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            findPhoto();
            }
        });

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

                //ubah state menjadi loading...
                btn_continue.setEnabled(false);
                btn_continue.setText("Loading...");

                //menyimpan ke Firebase
                reference = FirebaseDatabase.getInstance().getReference().child("Users").child(username_key_new);
                storage = FirebaseStorage.getInstance().getReference().child("Photousers").child(username_key_new);

                //validasi untuk file (apakah ada?)
                if (photo_location != null){
                    final StorageReference storageReference1 =
                            storage.child(System.currentTimeMillis() + "." +
                            getFileExtention(photo_location));

                    storageReference1.putFile(photo_location)
                            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                            storageReference1.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    String uri_photo = uri.toString();
                                    reference.getRef().child("url_photo_profile").setValue(uri_photo);
                                    reference.getRef().child("nama_lengkap").setValue(nama_lengkap.getText().toString());
                                    reference.getRef().child("bio").setValue(bio.getText().toString());

                                }
                            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                                @Override
                                public void onComplete(@NonNull Task<Uri> task) {
                                    //pindah activity
                                    Intent btncontinue = new Intent(Register_two.this,SuccessRegister.class);
                                    startActivity(btncontinue);
                                }
                            });

                            }
                    }).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                            //pindah activity
                           // Intent btncontinue = new Intent(Register_two.this,SuccessRegister.class);
                           // startActivity(btncontinue);
                        }
                    });
                }


            }
        });

        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent goback = new Intent(Register_two.this,Register_one.class);
                startActivity(goback);
            }
        });

    }

    String getFileExtention(Uri uri){
        ContentResolver contentResolver = getContentResolver();
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
    }

    public void findPhoto(){
        Intent pic = new Intent();
        pic.setType("image/*");
        pic.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(pic, photo_max);

    }

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

            if (requestCode == photo_max && resultCode == RESULT_OK && data != null && data.getData() != null)
            {
                photo_location = data.getData();
                Picasso.with(this).load(photo_location).centerCrop().fit().into(prof_pic);

            }
     }
     public void getUsernameLocal(){
         SharedPreferences sharedPreferences = getSharedPreferences(USERNAME_KEY, MODE_PRIVATE);
         username_key_new = sharedPreferences.getString(username_key,"");
     }
}

the error said, i'm passing null into a child in the line 81 错误说,我在第81行将null传递给一个child

storage = FirebaseStorage.getInstance().getReference().child("Photousers").child(username_key_new);

but i dont know what is wrong 但我不知道怎么了

Have you ever try this? 你有尝试过吗?

And I suggest to make a return string instead making a void method 我建议制作一个返回字符串,而不是制作一个void方法

//Please check what is the identifier of the string in sharedpreferences
//if usernamekey is the identifier then getString("usernamekey","");
public String getUsernameLocal(){
     SharedPreferences sharedPreferences = getSharedPreferences(USERNAME_KEY, MODE_PRIVATE);
     String userKey= sharedPreferences.getString(USERNAME_KEY,"");
     return userKey;
 }

And your reference 和你的参考

storage = FirebaseStorage.getInstance().getReference().child("Photousers").child(getUsernameLocal());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM