【问题标题】:Trying to upload song to firebase and to app fails with exception尝试将歌曲上传到 Firebase 和应用程序失败,但有异常
【发布时间】:2021-08-13 07:07:26
【问题描述】:

我正在尝试制作一个音乐应用程序,每当我尝试向其上传歌曲时应用程序崩溃,错误是:

2021-05-25 04:51:02.446 24439-24439/com.example.msctry E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.msctry, PID: 24439
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=101, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/msf:7900 flg=0x1 }} to activity {com.example.msctry/com.example.msctry.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5097)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5138)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2147)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:7814)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
     Caused by: java.lang.NullPointerException: Attempt to get length of null array
        at com.example.msctry.MainActivity.onActivityResult(MainActivity.java:112)
        at android.app.Activity.dispatchActivityResult(Activity.java:8292)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5090)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5138) 
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2147) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:237) 
        at android.app.ActivityThread.main(ActivityThread.java:7814) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)

起初我以为我只是没有提供内部存储权限,所以我做了,但它仍然发生,这是我的清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.msctry">
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:requestLegacyExternalStorage="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MscTry">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是主要的活动文件:

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    TextView TextimageView;
    ProgressBar progressBar;
    Uri audiouri;
    StorageReference mstorage;
    StorageTask mUploadTask;
    DatabaseReference reference;
    String songsCategory;
    MediaMetadataRetriever mediaMetadataRetriever;
    byte[] art;
    String title1,artist1,album_art1="",duration1;
    TextView title,artist,durations,album,dataa;
    ImageView album_art;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextimageView=findViewById(R.id.tvuploadsongfileselected);
        progressBar=findViewById(R.id.progressbar);
        title=findViewById(R.id.title);
        artist=findViewById(R.id.artist);
        durations=findViewById(R.id.duration);
        album=findViewById(R.id.album);
        dataa=findViewById(R.id.data);
        album_art=findViewById(R.id.img);
        mediaMetadataRetriever=new MediaMetadataRetriever();
        reference= FirebaseDatabase.getInstance().getReference().child("songs");
        mstorage= FirebaseStorage.getInstance().getReference().child("songs");
        Spinner spinner=findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(this);
        List<String> categories=new ArrayList<>();
        categories.add("Jogging Songs");
        categories.add("Swimming Exercise Songs");
        categories.add("Aerobic Songs");
        categories.add("Walking Songs");
        categories.add("Biking Songs");
        categories.add("Physical Therapy Songs");
        ArrayAdapter<String> dataAdapter=new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,categories);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);

    }


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        songsCategory=parent.getItemAtPosition(position).toString();
        Toast.makeText(this, "Selected"+songsCategory, Toast.LENGTH_SHORT).show();


    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
    public  void openAudioFiles(View v){
        Intent i=new Intent(Intent.ACTION_GET_CONTENT);
        i.setType("audio/*");
        startActivityForResult(i,101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==101&& resultCode==RESULT_OK && data.getData()!=null){
            audiouri=data.getData();
            String fileNames=getFileName(audiouri);
            TextimageView.setText(fileNames);
            mediaMetadataRetriever.setDataSource(this,audiouri);
            art=mediaMetadataRetriever.getEmbeddedPicture();
            Bitmap bitmap= BitmapFactory.decodeByteArray(art,0,art.length);
            album_art.setImageBitmap(bitmap);
            album.setText(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
            artist.setText(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
            dataa.setText(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE));
            durations.setText(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
            title.setText(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE));
            artist1=mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
            title1=mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
            duration1=mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);


        }
    }
    private  String getFileName(Uri uri){
        String result=null;
        if(uri.getScheme().equals("content")){
            Cursor cursor=getContentResolver().query(uri,null,null,null,null);
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));

                }
            }finally {
                cursor.close();
            }
        }
        if(result==null){
            result=uri.getPath();
            int cut=result.lastIndexOf('/');
            if(cut!=-1){
                result=result.substring(cut+1);
            }
        }
        return  result;
    }
    public  void uploadFileToFirebase(View v){
        if(TextimageView.equals("No file Selected")){
            Toast.makeText(this, "please select an image!", Toast.LENGTH_SHORT).show();

        }else{
            if(mUploadTask!=null&& mUploadTask.isInProgress()){
                Toast.makeText(this, "song upload is in progress !", Toast.LENGTH_SHORT).show();

            }else{
                uploadFiles();
            }
        }
    }

    private void uploadFiles() {
        if(audiouri!=null) {
            Toast.makeText(this, "Song Is Uploading Please Wait", Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.VISIBLE);
            final StorageReference storageReference = mstorage.child(System.currentTimeMillis() + "." + getfileextension(audiouri));
            mUploadTask = storageReference.putFile(audiouri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            UploadSong uploadSong = new UploadSong(songsCategory, title1, artist1, album_art1, duration1, uri.toString());
                            String uploadId = reference.push().getKey();
                            reference.child(uploadId).setValue(uploadSong);


                        }
                    });

                }
            }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
                    double progress = (100.0 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
                    progressBar.setProgress((int) progress);

                }
            });
        }else{
            Toast.makeText(this, "No file Selected to Upload", Toast.LENGTH_SHORT).show();


        }




    }
    private  String getfileextension(Uri audiouri){
        ContentResolver contentResolver=getContentResolver();
        MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(audiouri));

    }
}

错误发生在以下行:

Bitmap bitmap= BitmapFactory.decodeByteArray(art,0,art.length);

由于某种原因,他们无法获得我要上传的歌曲的长度,我不明白为什么,我尝试在另一部手机上运行该应用程序,当我从某个音乐播放器中选择歌曲时应用程序崩溃了,当我从音频中崩溃时它没有崩溃,但它在我的实际手机中根本不起作用

【问题讨论】:

  • 也许该歌曲文件没有嵌入图片?
  • 确保在art不为空时调用length,否则你会得到NPE。
  • @AlexMamo 怎么样?
  • @lyncx 我不确定这是从 youtube 到 mp3 转换器的文件
  • 检查无效。

标签: android arrays firebase error-handling


【解决方案1】:

你已经很接近了,但这应该可以工作

art=mediaMetadataRetriever.getEmbeddedPicture();
if(art != null){
Bitmap bitmap= BitmapFactory.decodeByteArray(art,0,art.length);
album_art.setImageBitmap(bitmap);
}

您只需要检查 art 是否为空,因为某些歌曲可能没有专辑封面。

附:这应该可以保存它,当您检索数据时,您还必须检查它是否为空

【讨论】:

    猜你喜欢
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多