Mediaplayer stops suddenly on playing

夙愿已清 提交于 2019-12-12 03:53:55

问题


I am new to android I have created a media player app but whenever i start playing it suddenly stops with an error as "Unfortunately youapp stopped". How should i rectify my app ?

Pls help me here's the code :

package com.example.allah;


import java.util.ArrayList;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
final ListView listview = (ListView) findViewById(R.id.listView1);
String[] values = new String[] { "Allah1", "Allah2" };
final ArrayList<String> list = new ArrayList<String>();

for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
    long arg3) {
myplaymethod();

}
});
}
public void myplaymethod(){
int myKey = 0;
View play_button = null;
switch (myKey) {
case 1:
    MediaPlayer my = MediaPlayer.create(getBaseContext(), R.raw.allah1);
    my.start();
    play_button.setVisibility(View.GONE);
    break;

case 2:
    MediaPlayer ma = MediaPlayer.create(getBaseContext(), R.raw.allah2);
    ma.start();
    play_button.setVisibility(View.GONE);
    break;

}


}

回答1:


Your mKey value is 0, and there is no case in switch which take 0 , Do it like this

I am supposing that you have only two songs in your list because you made only two cases in mplayermethod().

Inside listview.setOnItemClickListener replace your mplayermethod() with mplayermethod(arg2)

and in mplayermethod()

public void myplaymethod(int mKey){

View play_button = null;
switch (myKey) {
case 0:
MediaPlayer my = MediaPlayer.create(getBaseContext(), R.raw.allah1);
my.start();
play_button.setVisibility(View.GONE);
break;

case 1:
MediaPlayer ma = MediaPlayer.create(getBaseContext(), R.raw.allah2);
ma.start();
play_button.setVisibility(View.GONE);
break;

}


来源:https://stackoverflow.com/questions/19360454/mediaplayer-stops-suddenly-on-playing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!