我回去的时候,我的应用程序停了下来

时间:2017-12-19 06:50:35

标签: android nullpointerexception android-mediaplayer

我创建了一个音乐流应用,可以从Firebase中获取数据。但问题是,当我播放歌曲并转到主要活动时,显示应用已停止消息并且应用关闭。当我从列表视图播放歌曲并返回时,应用程序停止。我能做什么请告诉我。 我的代码

public class ViewUploadsActivity extends AppCompatActivity  implements MediaPlayer.OnBufferingUpdateListener,View.OnTouchListener
      ,MediaPlayer.OnCompletionListener{

 //the listview
 ListView listView;
  private SeekBar seekBarProgress;
  private int mediaFileLengthInMilliseconds;
  private final Handler handler = new Handler();
  CustomArrayAdapter adapter;
  //database reference to get uploads data
  DatabaseReference mDatabaseReference;

 //list to store uploads data
  List<Upload> uploadList = new ArrayList<>();
  private TextView mSelectedTrackTitle,selected_track_ar;
  private ImageView mSelectedTrackImage;
  private MediaPlayer mMediaPlayer =new MediaPlayer();
  private ImageView mPlayerControl;

  TextView length;

        @Override
     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_upload);
    listView = (ListView) findViewById(R.id.listView);
    //status = (TextView) findViewById(R.id.status);

    seekBarProgress = (SeekBar)findViewById(R.id.length);

    listView.setStackFromBottom(true);

    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

   mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            togglePlayPause();
        }
    });

     mSelectedTrackTitle(TextView)findViewById(R.id.selected_track_title);
    mSelectedTrackImage = 
           (ImageView)findViewById(R.id.selected_track_image);
    mPlayerControl = (ImageView)findViewById(R.id.player_control);
    selected_track_ar=(TextView)findViewById(R.id.selected_track_ar);
        mPlayerControl.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            togglePlayPause();
        }
          });
          get();
            //getting the database reference
            mDatabaseReference = FirebaseDatabase.getInstance().
              getReference(Constants.DATABASE_PATH_UPLOADS);

    //retrieving upload data from firebase database
         mDatabaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                Upload upload = postSnapshot.getValue(Upload.class);
                uploadList.add(upload);
            }

               adapter = new CustomArrayAdapter(getApplicationContext(), 
                      (ArrayList<Upload>) uploadList);
            listView.setAdapter(adapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
       });

       }
       @Override
       protected void onDestroy() {
            super.onDestroy();
  if (mMediaPlayer != null) {
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
    }
   private void togglePlayPause() {
    if (mMediaPlayer.isPlaying()) {
        mMediaPlayer.pause();
        mPlayerControl.setImageResource(R.drawable.ic_play);
    } else if(!mMediaPlayer.isPlaying()){
        mMediaPlayer.start();
        mPlayerControl.setImageResource(R.drawable.ic_pause);
        mediaFileLengthInMilliseconds = mMediaPlayer.getDuration();
        primarySeekBarProgressUpdater();
        mSelectedTrackImage.setImageResource(R.drawable.images);
    }
     }
    public void get()
     {
    seekBarProgress.setMax(99); // It means 100% .0-99
    seekBarProgress.setOnTouchListener(this);
    mMediaPlayer.setOnBufferingUpdateListener(this);
    mMediaPlayer.setOnCompletionListener(this);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int 
          i, long l) {
            //getting the upload
            Upload upload = uploadList.get(i);
            mSelectedTrackTitle.setText(upload.getName());
            selected_track_ar.setText(upload.getAr());
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
                mMediaPlayer.reset();
                seekBarProgress.setProgress(0);
            }

            try {
                mMediaPlayer.setDataSource(upload.getUrl());
               mMediaPlayer.prepare();

            } catch (IOException e) {
                e.printStackTrace();
            }
                        }
        });



     }
      private void primarySeekBarProgressUpdater() {
    seekBarProgress.setProgress((int
     (((float)mMediaPlayer.getCurrentPosition()
      /mediaFileLengthInMilliseconds)*100)); 
      // This math construction give a percentage of "was playing"/"song 
    length"
    if (mMediaPlayer.isPlaying()) {
        Runnable notification = new Runnable() {
            public void run() {
                primarySeekBarProgressUpdater();
            }
        };
        handler.postDelayed(notification,1000);
    }
     }

     @Override
     public boolean onTouch(View v, MotionEvent event) {
    if(v.getId() == R.id.length){
        /** Seekbar onTouch event handler. Method which seeks MediaPlayer to 
     seekBar primary progress position*/
       if(mMediaPlayer.isPlaying()){
            SeekBar sb = (SeekBar)v;
            int playPositionInMillisecconds = (mediaFileLengthInMilliseconds 
        / 100) * sb.getProgress();
           mMediaPlayer.seekTo(playPositionInMillisecconds);
        }
      }
      return false;
   }

   @Override
   public void onBufferingUpdate(MediaPlayer mp, int percent) {

    seekBarProgress.setSecondaryProgress(percent);
  }

    @Override
  public void onCompletion(MediaPlayer mp) {
    mPlayerControl.setImageResource(R.drawable.ic_play);
   }

}

Logcat

    Unrecognized GLES max version string in extensions: 
    ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 
        12-19 12:28:13.753 1377-3347/? E/OMXNodeInstance: 
            setConfig(5610023:google.mp3.decoder, 
      ConfigPriority(0x6f800002)) ERROR: Undefined(0x80001001)
            12-19 12:28:31.338 5777-5777/com.example.admin.firebsaseuploadd 
       E/AndroidRuntime: FATAL EXCEPTION: main

        Process: com.example.admin.firebsaseuploadd, PID: 5777

     java.lang.NullPointerException: Attempt to invoke virtual method 'int 
      android.media.MediaPlayer.getCurrentPosition()' on a null object 
       reference

    at 

          com.example.admin.firebsaseuploadd.ViewUploadsActivity.
         primarySeekBarProgressUp                         
         dater(ViewUploadsActivity.java:245)

       at 
              com.example.admin.firebsaseuploadd.ViewUploadsActivity.
             access$500(ViewUploadsActivity.java:62)

        at com.example.admin.firebsaseuploadd.ViewUploadsActivity$5.
       run(ViewUploadsActivity.java:249)

            at android.os.Handler.handleCallback(Handler.java:751)

            at android.os.Handler.dispatchMessage(Handler.java:95)

             at android.os.Looper.loop(Looper.java:154)

            at android.app.ActivityThread.main(ActivityThread.java:6119)

             at java.lang.reflect.Method.invoke(Native Method)

               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.
         run(ZygoteInit.java:886)

  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
 12-19 12:28:31.974 1311-1311/? E/EGL_emulation: tid 1311: egl 
 CreateSyncKHR(1881): error 0x3004 (EGL_BAD_ATTRIBUTE)
     12-19 12:28:32.533 1372-3348/? E/AudioFlinger: not enough memory for 
   AudioTrack size=131296
      12-19 12:28:32.533 1372-3348/? E/AudioFlinger: createRecordTrack_l() 
   initCheck failed -12; no control block?
      12-19 12:28:32.534 2522-
    5797/com.google.android.googlequicksearchbox:search E/AudioRecord: 
        AudioFlinger could not create record track, status: -12
   12-19 12:28:32.564 2522-
     5797/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: 
  Error creating AudioRecord instance: initialization check failed with 
    status -12.
  12-19 12:28:32.564 2522-
    5797/com.google.android.googlequicksearchbox:search 
     E/android.media.AudioRecord: Error code -20 when initializing native 
    AudioRecord object.
   12-19 12:28:32.595 2522-
     5797/com.google.android.googlequicksearchbox:search E/ActivityThread: 
   Failed to find provider info for 
     com.google.android.apps.gsa.testing.ui.audio.recorded
    12-19 12:28:37.712 1372-1794/? E/AudioFlinger: not enough memory for 
 AudioTrack size=131296
     12-19 12:28:37.714 1372-1794/? E/AudioFlinger: createRecordTrack_l() 
   initCheck failed -12; no control block?
    12-19 12:28:37.715 2522-
 5797/com.google.android.googlequicksearchbox:search E/AudioRecord: 
   AudioFlinger could not create record track, status: -12
       12-19 12:28:37.728 2522-
      5797/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: 
         Error creating AudioRecord instance: initialization check failed 
        with status -12.
     12-19 12:28:37.728 2522-                                    
    5797/com.google.android.googlequicksearchbox:search 
    E/android.media.AudioRecord: Error code -20 when initializing native 
    AudioRecord object.

    12-19 12:28:37.729 2522-
    5797/com.google.android.googlequicksearchbox:search E/ActivityThread: 
  Failed to find provider info for                                                                   
     com.google.android.apps.gsa.testing.ui.audio.recorded
  12-19 12:28:42.882 1372-1443/? E/AudioFlinger: not enough memory for                                     
  AudioTrack size=131296

  12-19 12:28:42.883 1372-1443/? E/AudioFlinger: createRecordTrack_l() 
  initCheck failed -12; no control block?

  12-19 12:28:42.883 2522-
  5797/com.google.android.googlequicksearchbox:search E/AudioRecord: 
  AudioFlinger could not create record track, status: -12

  12-19 12:28:42.916 2522-
  5797/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: 
  Error creating AudioRecord instance: initialization check failed with 
  status -12.

  12-19 12:28:42.917 2522-
  5797/com.google.android.googlequicksearchbox:search 
  E/android.media.AudioRecord: Error code -20 when initializing native 
  AudioRecord object.

  12-19 12:28:42.929 2522-
  5797/com.google.android.googlequicksearchbox:search E/ActivityThread: 
  Failed to find provider info for 
  com.google.android.apps.gsa.testing.ui.audio.recorded

  12-19 12:28:48.085 1372-1793/? E/AudioFlinger: not enough memory for 
  AudioTrack size=131296

  12-19 12:28:48.136 1372-1793/? E/AudioFlinger: createRecordTrack_l() 
  initCheck failed -12; no control block?

  12-19 12:28:48.151 2522-
  5797/com.google.android.googlequicksearchbox:search E/AudioRecord: 
  AudioFlinger could not create record track, status: -12

  12-19 12:28:48.248 2522-
  5797/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: 
  Error creating AudioRecord instance: initialization check failed with 
  status -12.

  12-19 12:28:48.249 2522-
  5797/com.google.android.googlequicksearchbox:search 
  E/android.media.AudioRecord: Error code -20 when initializing native 
  AudioRecord object.

  12-19 12:28:48.251 2522-
  5797/com.google.android.googlequicksearchbox:search E/ActivityThread: 
  Failed to find provider info for 
  com.google.android.apps.gsa.testing.ui.audio.recorded

  12-19 12:28:53.439 1372-1793/? E/AudioFlinger: not enough memory for 
  AudioTrack size=131296

  12-19 12:28:53.439 1372-1793/? E/AudioFlinger: createRecordTrack_l() 
  initCheck failed -12; no control block?

  12-19 12:28:53.443 2522-
  5797/com.google.android.googlequicksearchbox:search E/AudioRecord: 
  AudioFlinger could not create record track, status: -12

  12-19 12:28:53.455 2522-
  5797/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: 
  Error creating AudioRecord instance: initialization check failed with 
  status -12.

  12-19 12:28:53.456 2522-
  5797/com.google.android.googlequicksearchbox:search 
  E/android.media.AudioRecord: Error code -20 when initializing native 
  AudioRecord object.

  12-19 12:28:53.457 2522-
  5797/com.google.android.googlequicksearchbox:search E/ActivityThread: 
  Failed to find provider info for 
  com.google.android.apps.gsa.testing.ui.audio.recorded

  12-19 12:28:58.551 1372-1793/? E/AudioFlinger: not enough memory for 
  AudioTrack size=131296

  12-19 12:28:58.552 1372-1793/? E/AudioFlinger: createRecordTrack_l() 
  initCheck failed -12; no control block?

  12-19 12:28:58.552 2522-
  5797/com.google.android.googlequicksearchbox:search E/AudioRecord: 
  AudioFlinger could not create record track, status: -12

  12-19 12:28:58.573 2522-
  5797/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: 
  Error creating AudioRecord instance: initialization check failed with 
  status -12.

  12-19 12:28:58.574 2522-
  5797/com.google.android.googlequicksearchbox:search 
  E/android.media.AudioRecord: Error code -20 when initializing native 
  AudioRecord 
  object.

  12-19 12:28:58.577 2522-
  5797/com.google.android.googlequicksearchbox:search E/ActivityThread: 
  Failed to find provider info for 
  com.google.android.apps.gsa.testing.ui.audio.recorded

  12-19 12:29:03.652 1372-1794/? E/AudioFlinger: not enough memory for 
  AudioTrack size=131296

  12-19 12:29:03.652 1372-1794/? E/AudioFlinger: createRecordTrack_l() 
  initCheck failed -12; no control block?
  12-19 12:29:03.652 2522-                                          
      5797/com.google.android.googlequicksearchbox:search E/AudioRecord:  
        AudioFlinger             could not create record track, status:-12

  12-19 12:29:03.678 2522-
  5797/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: 
  Error creating AudioRecord instance: initialization check failed with 
  status -12.

  12-19 12:29:03.678 2522-
  5797/com.google.android.googlequicksearchbox:search 
  E/android.media.AudioRecord: Error code -20 when initializing native 
  AudioRecord object.

  12-19 12:29:03.679 2522-
  5797/com.google.android.googlequicksearchbox:search E/ActivityThread: 
  Failed to find provider info for 
  com.google.android.apps.gsa.testing.ui.audio.recorded
 12-19 12:29:08.775 1372-1443/? E/AudioFlinger: not enough memory for 
  AudioTrack 
 size=131296
12-19 12:29:08.775 1372-1443/? E/AudioFlinger: createRecordTrack_l() 
     initCheck 
      failed -12; no control block?
  12-19 12:29:08.778 2522-5 
  797/com.google.android.googlequicksearchbox:search 
 E/AudioRecord: AudioFlinger could not create record track, status: -12
 12-19 12:29:08.804 2522-5797/com.google.android.googlequicksearchbox:search 

  E/AudioRecord-JNI: Error creating AudioRecord instance: initialization 
  check failed with status -12.
   12-19 12:29:08.805 2522-
         5797/com.google.android.googlequicksearchbox:search 
    E/android.media.AudioRecord: Error code -20 when initializing native 
  AudioRecord object.
   12-19 12:29:08.809 2522-
 5797/com.google.android.googlequicksearchbox:search 

   E/ActivityThread: Failed to find provider info for 
  com.google.android.apps.gsa.testing.ui.audio.record ed

1 个答案:

答案 0 :(得分:0)

当我读到您的logcat时,您的问题是NullPointerException在&#39; int android.media.MediaPlayer.getCurrentPosition()&#39;。当您返回MainActivity时,将调用ViewUploadsActivity#onDestroy()。此方法会清除您的mMediaPlayer并将其设置为null。但是,您有一个通知处理程序,它总是随时间运行。最后一次运行,此跑步者致电iewUploadsActivity#primarySeekBarProgressUpdater()并致电seekBarProgress.setProgress((int (((float)mMediaPlayer.getCurrentPosition()))

解决方案:

  1. 在致电mMediaPlayer.getCurrentPosition()

    之前检查空
    if (mMediaPlayer != null) {
        int position = mMediaPlayer.getCurrentPosition();
        seekBarProgress.setProgress(position);
    }
    
  2. onDestroy()

  3. 停止处理程序