android force close on clicking on seekbar - android

i'm newbie to android programming. i have the following code but i have a problem. when i click on the seekbar without playing the sound it force close. i mean when i click the play button i can click and seek on the seekbar but without clicking the play button clicking on the seekbar will cause force close. what's the problem?!
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity implements Runnable, OnClickListener, OnSeekBarChangeListener{
private SeekBar seekBar;
private ImageButton startMedia;
private ImageButton pauseMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AudioControl();
}
public void AudioControl(){
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (ImageButton) findViewById(R.id.playbutton);
pauseMedia = (ImageButton) findViewById(R.id.pausebutton);
seekBar.setOnSeekBarChangeListener(this);
startMedia.setOnClickListener(this);
pauseMedia.setOnClickListener(this);
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp != null && mp.isPlaying()) return;
if(seekBar.getProgress() > 0) {
mp.start();
return;
}
mp = MediaPlayer.create(MainActivity.this, R.raw.lone);
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
if (v.equals(pauseMedia) && mp!=null) {
mp.pause();
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser) mp.seekTo(progress);
}
}
and i have another question:
i wanna when the user clicks on play button the pause button become visible and when the user clicks on pause button it tuen invisble. what code should i wirte and please tell me where should i put this code.

Every method that manages the UI has to be called on the UI Thread itself:
You can not run
seekBar.setProgress(currentPosition);
on a Thread different frome the UIThread.

Related

Media Player Button Is Not Restarting

I wanna make "Play/Stop" button. When button "Play" is clicked, the song must be played and its text should be converted into "Stop" and when "Stop" is clicked, the button text should be changed into "Play" again and song should start again to play from the beginning.
import android.media.MediaPlayer;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button btn_playStop;
private MediaPlayer mediaPlayer;
private boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Play Music");
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.zara_sa);
btn_playStop = (Button)findViewById(R.id.btn_play_stop);
btn_playStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying() && flag==true){
stopSong();
}
else if (flag == false){
playSong();
}
}
});
}
public void playSong(){
mediaPlayer.start();
btn_playStop.setText("Stop");
flag = true;
}
public void stopSong() {
mediaPlayer.stop();
btn_playStop.setText("Play");
flag = false;
}
}
You must call mediaPlayer.prepare(); if you called mediaPlayer.stop(); so in the first time you can just call mediaPlayer.start(); but in the next times you should call mediaPlayer.prepare(); before mediaPlayer.start();
public void playSong(){
try {
mediaPlayer.prepare();
} catch (IOException e) {
}
mediaPlayer.start();
btn_playStop.setText("Stop");
flag = true;
}

SeekBar wont display current position, but still plays the music on the position the user wanted

I recently posted a question that asks how SeekBars are operated. And someone directed me to this website/tutorial: http://android-mantra.blogspot.com/2013/09/seekbar-for-music-player.html
It really helped me alot and helped me understand how seekbars work, but I still have a problem. When I click the play button, the music will play, but when i seek the music, the seekbar will stay at position 0, although the music is runing on the position I wanted. Here is my code that i based (copy) from the tutorial.
package com.example.danbrianarenas.musictesterv2;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;
public class MainActivity extends Activity implements Runnable,View.OnClickListener,SeekBar.OnSeekBarChangeListener
{
SeekBar seekBar;
Button startMedia;
Button stopMedia;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (Button) findViewById(R.id.button1);
stopMedia = (Button) findViewById(R.id.button2);
startMedia.setOnClickListener(this);
stopMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setEnabled(false);
}
public void run()
{
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp !=null && currentPosition<total)
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
} catch (Exception e){
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View view){
if(view.equals(startMedia)){
if(mp == null){
mp=MediaPlayer.create(getApplicationContext(), R.raw.filc2);
seekBar.setEnabled(true);
}
if(mp.isPlaying()){
mp.pause();
startMedia.setText("Play");
}
else{
mp.start();
startMedia.setText("Pause");
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
}
if (view.equals(stopMedia) && mp!=null){
if (mp.isPlaying() || mp.getDuration()>0){
mp.stop();
mp = null;
startMedia.setText("play");
seekBar.setProgress(0);
}
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
try{
if(mp.isPlaying() || mp!=null){
if(fromUser)
mp.seekTo(progress);
}else if (mp==null){
Toast.makeText(getApplicationContext(),"Media is not running!",Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
}catch (Exception e){
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar){
//TODO Auto-generated method sub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar){
//TODO Auto-generated method sub
}
}
PS: please tell me if you need the XML file. :) TIA
As you are not chaning the position of seekbar on your seekbar change listener update your code and it will work:
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
try{
if(mp.isPlaying() || mp!=null){
if(fromUser){
seekBar.setProgress(progress); // ************** you have to add this line
mp.seekTo(progress);
}}else if (mp==null){
Toast.makeText(getApplicationContext(),"Media is not running!",Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
}catch (Exception e){
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}

How To play radio app in background and show Widget on notification bar?

Considering this code:
package com.radio.radiostar;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import java.io.IOException;
public class MainActivity extends Activity implements OnClickListener {
private final static String RADIO_STATION_URL = "http://178.32.137.180:8665/stream";
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
};
I want to enable the background play, with a widget on notification bar like "apollo" or any other media player (with only play/pause button and the "x" to close streaming and background).
Can you help me, writing the code that I must use, and in which part of code?
Thanks in advance.
Fabio.
EDIT: I have deleted
if (player.isPlaying()) {
player.p();
From
#Override
protected void onPause() {
super.onPause();
}
And now works in background u.u
I only need to show the widget on notification bar :)
You want to play the stream while the app is minimized? Then you have to user the Service. You should move your code to the service. And you will be able to handle notification bar from the service as well.
When you do this, you will probably ask yourself "how can I now update the UI since the player is handled in the service". The answer to this is usage of BroadcastService where your Service will broadcast all important data (like timer ticks while stream is active) and your Activity has to catch those data and use it to fill its own UI.
Since the code for what I described here is huge, you should try implementing a service and broadcast logic first, and if you are stuck, come back here with a concrete question.

Connecting Seekbar with Hardware buttons on device

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class pushke extends Activity {
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
MediaPlayer mp;
MediaPlayer mp2;
MediaPlayer mp3;
MediaPlayer mp4;
MediaPlayer mp5;
MediaPlayer mp6;
SeekBar seekGuns;
RelativeLayout rguns;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.guns);
initControls();
rguns=(RelativeLayout) findViewById(R.id.rguns);
mp=MediaPlayer.create(this, R.raw.hekler);
ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp2.isPlaying()){
mp2.pause();
mp2.seekTo(0);
}
if (mp3.isPlaying()){
mp3.pause();
mp3.seekTo(0);
}
if (mp4.isPlaying()){
mp4.pause();
mp4.seekTo(0);
}
if (mp5.isPlaying()){
mp5.pause();
mp5.seekTo(0);
}
if (mp6.isPlaying()){
mp6.pause();
mp6.seekTo(0);
}
if (mp.isPlaying()){
mp.pause();
mp.seekTo(0);
}
else{
mp.start();
}
}
});
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar)findViewById(R.id.seekGuns);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
int index = seekGuns.getProgress();
seekGuns.setProgress(index + 1);
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
int index = seekGuns.getProgress();
seekGuns.setProgress(index - 1);
return true;
}
return super.onKeyDown(keyCode, event);
}
I am trying to connect hardware buttons to my seekbar so when I click on volume buttons, seekbar which is used for volume, increase-decrease depending on which button I pressed.
I got this code which is supposed to be working, but I have no idea why it's not working in my case, everytime I launch my app on phone as emulator, and use hardware volume button app crashes.
I get this in LoGcat but Ican't figure out how to fix it or where is the problem because eclipse is not showing me any errors.
Here is my logcat: http://i.imgur.com/o4qSvCv.png
This is because you have declared two Seekbar variables.
private SeekBar volumeSeekbar = null;
SeekBar seekGuns;
and in your onKeyDown method you are using seekGuns named variable which is not initialized.
So you have two option.
1) Initialize means find the id for seekguns variable.
2) Use volumeSeekbar instead of seekguns in onKeyDown method.

seekbar not working when runnable and handler.postdelayed() are added in android apps

I'm not sure why I get error on the handler. The codes work until when I add in the handler to control the seekbar, it will prompt error.
package com.voice.recording.v3;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class VoiceRecordingPlaybackv3Activity extends Activity implements OnCompletionListener,
OnTouchListener, OnClickListener, OnSeekBarChangeListener {
MediaPlayer mediaPlayer;
View theView;
Button stopButton, startButton, quitButton;
SeekBar seekBar;
Handler handler;
int position = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
stopButton = (Button)this.findViewById(R.id.StopButton);
startButton = (Button)this.findViewById(R.id.StartButton);
quitButton = (Button)this.findViewById(R.id.quitButton);
startButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
quitButton.setOnClickListener(this);
theView = this.findViewById(R.id.theview);
theView.setOnTouchListener(this);
mediaPlayer = MediaPlayer.create(this, R.raw.goodmorningandroid);
mediaPlayer.setOnCompletionListener(this);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setMax(mediaPlayer.getDuration());
}
public void onCompletion(MediaPlayer mp){
mediaPlayer.start();
mediaPlayer.seekTo(position);
}
public boolean onTouch(View v, MotionEvent me){
if(me.getAction() == MotionEvent.ACTION_MOVE){
if(mediaPlayer.isPlaying()){
position = (int)(me.getX()*
mediaPlayer.getDuration()/theView.getWidth());
Log.v("SEEK",""+position);
mediaPlayer.seekTo(position);
}
}
return true;
}
public void onClick(View v){
if(v == stopButton){
mediaPlayer.pause();
}else if(v == startButton){
try{
mediaPlayer.start();
startPlayProgressUpdater();
}catch(IllegalStateException e){
mediaPlayer.pause();
}
}else if(v == quitButton ){
mediaPlayer.stop();
mediaPlayer.release();
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
seekBar.setSecondaryProgress(seekBar.getProgress());
}
public void startPlayProgressUpdater() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification,100);
}else{
mediaPlayer.pause();
seekBar.setProgress(0);
}
}
}
The error I get is NullPointerException, can anyone please point out my mistaken
Your code shows handler is defined by not initialized. Please post stacktrace if that's not the problem.

Categories

Resources