android - 上传图片时 Firebase 应用程序崩溃

标签 android firebase android-recyclerview firebase-storage

我的应用需要将图像上传到 firebase 存储并将其显示在 recyclerView 中。我的前两张图片在列表中显示得很好。但是,当我尝试上传第三张图片时,应用程序崩溃了,也无法将图片存储在 firebase 上。每个图像大小从 500KB 到 700KB 不等。我还在我的 list 中使用了 android:largeHeap="true"。怎么办?

//代码如下:

public class PostActivity extends Activity {


private EditText postTitle;
private EditText postDescription;
private Button submitButton;
private Uri imageUri=null;
private StorageReference storage;
private ProgressDialog progressDialogue;
private DatabaseReference database;
public  String titleVal;
public String descriptionVal;
private ImageView mImageView;
private static final int GALLERY_REQUEST=1;


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

    storage= FirebaseStorage.getInstance().getReference();
    database= FirebaseDatabase.getInstance().getReference().child("Posts");





    mImageView=(ImageView) findViewById(R.id.imageView);

    postTitle=(EditText) findViewById(R.id.titleField);
    postDescription=(EditText)findViewById(R.id.descriptionField);
    submitButton=(Button) findViewById(R.id.submitPost);
    progressDialogue=new ProgressDialog(this);


    imageUri = Uri.parse(getIntent().getStringExtra("imageUri"));
    ImageView img = (ImageView) findViewById(R.id.imageView);
    img.setImageURI(imageUri);

//帖子提交后会发生什么。

    submitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startPosting();

        }
    });
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("titleVal", titleVal);
    outState.putString("descriptionVal",descriptionVal );

}


private void startPosting() {


    titleVal=postTitle.getText().toString().trim();
    descriptionVal=postDescription.getText().toString().trim();



    if(!TextUtils.isEmpty(titleVal) && !TextUtils.isEmpty(descriptionVal) && imageUri!=null){
        progressDialogue.setMessage("আপলোড হচ্ছে......");
        progressDialogue.show();

        StorageReference filePath=storage.child("post_images").child(imageUri.getLastPathSegment());
        filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Uri downloadUrl=taskSnapshot.getDownloadUrl();
                Picasso.with(PostActivity.this).load(downloadUrl).into(mImageView);
                DatabaseReference newPost=database.push();
                newPost.child("title").setValue(titleVal);
                newPost.child("description").setValue(descriptionVal);
                newPost.child("image").setValue(downloadUrl.toString());





                progressDialogue.dismiss();
                Toast.makeText(getApplicationContext(), "Successfully Uploaded", Toast.LENGTH_LONG).show();

                startActivity(new Intent(PostActivity.this,HomeActivity.class));
            }
        });

    }else{
        Toast.makeText(getApplicationContext(), "Please provide a Title", Toast.LENGTH_LONG).show();
    }


    }

}

最佳答案

试试下面的代码,我正在使用这段代码将图像上传到 firebase 存储,如果您发现任何问题或有任何疑问,请告诉我

Uploading image to firebase storage After uploading image to firebase storage

见下图,可以看到图片已经上传成功 Firebase storage image

1 - 在您的 Java 文件中,放入这些代码

private SimpleDraweeView imgProfile;
private FirebaseStorage storage;
private Uri file, resultUri;
private StorageMetadata metadata;
private UploadTask uploadTask;
private StorageReference storageRef;
private final String MY_BUCKET_PATH = "YOUR BUCKET PATH OF YOUR STORAGE";

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

    storage = FirebaseStorage.getInstance();
    storageRef = storage.getReferenceFromUrl(MY_BUCKET_PATH);
}

2 - 在 onActivityResult 中获取图片的 Uri 后,将图片上传到 firebase 存储,还要确保获取正确的图片 Uri

private void UploadImage() {

    file = Uri.fromFile(new File(resultUri.getPath()));

    // Create the file metadata
    metadata = new StorageMetadata.Builder().setContentType("image/jpg").build();

    // Upload file and metadata to the path 'images/mountains.jpg'
    uploadTask = storageRef.child("images/" + file.getLastPathSegment()).putFile(file, metadata);

    // Listen for state changes, errors, and completion of the upload.
    uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
            showUploadProgress(progress);
            System.out.println("Upload is " + progress + "% done");
        }
    }).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
            System.out.println("Upload is paused");
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle unsuccessful uploads
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            Log.e("Uploading image==", "onSuccess");
            // Handle successful uploads on complete
            Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
            imgProfile.setImageURI(Uri.parse(downloadUrl.toString())); // Here image will be reflected after uploading
            mDialog.dismiss();
            Log.e("DownloadUrl getPath==>>", taskSnapshot.getDownloadUrl().getPath());
            Log.e("Metadata getPath==>>", taskSnapshot.getMetadata().getPath());  // this line will give you path to download Image from Firebase storage omitting child storage reference
            Log.e("Metadata dwndUrl getpath", taskSnapshot.getMetadata().getDownloadUrl().getPath());
            Log.e("storageRef path==>>", taskSnapshot.getMetadata().getReference().getPath());
            mSessionManager.storeStringValues("profile_photo", downloadUrl.toString());
            mSessionManager.storeStringValues("profile_photo_path", taskSnapshot.getMetadata().getPath());
        }
    });
}

关于android - 上传图片时 Firebase 应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41180183/

相关文章:

java - Android Studio停止声音

java - onClick Sign Up 方法包含 onClick Datepicker,如何使其工作?

android - 获取RecyclerView中选定的TextView值

java - 如何在recyclerview中创建和填充公共(public)字段?

android - 如何在android中挂载USB路径?

android - 如何增加Android Kitkat的ADB录屏时限

java - 具有自定义布局的 fragment 内的 Google map

javascript - Firebase Push() 方法随机播放列表数据

Firebase 身份验证限制同一用户登录

java - 是否有任何库可以让我们在 recyclerview 中获得选框效果(例如 hotstar vip 页面滚动图像)?