Check if file exists with
if(audioFile.exists())
{
intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
startActivity(intent);
}
else
{
// show error
}
Domanda
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);
}
}
Soluzione
Check if file exists with
if(audioFile.exists())
{
intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
startActivity(intent);
}
else
{
// show error
}
Altri suggerimenti
You can check whether File exists or not by using File.exists()
File f = new File(filePathString);
if(f.exists())
{
//Play your sound
}
else
{
//And your other stuffs goes here
}
Note :
exists()
will return true for directories, too
Use below code.
if(audioFile.exists())
{
intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
startActivity(intent);
}
else
{
Builder alert = new AlertDialog.Builder(activity_name.this);
alert.setTitle("Alert");
alert.setMessage("File does not exist");
alert.setPositiveButton("OK", null);
alert.show();
}