音乐播放器中的NullPointerException

时间:2014-09-08 07:05:21

标签: android

我试图从教程@AndroidHive.com建立一个音乐播放器。代码没有错误但是当我在移动设备上运行这个应用程序时会出现这样的错误:

[.814: I/ActivityManager(1019): Start proc com.examplesample for activity com.examplesample/.MainActivity: pid=31113 uid=10119 gids={50119}
09-08 12:12:39.821: D/dalvikvm(31113): Late-enabling CheckJNI
09-08 12:12:39.963: D/dalvikvm(31113): GC_FOR_ALLOC freed 79K, 2% free 9431K/9552K, paused 12ms, total 12ms
09-08 12:12:39.973: D/AndroidRuntime(31113): Shutting down VM
09-08 12:12:39.973: W/dalvikvm(31113): threadid=1: thread exiting with uncaught exception (group=0x415b4ba8)
09-08 12:12:39.974: E/AndroidRuntime(31113): FATAL EXCEPTION: main
09-08 12:12:39.974: E/AndroidRuntime(31113): Process: com.examplesample, PID: 31113
09-08 12:12:39.974: E/AndroidRuntime(31113): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.examplesample/com.examplesample.MainActivity}: java.lang.NullPointerException
09-08 12:12:39.974: E/AndroidRuntime(31113):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at android.os.Handler.dispatchMessage(Handler.java:102)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at android.os.Looper.loop(Looper.java:136)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at android.app.ActivityThread.main(ActivityThread.java:5001)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at java.lang.reflect.Method.invokeNative(Native Method)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at java.lang.reflect.Method.invoke(Method.java:515)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at dalvik.system.NativeStart.main(Native Method)
09-08 12:12:39.974: E/AndroidRuntime(31113): Caused by: java.lang.NullPointerException
09-08 12:12:39.974: E/AndroidRuntime(31113):    at com.examplesample.SongsManager.getPlayList(SongsManager.java:21)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at com.examplesample.MainActivity.onCreate(MainActivity.java:77)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at android.app.Activity.performCreate(Activity.java:5231)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-08 12:12:39.974: E/AndroidRuntime(31113):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
09-08 12:12:39.974: E/AndroidRuntime(31113):    ... 11 more
09-08 12:12:39.977: W/ActivityManager(1019):   Force finishing activity com.examplesample/.MainActivity
09-08 12:12:40.086: D/dalvikvm(1019): GC_FOR_ALLOC freed 2662K, 21% free 30433K/38356K, paused 92ms, total 93ms]

主要活动是:

package com.examplesample;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements                 OnCompletionListener,SeekBar.OnSeekBarChangeListener {

private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnPlaylist;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private MediaPlayer mp;
private Handler mhandler=new Handler();
private SongsManager SongsManager;
private Utilities utils;
private int seekForwardTime=5000;
private int seekBackwardTime=5000;
private int currentSongIndex=0;
private boolean isShuffle=false;
private boolean isRepeat=false;
private ArrayList<HashMap<String,String>> songsList=new     ArrayList<HashMap<String,String>>();





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

    btnPlay=(ImageButton) findViewById(R.id.btnPlay);
    btnForward=(ImageButton)findViewById(R.id.btnForward);
    btnBackward=(ImageButton)findViewById(R.id.btnBackward);
    btnNext=(ImageButton) findViewById(R.id.btnNext);
    btnPrevious=(ImageButton) findViewById(R.id.btnPrevious);
    btnPlaylist=(ImageButton) findViewById(R.id.btnPlaylist);
    btnRepeat=(ImageButton) findViewById(R.id.btnRepeat);
    btnShuffle=(ImageButton) findViewById(R.id.btnShuffle);
    songProgressBar=(SeekBar) findViewById(R.id.songProgressBar);
    songTitleLabel=(TextView) findViewById(R.id.songTitle);
    songCurrentDurationLabel=(TextView) findViewById(R.id.songCurrentDurationLabel);
    songTotalDurationLabel=(TextView) findViewById(R.id.songTotalDurationLabel);
    mp = new MediaPlayer();
    SongsManager = new SongsManager();
    utils = new Utilities();
    songProgressBar.setOnSeekBarChangeListener(this);
    mp.setOnCompletionListener(this);

    songsList=SongsManager.getPlayList();
    playSong(0);

    btnPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if(mp.isPlaying()){
                if (mp!=null) {
                    mp.pause();
                    btnPlay.setImageResource(R.drawable.btn_play);

                }
            }else{


            if(mp!=null){
                mp.start();
                btnPlay.setImageResource(R.drawable.btn_pause);
            }
            }
        }
    });
    btnForward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            int currentPosition=mp.getCurrentPosition();
            if(currentPosition+seekForwardTime<=mp.getDuration()){
                mp.seekTo(currentPosition+seekForwardTime);
            }else {
                mp.seekTo(mp.getDuration());
            }


        }
    });

    btnBackward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            int currentPosition=mp.getCurrentPosition();
            if(currentPosition-seekBackwardTime>=0){
                mp.seekTo(currentPosition-seekBackwardTime);
            }else {
                mp.seekTo(0);
            }

        }
    });

    btnNext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
        if(currentSongIndex<(songsList.size()-1)){
            playSong(currentSongIndex+1);
            currentSongIndex=currentSongIndex+1;
        }else{
            playSong(0);
            currentSongIndex=0;
        }

        }
    });


    btnPrevious.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if(currentSongIndex>0){
                playSong(currentSongIndex-1);
                currentSongIndex=currentSongIndex-1;
            }else{
                playSong(songsList.size()-1);
                currentSongIndex=songsList.size()-1;
            }


        }
    });

    btnRepeat.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if(isRepeat){
                isRepeat=false;
                Toast.makeText(getApplicationContext(), "Repeat is OFF",    Toast.LENGTH_SHORT).show();
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            } else{
                isRepeat=true;
                Toast.makeText(getApplicationContext(), "Repeat is ON",     Toast.LENGTH_SHORT).show();
                isShuffle=false;
                btnRepeat.setImageResource(R.drawable.btn_repeat_all);
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            }


        }
    });

    btnShuffle.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if(isShuffle){
                isShuffle=false;
                Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            } else {
                isShuffle=true;
                Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
                isRepeat=false;
                btnShuffle.setImageResource(R.drawable.btn_shuffle_all);
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            }
        }
    });

    btnPlaylist.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
        Intent intent = new Intent(getApplicationContext(), PlayListActivity.class);
        startActivityForResult(intent, 100);    
        }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode,Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode==100){
        currentSongIndex=data.getExtras().getInt("SongIndex");
        playSong(currentSongIndex);
    }
}


public void playSong(int songIndex) {
    // TODO Auto-generated method stub
    try {
        mp.reset();

        mp.setDataSource(songsList.get(songIndex).get("songPath"));
        mp.prepare();
        mp.start();
        String songTitle=songsList.get(songIndex).get("songTitle");
        songTitleLabel.setText(songTitle);
        btnPlay.setImageResource(R.drawable.btn_pause);
        songProgressBar.setProgress(0);
        songProgressBar.setProgress(100);
        updateProgressBar();


    } catch (IllegalArgumentException e) {
        // TODO: handle exception
    e.printStackTrace();
    } catch (IllegalStateException e){
        e.printStackTrace();
    }catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}


private void updateProgressBar() {
    // TODO Auto-generated method stub
    mhandler.postDelayed(mUpdateTimeTask, 100);
}

private Runnable mUpdateTimeTask=new Runnable() {


    @Override
    public void run() {
        // TODO Auto-generated method stub
        long totalDuration=mp.getDuration();
        long currentDuration=mp.getCurrentPosition();
        songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
            songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
        int progress=(int)(utils.getProgressPercentage(currentDuration,totalDuration));
        songProgressBar.setProgress(progress);
        mhandler.postDelayed(this, 100);
    }
};



@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}


@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
    // TODO Auto-generated method stub

}


@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    mhandler.removeCallbacks(mUpdateTimeTask);
}


@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    mhandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration=mp.getDuration();
    int currentPosition=utils.progressToTimer(seekBar.getProgress(),totalDuration);
    mp.seekTo(currentPosition);
    updateProgressBar();
}


@Override
public void onCompletion(MediaPlayer arg0) {
    // TODO Auto-generated method stub
    if(isRepeat) {
        playSong(currentSongIndex);

    } else if(isShuffle) {
        Random rand=new Random();
        currentSongIndex=rand.nextInt((songsList.size()-1)-0+1)+0;
        playSong(currentSongIndex);

    }else {
        if(currentSongIndex<(songsList.size()-1)) {
            playSong(currentSongIndex+1);
            currentSongIndex=currentSongIndex+1;
        } else{
            playSong(0);
            currentSongIndex=0;

        }
    }
}

@Override
public void onDestroy(){
    super.onDestroy();``
    mp.release();
}

}

当双击它关注的错误时:'songsList = SongsManager.getPlayList();         playSong(0);”

我是Android新手。我只有一些关于java的知识。请帮助我

songsmanager:

    public class SongsManager {
private long id;
private String title;
private String artist;
final String MEDIA_PATH=new String("/sdcard/");
private ArrayList<HashMap<String, String>> songsList=new   ArrayList<HashMap<String,String>>();

public SongsManager(){

}
    public ArrayList<HashMap<String, String>> getPlayList() {
    // TODO Auto-generated method stub
        File home=new File(MEDIA_PATH);
        if(home.listFiles(new FileExtensionFilter()).length>0){
        for(File file:home.listFiles(new FileExtensionFilter())){
            HashMap<String, String> song=new HashMap<String, String>();
            song.put("songTitle", file.getName().substring(0,      (file.getName().length()-4)));
            song.put("songPath", file.getPath());
            songsList.add(song);
            }
        }
        return songsList;
    }

    class FileExtensionFilter implements FilenameFilter {


    @Override
    public boolean accept(File dir, String name) {
        // TODO Auto-generated method stub

        return (name.endsWith(".mp3")||name.endsWith(".MP3"));
    }

 }

}

0 个答案:

没有答案