<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.m.musicplayer"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:permission="android.permission.READ_EXTERNAL_STORAGE">
<activity
android:name="com.m.musicplayer.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboardHidden|orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.m.musicplayer.PlayListActivity" />
</application>
</manifest>
这是我的manifest.xml文件,当我尝试在sony xperia tipo中安装我的应用程序时,它会崩溃并显示应用程序停止工作但它在蓝色堆栈中工作正常..
上述程序的Logcat stacktrace是:
09-16 09:40:32.842: E/AndroidRuntime(812): FATAL EXCEPTION: main
09-16 09:40:32.842: E/AndroidRuntime(812): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.m.musicplayer/com.m.musicplayer.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
09-16 09:40:32.842: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-16 09:40:32.842: E/AndroidRuntime(812): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-16 09:40:32.842: E/AndroidRuntime(812): at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-16 09:40:32.842: E/AndroidRuntime(812): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-16 09:40:32.842: E/AndroidRuntime(812): at android.os.Handler.dispatchMessage(Handler.java:99)
09-16 09:40:32.842: E/AndroidRuntime(812): at android.os.Looper.loop(Looper.java:137)
09-16 09:40:32.842: E/AndroidRuntime(812): at android.app.ActivityThread.main(ActivityThread.java:5039)
09-16 09:40:32.842: E/AndroidRuntime(812): at java.lang.reflect.Method.invokeNative(Native Method)
09-16 09:40:32.842: E/AndroidRuntime(812): at java.lang.reflect.Method.invoke(Method.java:511)
09-16 09:40:32.842: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-16 09:40:32.842: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-16 09:40:32.842: E/AndroidRuntime(812): at dalvik.system.NativeStart.main(Native Method)
09-16 09:40:32.842: E/AndroidRuntime(812): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
09-16 09:40:32.842: E/AndroidRuntime(812): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
09-16 09:40:32.842: E/AndroidRuntime(812): at java.util.ArrayList.get(ArrayList.java:304)
09-16 09:40:32.842: E/AndroidRuntime(812): at com.m.musicplayer.MainActivity.playSong(MainActivity.java:319)
09-16 09:40:32.842: E/AndroidRuntime(812): at com.m.musicplayer.MainActivity.onCreate(MainActivity.java:112)
09-16 09:40:32.842: E/AndroidRuntime(812): at android.app.Activity.performCreate(Activity.java:5104)
09-16 09:40:32.842: E/AndroidRuntime(812): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-16 09:40:32.842: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-16 09:40:32.842: E/AndroidRuntime(812): ... 11 more
任何建议..?
提前thanx
package com.m.musicplayer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import android.app.Activity;
//import android.content.Context;
import android.content.Intent;
//import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.KeyEvent;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.VerticalSeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity 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 ImageButton btnVolume;
private VerticalSeekBar volumeProgressBar;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
private MediaPlayer mp;
//private AudioManager am;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
//set max and current volume
int maxVolume=15;
int curVolume=0;
float Volume=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
// All player buttons
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);
//btnVolume = (ImageButton) findViewById(R.id.btnVolume);
volumeProgressBar = (android.widget.VerticalSeekBar) findViewById(R.id.volumeProgressBar);
songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
songTitleLabel = (TextView) findViewById(R.id.songTitle);
songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
// Media player
mp = new MediaPlayer();
songManager = new SongsManager();
utils = new Utilities();
//am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Listeners
songProgressBar.setOnSeekBarChangeListener(this); // Important
mp.setOnCompletionListener(this); // Important
/*maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
curVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
volumeProgressBar.setMax(maxVolume);
volumeProgressBar.setProgress(curVolume);*/
volumeProgressBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekbar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekbar) {
}
@Override
public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser)
{
Volume= (float)progress/100;
mp.setVolume(Volume, Volume);
}
});
// Getting all songs list
songsList = songManager.getPlayList();
// By default play first song
playSong(0);
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// check for already playing
if(mp.isPlaying()){
if(mp!=null){
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
}else{
// Resume song
if(mp!=null){
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
}
}
}
});
/**
* Forward button click event
* Forwards song specified seconds
* */
btnForward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// get current song position
int currentPosition = mp.getCurrentPosition();
// check if seekForward time is lesser than song duration
if(currentPosition + seekForwardTime <= mp.getDuration()){
// forward song
mp.seekTo(currentPosition + seekForwardTime);
}else{
// forward to end position
mp.seekTo(mp.getDuration());
}
}
});
/**
* Backward button click event
* Backward song to specified seconds
* */
btnBackward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// get current song position
int currentPosition = mp.getCurrentPosition();
// check if seekBackward time is greater than 0 sec
if(currentPosition - seekBackwardTime >= 0){
// forward song
mp.seekTo(currentPosition - seekBackwardTime);
}else{
// backward to starting position
mp.seekTo(0);
}
}
});
/**
* Next button click event
* Plays next song by taking currentSongIndex + 1
* */
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(isShuffle){
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
}
// check if next song is there or not
if(currentSongIndex < (songsList.size() - 1)){
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
}else{
// play first song
playSong(0);
currentSongIndex = 0;
}
}
});
/**
* Back button click event
* Plays previous song by currentSongIndex - 1
* */
btnPrevious.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(currentSongIndex > 0){
playSong(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
}else{
// play last song
playSong(songsList.size() - 1);
currentSongIndex = songsList.size() - 1;
}
}
});
/**
* Button Click event for Repeat button
* Enables repeat flag to true
* */
btnRepeat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(isRepeat){
isRepeat = false;
Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
btnRepeat.setImageResource(R.drawable.btn_repeat);
}else{
// make repeat to true
isRepeat = true;
Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
// make shuffle to false
isShuffle = false;
btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}
}
});
/**
* Button Click event for Shuffle button
* Enables shuffle flag to true
* */
btnShuffle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(isShuffle){
isShuffle = false;
Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}else{
// make repeat to true
isShuffle= true;
Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
// make shuffle to false
isRepeat = false;
btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
btnRepeat.setImageResource(R.drawable.btn_repeat);
}
}
});
/**
* Button Click event for Play list click event
* Launches list activity which displays list of songs
* */
btnPlaylist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
startActivityForResult(i, 100);
}
});
}
/**
* Receiving song index from playlist view
* and play the song
* */
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 100){
currentSongIndex = data.getExtras().getInt("songIndex");
// play selected song
playSong(currentSongIndex);
}
}
/**
* Function to play a song
* @param songIndex - index of song
* */
public void playSong(int songIndex){
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
// Displaying Song title
String songTitle = songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
//volumeProgressBar.setMax(maxVolume);
//volumeProgressBar.setProgress(curVolume);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Update timer on seekbar
* */
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// Displaying Total Duration time
songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
//Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
/**
*
* */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
//am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
//Volume = progress;
}
/**
* When user starts moving the progress handler
* */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
mHandler.removeCallbacks(mUpdateTimeTask);
}
/**
* When user stops moving the progress hanlder
* */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
/*if(SeekBar.class.equals(volumeProgressBar))
{
Toast.makeText(getApplicationContext(), "Volume: " + Integer.toString(Volume), Toast.LENGTH_SHORT).show();
}*/
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
/**
* On Song Playing completed
* if repeat is ON play same song again
* if shuffle is ON play random song
* */
@Override
public void onCompletion(MediaPlayer arg0) {
// check for repeat is ON or OFF
if(isRepeat){
// repeat is on play same song again
playSong(currentSongIndex);
} else if(isShuffle){
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else{
// no repeat or shuffle ON - play next song
if(currentSongIndex < (songsList.size() - 1)){
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
}else{
// play first song
playSong(0);
currentSongIndex = 0;
}
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode ==KeyEvent.KEYCODE_VOLUME_UP)
{
curVolume++;
if(curVolume<=maxVolume){
Volume= (float) (1 - (Math.log(maxVolume - curVolume) / Math.log(maxVolume)));
mp.setVolume(Volume, Volume);
Toast.makeText(getApplicationContext(), "Volume: " + Float.toString(Volume), Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "Maximum Volume: " + Float.toString(Volume), Toast.LENGTH_SHORT).show();
}
else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
curVolume--;
if(curVolume>0)
{
Volume= (float) (1 - (Math.log(maxVolume - curVolume) / Math.log(maxVolume)));
mp.setVolume(Volume, Volume);
Toast.makeText(getApplicationContext(), "Volume: " + Float.toString(Volume), Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "Minimum Volume: " + Float.toString(Volume), Toast.LENGTH_SHORT).show();
}
return true;
}
@Override
public void onDestroy(){
super.onDestroy();
mp.release();
}
}
ny songmanager.java类中的songmanager.getplaylist代码
package com.m.musicplayer;
import android.annotation.SuppressLint;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
public class SongsManager {
// SDCard Path
@SuppressLint("SdCardPath") final String MEDIA_PATH = new String("/sdcard/");
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Constructor
public SongsManager(){
}
/**
* Function to read all mp3 files from sdcard
* and store the details in ArrayList
* */
public ArrayList<HashMap<String, String>> getPlayList(){
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());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which are having .mp3 extension
* */
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
}