Search code examples
androidandroid-sdcardandroid-music-player

play music in sdcard if exist file


i am playing music from SD-card and file exist it is playing music file but if it does not exist my app crashes what can i do?

package com.example.downloadplay;

public class AudioPlayer extends Activity implements OnClickListener {
Button playButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

playButton = (Button) this.findViewById(R.id.ButtonPlayStop);
playButton.setOnClickListener(this);
}

public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File sdcard = Environment.getExternalStorageDirectory();
File audioFile = new File(sdcard.getPath() + "/bluetooth/یه سوال دارم مگه.mp3");

 intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
 startActivity(intent);
 }
 }

Solution

  • Check if file exists with

    if(audioFile.exists())
    {
      intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
      startActivity(intent);
    }
    else
    {
       // show error
    }