Can't handle with Handler - android

I am playing music form my sd card and i want my seekbar to getprogress every 2 sec when music is playing. I am trying to do it with Handler. But i dont know how to use Handler coretly
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar1 = (SeekBar) findViewById(R.id.seekBar1);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
textView1 = (TextView) findViewById(R.id.textView1);
button1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(Environment.getExternalStorageDirectory()+"/MyImages/.audio2.wav");
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setupHandler();
}
});
}
private void setupHandler()
{
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 2000); //cal the thread after millisec
}
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if(mediaPlayer.isPlaying()){
int mediaPos = mediaPlayer.getCurrentPosition();
int mediaMax = mediaPlayer.getDuration();
seekBar1.setMax(mediaMax);
seekBar1.setProgress(mediaPos);
handler.postDelayed(this, 2000); //Looping the thread after second
// seconds
}
}
};
}
My app crashing 2 second after i clikc the button1. So i am sure the problem here is Handler. Do i call this handler wrong or something?

Post your logcat always when you ask about app crashes.
Therefor in this case you have NullPointerException here, i think:
if(mediaPlayer.isPlaying())
You doesn't initialize your mediaplayer variable.
EDITED:
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar1 = (SeekBar) findViewById(R.id.seekBar1);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
textView1 = (TextView) findViewById(R.id.textView1);
button1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(Environment.getExternalStorageDirectory()+"/MyImages/.audio2.wav");
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setupHandler();
}
});
}
private void setupHandler()
{
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 2000); //cal the thread after millisec
}
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if(mediaPlayer.isPlaying()){
int mediaPos = mediaPlayer.getCurrentPosition();
int mediaMax = mediaPlayer.getDuration();
seekBar1.setMax(mediaMax);
seekBar1.setProgress(mediaPos);
handler.postDelayed(this, 2000); //Looping the thread after second
// seconds
}
}
};

Use The below code to Update the SeekBar after 2Seconds.
Create the Object for Handler inside your onCreate() like the following one.
Handler miHandler=new Handler();
add Paste the code inside your thread.
miHandler.postDelayed(new Runnable() {
#Override
public void run() {
try{
seekBar1.setProgress(mediaPos+ add 2sec delay time also);
}catch(Exception e) {e.printStrackTrace();}
}
}, 1500);

Related

Seekbar for a mp3 file from SD card

I want add a seekbar on this class , but I cant
Please help me out
public class Play extends Title { // your class name
Button button, button1, stop;
MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
TextView tvHeading = (TextView) findViewById(R.id.titleHeading);
tvHeading.setText("music");
try {
audioPlayer("/sdcard/Android" , "Lala.mp3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
button = (Button) findViewById(R.id.play);
PersianReshape.ReshapeButton(button, "2 Sfarnaz.TTF", Play.this);
button1 = (Button) findViewById(R.id.puse);
PersianReshape.ReshapeButton(button1, "2 Sfarnaz.TTF", Play.this);
stop = (Button) findViewById(R.id.stop);
PersianReshape.ReshapeButton(stop, "2 Sfarnaz.TTF", Play.this);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mp.start();
}
});
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mp.pause();
}
});
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mp.setLooping(true);
}
});
}
public void audioPlayer(String path, String fileName) throws IOException{
if (mp != null) {
mp.reset();
}
try {
mp.setDataSource(path+"/"+fileName);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
//mp.reset();
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
mp.stop();
finish();
}}
I've tried a lot of code but did not receive an answer,
This code reads the file from the memory, but it is not the case for seekbar
PLZ help me

How do I call mediaplayer once only?

In android, I have a mediaplayer on detail screen, which duplicates when I select another screen then play another detail, causing sound files to play on the same time. how do I fix this problem? Id like to play the most recent selected media only.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feeddetail);
tc_recDurat = (TextView)findViewById(R.id.recDetDurat);
tc_recDuratBack = (TextView)findViewById(R.id.recDetDuratBack);
TextView tc_recPath = (TextView)findViewById(R.id.recDetPath);
recPath = (String) intent.getSerializableExtra("INTENT_PATH");
tc_recPath.setText(recPath);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(recPath);
} catch (IOException e1) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e1.getLocalizedMessage(), Toast.LENGTH_LONG);
}
ImageButton mClickButton1 = (ImageButton)findViewById(R.id.btnPlay);
mClickButton1.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer !=null){
try {
mediaPlayer
mediaPlayer.prepare();
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
seekUpdate();
isPlaying = true;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
ImageButton mClickButton2 = (ImageButton)findViewById(R.id.btnStop);
mClickButton2.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mediaPlayer.stop();
isPlaying = false;
}
});
I am not sure what your problem is, but i believe you are trying to say that as you change through different activities, the sounds files do not stop playing
In that case you can do the following
In the activity
You can override the onPause method and put mediaPlayer.stop() inside it
#Override
public void onPause() {
super.onPause();
mediaPlayer.stop();
}

Android Media Player Next Song

I have a listview in MainActivity from hehe i passing my listview position using this
Intent intent = new Intent(MainActivity.this, Linkview.class);
intent.putExtra("position", position);
startActivity(intent);
And I have a Linkview class here i received my position using this
final Bundle bundle = getIntent().getExtras();
position = bundle.getInt("position");
And i have a linkArray list.
link = getResources().getStringArray(R.array.lin
My player play well and i can stop it.
But I have a next button
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uri = Uri.parse(link[position+1]);
}
});
When I pressed my next button nothing is happened. I want that when I pressed the next button from my array next link will be play but nothing is play.
How i can solve this issue.
My hole code is here.
public class Linkview extends Activity {
Button play, stop, next;
MediaPlayer mediaPlayer;
private String currentSongIndex;
RowItem rowItem;
MainActivity mainActivity;
Uri uri;
public String link[];
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_linkview);
stop = (Button) findViewById(R.id.stopbutton);
play = (Button) findViewById(R.id.playbutton);
next = (Button) findViewById(R.id.nextbutton1);
link = getResources().getStringArray(R.array.link);
// String itemString = MainActivity.link[position];
final Bundle bundle = getIntent().getExtras();
// String link = bundle.getString("link");
// position = bundle.getInt("position");
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
if (position <= 2) {
uri = Uri.parse(link[position + 1]);
}
}
});
position = bundle.getInt("position");
uri = Uri.parse(link[position]);
// .parse("android.resource://com.prgguru.example/"
// + R.raw.hosannatamil);");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getApplicationContext(), uri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
});
}
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
Maybe this will work:
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
uri = Uri.parse(link[position + 1]);
mediaPlayer.setDataSource(getApplicationContext(), uri);
mediaPlayer.prepare();
mediaPlayer.start();
}
});

Android handling state of ProgressBar onPause/onResume

Hi have a progressBar that i run. but when the user exits the app via the home button and then re-enters it by holding down the home button and selected the app. The progressBar setProgress flickers between an old value and a new one almost as if its remembering the previous state. I have created a function in my on pause/onResume methods to pause the timer save the values and on resume get those values and start the timer and progress bar again. The confusing thing is it works the onPause stuff works perfectly if the onPause function is run and the user stays in the app for example presses the back button. Does anyone know where im going wrong or how to correctly implement a progressBar using a CountDownTimer?
heres my code
#Override
protected void onResume() {
// TODO Auto-generated method stub
Log.v("Game","ONRESUME");
loadData();
layoutChecks();
loadViews();
try {
if(!myData.get("completed").equals("3")){
hintCheck();
getHints();
startTimer();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onResume();
}
#Override
protected void onPause() {
Log.v("Game","ONPAUSE");
try {
if(!myData.get("completed").equals("3")){
pauseTimer();
updateData();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPause();
}
public void loadViews(){
progressBar = new ProgressBar(this);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressD = progressBar.getProgressDrawable();
}
public void prepareProgressBar(){
progressD.setLevel(0);
progressBar.setProgress(0);
progressD.setLevel(points*100);
progressBar.setProgress(points);
}
public void startTimer(){
try {
points = Integer.valueOf(myData.getJSONObject("Data").getString("points"));
int timer = points;
hasTimerCancelled = false;
prepareProgressBar();
counter = new MyCount(timer/2 * 1000,1000);
counter.start();
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public void pauseTimer(){
try {
counter.cancel();
hasTimerCancelled = true;
JSONObject Data = myData.getJSONObject("Data");
Data.put("points", String.valueOf(points));
myData.put("Data", Data);
updateData();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class MyCount extends CountDownTimer{
public long totaltime;
public MyCount(long totalTime, long countDownInterval) {
super(totalTime, countDownInterval);
totaltime = totalTime;
}
#Override
public void onFinish() {
counter.cancel();
points = 0;
progressBar.setProgress(0);
}
#Override
public void onTick(long millisUntilFinished) {
if(!hasTimerCancelled){
if(points > 0){
points = points - 1;
}
progressBar.setProgress((int) totaltime);
}
}
}

synchronizing seekbar with the audio song

I am playing a song from the sdcard.
Its plays fine. I tried to implement the seekbar such that when the user moves the seekbar the song gets forwarded or rewnided as per the seek bar position.
Here is the code
public class ViewAudio extends Activity implements OnSeekBarChangeListener,OnSeekCompleteListener,OnCompletionListener,OnPreparedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player);
System.gc();
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("audiofilename");
try {
mPlayer.setDataSource(filename);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.setOnCompletionListener(this);
mPlayer.setOnPreparedListener(this);
mPlayer.setOnSeekCompleteListener((OnSeekCompleteListener) this);
mPlayer.start();
TextView tv=(TextView) findViewById(R.id.file);
tv.setText("Playing "+filename);
seekbar = (SeekBar)findViewById(R.id.seekBar1);
mPlay = (Button)findViewById(R.id.play);
mPause = (Button)findViewById(R.id.pause);
seekbar.setProgress(0);
seekbar.setOnSeekBarChangeListener(this);
total = mPlayer.getDuration();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
Log.d("Progres changed",""+progress);
if(fromUser){
mPlayer.seekTo(progress);
seekbar.setProgress(progress);
}
}
}
Now where ever i click the seekbar the song is getting played from the beginning not from the position i clicked. And it is not moving based on the song.
Any one please help.
i have solved it.
Create a thread that will check the song position every second and move the seekbar based on the song position
mediaPos = mplayer.getCurrentPosition();
mediaMax = mplayer.getDuration();
seekbar.setMax(mediaMax); // Set the Maximum range of the
seekbar.setProgress(mediaPos);// set current progress to song's
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100); //cal the thread after 100 milliseconds
}
/**
* The Move seek bar. Thread to move seekbar based on the current position
* of the song
*/
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if(mplayer.isPlaying()){
int mediaPos_new = mPlayer.getCurrentPosition();
int mediaMax_new = mPlayer.getDuration();
seekbar.setMax(mediaMax_new);
seekbar.setProgress(mediaPos_new);
handler.postDelayed(this, 100); //Looping the thread after 0.1 second
}
}
};

Categories

Resources