首页 > 解决方案 > 我正在尝试创建一个活动,如果文件大小小于 16mb,用户可以在其中选择 pdf 和音频文件并上传到 firebase 存储

问题描述

我创建了一个活动,如果文件大小小于 16mb,用户可以从存储中选择 pdf 和音频文件并上传到 firebase 存储。为了检查文件大小,我创建了一个比较文件大小是否小于 16mb 的方法。此活动应上传文件但每当我选择任何文件时都会出现错误说

错误:java.lang.RuntimeException:传递结果失败 ResultInfo{who=null, request=438, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/35 flg =0x1 }} 到活动 {com.nanb.Alpha/com.nanb.Alpha.personalchat.personalChat}:java.lang.NullPointerException。

我已经搜索了解决方案,发现该文件没有被选中,但没有得到任何解决方案来消除错误。

下面给出了我使用过的代码:

 audio.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checker = "audio";
            Intent audioIntent = new Intent();
            audioIntent.setAction(Intent.ACTION_GET_CONTENT);
            audioIntent.setType("audio/*");
            startActivityForResult(Intent.createChooser(audioIntent,"Select Audio"),438);
        }
    });
    pdf.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checker = "pdf";
            Intent pdfIntent = new Intent();
            pdfIntent.setAction(Intent.ACTION_GET_CONTENT);
            pdfIntent.setType("application/pdf");
            startActivityForResult(Intent.createChooser(pdfIntent,"Select pdf file"),438);
        }
    });

我也试过把

     Intent audioIntent = new Intent(
            Intent.ACTION_PICK,
            android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(Intent.createChooser(audioIntent, "Select Audio"), AUDIO_REQUEST);

仍然得到同样的错误。其余所有代码如下:

    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 438 && resultCode == RESULT_OK && data!=null && data.getData()!=null){
        imagefile = data.getData();
        String filePath = this.getRealPathFromURI(imagefile);
        Long Filelength = this.getfilesize(filePath);
        if(checckfilesize(Filelength).equals("ok")) {
         if (checker.equals("pdf")) {
               pdfFilemessage(filePath);
            }else{
               String fileName = this.getfilename(filePath);
                audiofilemessage(filePath,fileName);
         }
       }
      }


       public Long getfilesize(String filepath){
    File filedata = new File(filepath);
    Long fileLength = filedata.length();
    fileLength = fileLength/1024;
    return fileLength;
}
public String getRealPathFromURI(Uri contentUri) {
    String[] proj = {
            MediaStore.Audio.Media.DATA
    };
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
    cursor.moveToFirst();
    int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
    //        Toast.makeText(personalChat.this, 
   Long.toString(cursor.getLong(sizeIndex)),Toast.LENGTH_SHORT).show();
    return cursor.getString(column_index);
}
public String checckfilesize(Long Filelength){
    String checkstate;
    if(Filelength < 16000 ){
        checkstate = "ok";
    }else{
        checkstate = "file large than 16mb.";
    }
    return checkstate;
}
private String getfilename(String filepath){
    File file = new File(filepath);
    String filename = file.getName();
    return filename;
}

检索临时文件

  private void reciverpdftempImage(Uri imagefile, String msgpushId) {
    int pageNumber = 0;
    PdfiumCore pdfiumCore = new PdfiumCore(this);
    try {

        ParcelFileDescriptor fd = getContentResolver().openFileDescriptor(imagefile, "r");
        PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
        pdfiumCore.openPage(pdfDocument, pageNumber);
        int width = pdfiumCore.getPageWidthPoint(pdfDocument, pageNumber);
        int height = pdfiumCore.getPageHeightPoint(pdfDocument, pageNumber);
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        pdfiumCore.renderPageBitmap(pdfDocument, bmp, pageNumber, 0, 0, width, height);
        saveImage(bmp,msgpushId);
        pdfiumCore.closeDocument(pdfDocument); // important!
    } catch(Exception e) {
        //todo with exception
    }
}

将音频和 pdf 文件上传到 firebase

   private void audiofilemessage(String vfilePath,final String filename) {
    StorageReference imagereference = FirebaseStorage.getInstance().getReference().child("Audio");
    final String msgSenderref = "Chats/" + mAuth.getCurrentUser().getUid() + "/" + userid;
    final String msgReciverref = "Chats/" + userid + "/" + mAuth.getCurrentUser().getUid();
    DatabaseReference usermsgKeyRef = rootref.child("Chats").child(mAuth.getCurrentUser().getUid()).child(userid).push();
    final String msgPushId = usermsgKeyRef.getKey();
    final StorageReference filePath = imagereference.child(msgPushId+"."+"mp3");
    uploadTask = filePath.putFile(Uri.fromFile(new File(vfilePath)));
    String destinationfile = Environment.getExternalStorageDirectory()+"/Alpha/Audio/Send/"+msgPushId+".mp3";
    copyFileOrDirectory(vfilePath,destinationfile);
    uploadTask.continueWithTask(new Continuation() {
        @Override
        public Object then(@NonNull Task task) throws Exception {
            if (!task.isSuccessful()){
                throw task.getException();
            }
            return filePath.getDownloadUrl();
        }
    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
        @Override
        public void onComplete(@NonNull Task<Uri> task) {
            if (task.isSuccessful()) {
                Uri downloadUri = task.getResult();
                String myUrl = downloadUri.toString();
                Toast.makeText(getApplicationContext(),myUrl,Toast.LENGTH_SHORT).show();
               // uploadfiletotheserver(myUrl,filename,checker,msgPushId,msgSenderref,msgReciverref);

            }
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            loadingBar.dismiss();
            Toast.makeText(personalChat.this,e.getMessage(),Toast.LENGTH_SHORT).show();
        }
    });

}

private void pdfFilemessage(String vfilePath) {

    StorageReference imagereference = FirebaseStorage.getInstance().getReference().child("Doc");
    final String msgSenderref = "Chats/" + mAuth.getCurrentUser().getUid() + "/" + userid;
    final String msgReciverref = "Chats/" + userid + "/" + mAuth.getCurrentUser().getUid();
    DatabaseReference usermsgKeyRef = rootref.child("Chats").child(mAuth.getCurrentUser().getUid()).child(userid).push();
    final String msgPushId = usermsgKeyRef.getKey();
    reciverpdftempImage(imagefile,msgPushId);
    final StorageReference filePath = imagereference.child(msgPushId+"."+"pdf");
    uploadTask = filePath.putFile(imagefile);
    String destinationfile = Environment.getExternalStorageDirectory()+"/Alpha/pdf/Send/"+msgPushId+".pdf";
    copyFileOrDirectory(vfilePath,destinationfile);
    uploadTask.continueWithTask(new Continuation() {
        @Override
        public Object then(@NonNull Task task) throws Exception {
            if (!task.isSuccessful()){
                throw task.getException();
            }
            return filePath.getDownloadUrl();
        }
    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
        @Override
        public void onComplete(@NonNull Task<Uri> task) {
            if (task.isSuccessful()) {
                Uri downloadUri = task.getResult();
                String myUrl = downloadUri.toString();
                Toast.makeText(getApplicationContext(),myUrl,Toast.LENGTH_SHORT).show();
                //uploadpdfTempfile(myUrl,imagefile,checker,msgPushId,msgSenderref,msgReciverref);
            }
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            loadingBar.dismiss();
            Toast.makeText(personalChat.this,e.getMessage(),Toast.LENGTH_SHORT).show();
        }
    });

}
private void uploadpdfTempfile(final String myUrl,final Uri imagefile,final String checker, final String msgPushId, final String msgSenderref, final String msgReciverref) {
    StorageReference imagereference = FirebaseStorage.getInstance().getReference().child("Doc").child("temp");
    Uri file = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/Alpha/PDF/temp/"+msgPushId+".png"));
    final StorageReference fileuploadpath = imagereference.child(msgPushId+".png");
    uploadTask = fileuploadpath.putFile(file);
    uploadTask.continueWithTask(new Continuation() {
        @Override
        public Object then(@NonNull Task task) throws Exception {
            if (!task.isSuccessful()){
                throw task.getException();
            }
            return fileuploadpath.getDownloadUrl();
        }
    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
        @Override
        public void onComplete(@NonNull Task<Uri> task) {
            if(task.isSuccessful()){
                Uri downloadUri = task.getResult();
                String  myfileUrl = downloadUri.toString();
                //Toast.makeText(personalChat.this,myfileUrl,Toast.LENGTH_SHORT).show();
                uploadpdfdatatotheserver(myUrl,imagefile,checker,msgPushId,msgSenderref,msgReciverref,myfileUrl);

            }
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(personalChat.this,"Error:"+ e,Toast.LENGTH_SHORT).show();
        }
    });
}
private void uploadpdfdatatotheserver(String myUrl, Uri imagefile, String checker, final String msgPushId, final String msgSenderref, final String msgReciverref,final String myfileurl) {


    Map msgpicbody = new HashMap();
    msgpicbody.put("message",myUrl);
    msgpicbody.put("name",imagefile.getLastPathSegment());
    msgpicbody.put("type",checker);
    msgpicbody.put("ffrom",mAuth.getCurrentUser().getUid());
    msgpicbody.put("to",userid);
    msgpicbody.put("date", savecurrentDate);
    msgpicbody.put("time",savecurrentTime);
    msgpicbody.put("messageId",msgPushId);
    msgpicbody.put("tempfile",myfileurl);

    Map msgBodyDetail = new HashMap();
    msgBodyDetail.put(msgSenderref + "/" +msgPushId,msgpicbody);
    msgBodyDetail.put(msgReciverref + "/" +msgPushId,msgpicbody);

    rootref.updateChildren(msgBodyDetail).addOnCompleteListener(new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
            if (task.isSuccessful()){
                loadingBar.dismiss();
                msginput.setText(null);
                frameLayout.setVisibility(View.GONE);

            }else{
                loadingBar.dismiss();
                msginput.setText(null);
                frameLayout.setVisibility(View.GONE);
                Toast.makeText(personalChat.this,"error",Toast.LENGTH_SHORT).show();
            }

        }
    });
}

日志猫

      java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=438, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/35 flg=0x1 }} to activity {com.nanb.Alpha/com.nanb.Alpha.personalchat.personalChat}: java.lang.NullPointerException
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4090)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4133)
    at android.app.ActivityThread.-wrap20(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1534)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6125)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
 Caused by: java.lang.NullPointerException
    at java.io.File.<init>(File.java:262)
    at com.nanb.Alpha.personalchat.personalChat.getfilesize(personalChat.java:813)
    at com.nanb.Alpha.personalchat.personalChat.onActivityResult(personalChat.java:179)
    at android.app.Activity.dispatchActivityResult(Activity.java:7194)

标签: javaandroidfirebasefirebase-storage

解决方案


推荐阅读