setDataSource(String path)抛出空指针异常

时间:2016-01-14 20:09:37

标签: android

我正在学习Android几天。在开发一个简单的音乐播放器时,我在使用setDataSource(String fileName)方法时遇到了这个异常

MainActivity.java

package com.bihan.zombieplayer;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import android.app.Activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener, OnSeekBarChangeListener{

ImageButton list, play,next, prev, fast, rev;
TextView sn, ct, dt;
MediaPlayer mp;
SeekBar sb;
private Handler myHandler = new Handler();
SharedPreferences sp;
protected int startTime, finalTime;
String songName, songLoc;
Boolean songSet = false;
ImageView ab;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initialize_components();
    initialize_mediaPlayer();

}
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    int id = v.getId();

    if(id == R.id.bt_play){

        if(songSet == true)
        {
            if(mp.isPlaying()){
                play.setImageResource(R.drawable.bt_pause);
                mp.pause();
            }
        else{

                startTime = mp.getCurrentPosition();
                setTime(startTime,ct);
                setTime(finalTime,dt);
                sb.setProgress(startTime);
                myHandler.postDelayed(UpdateSongTime, 100);

            }
    }
        else 
            Toast.makeText(this, "Select a song", Toast.LENGTH_LONG).show();

    }

    else if(id == R.id.bt_back){

        int curTime = mp.getCurrentPosition();
        mp.seekTo(curTime+PlayerDetails.TIME_TO_SEEK);
    }
    else if(id == R.id.bt_next){

    }
    else if(id == R.id.bt_prev){

    }
    else if(id == R.id.bt_fwd){
        int curTime = mp.getCurrentPosition();
        mp.seekTo(curTime-PlayerDetails.TIME_TO_SEEK);
    }
    else if(id == R.id.bt_list){
        Intent i = new Intent(this,PlayList.class);
        startActivityForResult(i, PlayerDetails.REQUEST_CODE);
    }

}

private void initialize_components()
{
    /***
     * This Funtion initializes the components on the activity
     */
    list = (ImageButton)findViewById(R.id.bt_list);
    play = (ImageButton)findViewById(R.id.bt_play);
    next = (ImageButton)findViewById(R.id.bt_next);
    prev = (ImageButton)findViewById(R.id.bt_prev);
    fast = (ImageButton)findViewById(R.id.bt_fwd);
    rev = (ImageButton)findViewById(R.id.bt_back);
    sn = (TextView)findViewById(R.id.song_name);
    ct = (TextView)findViewById(R.id.cur_time);
    dt = (TextView)findViewById(R.id.dur_time);
    sb = (SeekBar)findViewById(R.id.mp_seekbar);
    ab = (ImageView)findViewById(R.id.album_image);
    list.setOnClickListener(this);
    play.setOnClickListener(this);
    next.setOnClickListener(this);
    prev.setOnClickListener(this);
    fast.setOnClickListener(this);
    rev.setOnClickListener(this);
    sb.setOnSeekBarChangeListener(this);
}

private void initialize_mediaPlayer()
{
    /***
     * This method initializes the mediaplayer
     * If no media is selected it shows the prefered media (last played music)
     */

        //use sharedPreference
        sp = getSharedPreferences("musicplayer", MODE_PRIVATE);
        songName = sp.getString("songName","No Song Selected");
        songLoc = sp.getString("songLoc","");
        songSet = sp.getBoolean("songPlay", false);
        if(songSet == false)
        {
            sn.setText(songName);
            setTime(0,dt);
            setTime(0,ct);
        }

        else
        {
            try{
                mp.setDataSource(songLoc);
                mp.prepare();
            }
            catch(Exception e){
                Toast.makeText(this, "Some Error Occured", Toast.LENGTH_LONG).show();
            }
            finalTime = mp.getDuration();
            setTime(mp.getDuration(),dt);
            sb.setMax(mp.getDuration());

        }


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == PlayerDetails.REQUEST_CODE)
    {
        if(resultCode == PlayerDetails.RESULT_PLAY)
        {
            Bundle b = data.getExtras();
            songName = b.getString("songName");
            songLoc = b.getString("songLoc");

            try{
                Log.v("Before Data Set", songLoc);
                mp.setDataSource(songLoc);
                mp.prepare();
                Log.v("TRY", " After Data Set");
            }catch(Exception e){
                Toast.makeText(this, "Some Error Occured", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
            /*
            finalTime = mp.getDuration();
            setTime(finalTime,dt);
            sb.setMax(mp.getDuration());
            */
        }
    }
}


 private Runnable UpdateSongTime = new Runnable() {
      public void run() {
         startTime = mp.getCurrentPosition();
         setTime(startTime,ct);
         sb.setProgress((int)startTime);
         myHandler.postDelayed(this, 100);
      }
   };


private void setTime(int millis, TextView tv){
    /**
     * This method shows the time in time format
     */
    tv.setText(String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
            TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1))
            );
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    // TODO Auto-generated method stub
    if(fromUser){
        sb.setProgress(progress);
        mp.seekTo(progress);
    }
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    mp.pause();

}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    mp.start();
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    Editor e = sp.edit();
    if(songSet == true){
        e.putString("songName", songName);
        e.putString("songLoc",  songLoc);
        e.putBoolean("songPlay", true);
    }else{
        e.remove("songName");
        e.remove("songLoc");
        e.remove("songPlay");
    }
    e.commit();
    super.onDestroy();
}

}

PlayList.java

package com.bihan.zombieplayer;


import java.util.ArrayList;
import java.util.List;


import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;

import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;

import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class PlayList extends ListActivity{

public List<String> songName = new ArrayList<String>();
public List<String> songLoc = new ArrayList<String>();

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

    updateList();

    ArrayAdapter<String> a = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,songName);

    setListAdapter(a);
}


public void updateList(){
    if(isExternalStorageReadable())
    {
        ContentResolver cr = getContentResolver();
        //Cursor c = cr.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, null, null, null,null);
        Cursor c = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        while(c.moveToNext()){
            String name = c.getString(c.getColumnIndex(MediaStore.Audio.Media.TITLE));
            songName.add(name);
            String path = c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA));
            songLoc.add(path);
        }
    }
}


public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);

    String name = songName.get(position);
    String path = songLoc.get(position);
    Intent i = new Intent();
    i.putExtra("songName", name);
    i.putExtra("songLoc", path);
    setResult(PlayerDetails.RESULT_PLAY,i);
    finish();
}

}

和播放歌曲时的日志文件

01-15 01:26:23.662: V/Before Data Set(2883):    /storage/emulated/0/media/audio/notifications/facebook_ringtone_pop.m4a
01-15 01:26:23.667: W/System.err(2883): java.lang.NullPointerException: Attempt to  invoke virtual method 'void android.media.MediaPlayer.setDataSource (java.lang.String)' on a null object reference
01-15 01:26:23.668: W/System.err(2883):     at  com.bihan.zombieplayer.MainActivity.onActivityResult(MainActivity.java:179)
01-15 01:26:23.668: W/System.err(2883):     at  android.app.Activity.dispatchActivityResult(Activity.java:6442)
01-15 01:26:23.668: W/System.err(2883):     at  android.app.ActivityThread.deliverResults(ActivityThread.java:3716)
01-15 01:26:23.668: W/System.err(2883):     at  android.app.ActivityThread.handleSendResult(ActivityThread.java:3763)
01-15 01:26:23.668: W/System.err(2883):     at android.app.ActivityThread.- wrap16(ActivityThread.java)
01-15 01:26:23.668: W/System.err(2883):     at android.app.ActivityThread   $H.handleMessage(ActivityThread.java:1403)
01-15 01:26:23.668: W/System.err(2883):     at  android.os.Handler.dispatchMessage(Handler.java:102)
01-15 01:26:23.668: W/System.err(2883):     at android.os.Looper.loop   (Looper.java:148)
01-15 01:26:23.668: W/System.err(2883):     at android.app.ActivityThread.main  (ActivityThread.java:5443)
01-15 01:26:23.668: W/System.err(2883):     at java.lang.reflect.Method.invoke  (Native Method)
01-15 01:26:23.668: W/System.err(2883):     at  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
01-15 01:26:23.668: W/System.err(2883):     at  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
01-15 01:26:23.749: V/RenderScript(2883): 0xb887cc40 Launching thread(s), CPUs 4
01-15 01:26:27.173: E/Surface(2883): getSlotFromBufferLocked: unknown buffer:   0xb86bb240

我搜索了许多答案,但没有一个有效。

这是清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bihan.zombieplayer"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="16" />
<uses-permission 
    android:name = "android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission 
    android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".PlayList"
        android:label="@string/title_activity_play_list" >
    </activity>
</application>

</manifest>

1 个答案:

答案 0 :(得分:0)

mpnull,因为您从未为其指定过值。