Я создал упражнение, в котором пользователь может выбрать pdf и аудиофайл из хранилища и загрузить их в хранилище firebase, если размер файла меньше 16 МБ. Чтобы проверить размер файла, я создал метод, в котором сравнивается размер файла, если размер файла меньше 16 МБ. это действие должно загрузить файл, но всякий раз, когда я выбираю какой-либо файл, возникает ошибка:
error: java .lang.RuntimeException: ошибка доставки результата ResultInfo {who = null, request = 438, result = -1, данные = намерение {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-файл в базу данных
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();
}
}
});
}
logcat
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)