Question

I'm making a simple mediaplayer app that downloads a song from a predetermined URL then let's the user play, pause and stop the song, among other things. My only problem right now is that if the user tries to play the song before they download it the application force closes.

My first instinct is to create a global bool flag, set it to true when my download service downloads the file, and then use that flag to error check before I let the play.onclick button run the play service.

So for example:

play.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            if (downloadFlag == true){
                Intent intent = new Intent(getApplicationContext(), PlayService.class);
                intent.putExtra("key", 0);
                intent.putExtra("nkey", 0);
                startService(intent);   
                String artistFirst = url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('_'));
                String artistLast = url.substring(url.lastIndexOf('_')+1, url.lastIndexOf('-'));
                String song = url.substring(url.lastIndexOf('-')+1, url.lastIndexOf('.'));
                tv_artist.setText("Artist: "+artistFirst+" "+artistLast);
                tv_song.setText("Song: "+song);
                final ImageView album = (ImageView) findViewById(R.id.imageView1);
                album.setImageResource(R.drawable.album);
            }
        }
    });

Is this a good way to approach this problem or should I pursue a more elegant solution?

Edit::Solution found

At start of the application I disable the play button and then enable it in my broadcastreceiver (which catches when the download finishes)

 Button play = (Button) ((Activity) context).findViewById(R.id.play);
    play.setEnabled(true);
Was it helpful?

Solution

Add the listener after the song is downloaded (in the same place you would set your flag to true). Or disable the button and enable it when the song is downloaded. That way you don't have to use a flag.

play.setEnabled(false)
//...
play.setEnabled(true)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top