MediaPlayer - handler.getCurrentPosition() - java

The issue is with these lines
seekBar1.setProgress(player.getCurrentPosition());
and
seekBar2.setProgress(player2.getCurrentPosition());
Error
Attempt to invoke virtual method 'int android.media.MediaPlayer.getCurrentPosition()' on a null object reference
also, a small request I have an issue with the handler.postDelayed can you please check this user question too I have the same issue, here is the link to that question
Code // full code is belove this
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}
Full Code // the code can be a little confusing and written badly
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MediaPlayer player, player2;
SeekBar seekBar1, seekBar2;
TextView currentTime1, currentTime2;
TextView totalTime1, totalTime2;
Handler handler1 = new Handler();
Handler handler2 = new Handler();
ImageView play, pause, stop, play2, pause2, stop2;
int pauseCurrentPosition, pauseCurrentPosition2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = MediaPlayer.create(this, R.raw.dog_howl);
player2 = MediaPlayer.create(this, R.raw.dog_bark);
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
play = findViewById(R.id.playbtn);
pause = findViewById(R.id.pausebtn);
stop = findViewById(R.id.stopbtn);
play2 = findViewById(R.id.playbtn2);
pause2 = findViewById(R.id.pausebtn2);
stop2 = findViewById(R.id.stopbtn2);
currentTime1 = findViewById(R.id.currentTime1);
currentTime2 = findViewById(R.id.currentTime2);
totalTime1 = findViewById(R.id.totalTime1);
totalTime2 = findViewById(R.id.totalTime2);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
play2.setOnClickListener(this);
pause2.setOnClickListener(this);
stop2.setOnClickListener(this);
seekBar1.setMax(player.getDuration());
seekBar2.setMax(player2.getDuration());
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
player.seekTo(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
player2.seekTo(i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
String totTime1 = createTimerLable1(player.getDuration());
totalTime1.setText(totTime1);
String totTime2 = createTimerLable2(player2.getDuration());
totalTime1.setText(totTime2);
}
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.playbtn:
UpdateSeekBar1 updateSeekBar1 = new UpdateSeekBar1();
handler1.post(updateSeekBar1);
if (player == null) {
player = MediaPlayer.create(getApplicationContext(), R.raw.dog_howl);
player.start();
} else if (!player.isPlaying()) {
player.seekTo(pauseCurrentPosition);
player.start();
}
break;
case R.id.pausebtn:
if (player != null) {
player.pause();
pauseCurrentPosition = player.getCurrentPosition();
}
break;
case R.id.stopbtn:
if (player != null) {
player.stop();
player = null;
}
break;
case R.id.playbtn2:
UpdateSeekBar2 updateSeekBar2 = new UpdateSeekBar2();
handler2.post(updateSeekBar2);
if (player2 == null) {
player2 = MediaPlayer.create(getApplicationContext(), R.raw.dog_bark);
player2.start();
} else if (!player2.isPlaying()) {
player2.seekTo(pauseCurrentPosition2);
player2.start();
}
break;
case R.id.pausebtn2:
if (player2 != null) {
player2.pause();
pauseCurrentPosition2 = player2.getCurrentPosition();
}
break;
case R.id.stopbtn2:
if (player2 != null) {
player2.stop();
player2 = null;
}
break;
}
}
public String createTimerLable1(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public String createTimerLable2(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}
}

Enter this code:-
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MediaPlayer player, player2;
SeekBar seekBar1, seekBar2;
TextView currentTime1, currentTime2;
TextView totalTime1, totalTime2;
Handler handler1 = new Handler();
Handler handler2 = new Handler();
ImageView play, pause, stop, play2, pause2, stop2;
int pauseCurrentPosition, pauseCurrentPosition2;
UpdateSeekBar1 updateSeekBar1 = new UpdateSeekBar1();
UpdateSeekBar2 updateSeekBar2 = new UpdateSeekBar2();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = MediaPlayer.create(this, R.raw.bekhayali);
player2 = MediaPlayer.create(this, R.raw.hawabanke);
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
play = findViewById(R.id.playbtn);
pause = findViewById(R.id.pausebtn);
stop = findViewById(R.id.stopbtn);
play2 = findViewById(R.id.playbtn2);
pause2 = findViewById(R.id.pausebtn2);
stop2 = findViewById(R.id.stopbtn2);
currentTime1 = findViewById(R.id.currentTime1);
currentTime2 = findViewById(R.id.currentTime2);
totalTime1 = findViewById(R.id.totalTime1);
totalTime2 = findViewById(R.id.totalTime2);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
play2.setOnClickListener(this);
pause2.setOnClickListener(this);
stop2.setOnClickListener(this);
seekBar1.setMax(player.getDuration());
seekBar2.setMax(player2.getDuration());
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.seekTo(seekBar.getProgress());
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player2.seekTo(seekBar.getProgress());
}
});
String totTime1 = createTimerLable1(player.getDuration());
totalTime1.setText(totTime1);
String totTime2 = createTimerLable2(player2.getDuration());
totalTime1.setText(totTime2);
}
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.playbtn:
handler1.post(updateSeekBar1);
if (player == null) {
player = MediaPlayer.create(getApplicationContext(), R.raw.bekhayali);
player.start();
} else if (!player.isPlaying()) {
player.seekTo(pauseCurrentPosition);
player.start();
}
break;
case R.id.pausebtn:
if (player != null) {
player.pause();
pauseCurrentPosition = player.getCurrentPosition();
}
break;
case R.id.stopbtn:
if (player != null) {
player.stop();
handler1.removeCallbacks(updateSeekBar1);
player = null;
}
break;
case R.id.playbtn2:
handler2.post(updateSeekBar2);
if (player2 == null) {
player2 = MediaPlayer.create(getApplicationContext(), R.raw.hawabanke);
player2.start();
} else if (!player2.isPlaying()) {
player2.seekTo(pauseCurrentPosition2);
player2.start();
}
break;
case R.id.pausebtn2:
if (player2 != null) {
player2.pause();
pauseCurrentPosition2 = player2.getCurrentPosition();
}
break;
case R.id.stopbtn2:
if (player2 != null) {
player2.stop();
handler2.removeCallbacks(updateSeekBar2);
player2 = null;
}
break;
}
}
public String createTimerLable1(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public String createTimerLable2(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}}

Related

How to show a alert dialog when app is launched first time

I have two audio files in my app. When the app is launched the first time and when the user plays the first audio for the first time, I want to show a dialog, but afterwards never show it again.
When the user clicks OK, then only the dialog will disappear.
I have only created the XML of the dialog because I don't know how to show a layout when the app is launched the first time.
MainActivity.java here the player1 (Media Player) and play1 (ImageView as the button to play the audio) is for the first audio where the dialog has to be shown.
public class MainActivity extends AppCompatActivity {
MediaPlayer player1, player2;
SeekBar seekBar1, seekBar2;
TextView currentTime1, currentTime2;
TextView remainingTime1, remainingTime2;
ImageView play1, play2;
int totalTime1, totalTime2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// PlayButton * The ButtonClick is in the last if you want to jump directly there *
play1 = findViewById(R.id.playbtn);
play2 = findViewById(R.id.playbtn2);
// TimeLables
currentTime1 = findViewById(R.id.currentTime1);
currentTime2 = findViewById(R.id.currentTime2);
remainingTime1 = findViewById(R.id.totalTime1);
remainingTime2 = findViewById(R.id.totalTime2);
// MediaPlayer
player1 = MediaPlayer.create(this, R.raw.dog_howl);
player2 = MediaPlayer.create(this, R.raw.dog_bark);
player1.setLooping(false);
player1.seekTo(0);
totalTime1 = player1.getDuration();
player2.setLooping(false);
player2.seekTo(0);
totalTime2 = player2.getDuration();
//SeekBar
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
seekBar1.setMax(totalTime1);
seekBar2.setMax(totalTime2);
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
player1.seekTo(progress);
seekBar1.setProgress(progress);
currentTime1.setText(createTimerLable1(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
player2.seekTo(i);
seekBar2.setProgress(i);
currentTime2.setText(createTimerLable2(i));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
new Thread(() -> {
while (player1 != null) {
try {
Message msg = new Message();
msg.what = player1.getCurrentPosition();
handler1.sendMessage(msg);
Thread.sleep(1000000000);
} catch (InterruptedException ignored) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000000000);
} catch (InterruptedException ignored) {
}
}
}).start();
// Admob Banner Ad
MobileAds.initialize(this, initializationStatus -> {
});
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
#SuppressLint("HandlerLeak")
private final Handler handler1 = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition1 = msg.what;
//Update SeekBar
seekBar1.setProgress(currentPosition1);
// Update Timelable
String totTime1 = createTimerLable1(player1.getDuration());
remainingTime1.setText(totTime1);
}
};
#SuppressLint("HandlerLeak")
private final Handler handler2 = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition2 = msg.what;
// Update SeekBar
seekBar2.setProgress(currentPosition2);
// Update Timelable
String totTime2 = createTimerLable2(player2.getDuration());
remainingTime2.setText(totTime2);
}
};
public String createTimerLable1(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public String createTimerLable2(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public void playBtnClick1(View view) {
if (player2.isPlaying()) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player1.isPlaying()) {
// Stoping
player1.start();
play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
public void playBtnClick2(View view) {
if (player1.isPlaying()) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player2.isPlaying()) {
// Stoping
player2.start();
play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
}
As #blackapps suggested, You will save the information about the user in SharedPreferences. You will save whether you have displayed the dialog and whether user's has played audio for first time or not.
To save or get the details from SharedPreferences,
You can follow this SO answer for storing strings, int, boolean etc.
You can follow this SO answer for storing custom objects.

CountDownTimer is not stopping on BackPressed running in background,may be handler.postDelayed() is the issue. How to fix it in this code?

My Countdown timer is working fine but when I use back press during running state of the time, my countdown timer did not stop. I have tried everything as follows but none of them is able to stop the countdown timer from running in the background. After searching the forum an applying the results from it to my project I am unable to figure out whats fault in my code. Please anyone help me out and I shall be very thankful.
public class QuizActivity extends AppCompatActivity {
private static final long COUNTDOWN_IN_MILLIS = 30000 ;
List<Questions> mQuestions;
int score = 0;
int qid = 0;
Questions currentQ;
TextView txtQuestions, textViewCountDown;
RadioButton rda, rdb, rdc;
Button btnNext;
private QuestionsViewModel questionsViewModel;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private ColorStateList textColorDefaultCd;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;
private Handler handler;
private Runnable runnable = new Runnable() {
#Override
public void run() {
takeAction();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
textViewCountDown = findViewById(R.id.text_view_countdown);
relativeLayout = (RelativeLayout)findViewById(R.id.profileLoadingScreen);
linearLayout = (LinearLayout) findViewById(R.id.linearView);
textColorDefaultCd = textViewCountDown.getTextColors();
fetchQuestions();
questionsViewModel = ViewModelProviders.of(QuizActivity.this).get(QuestionsViewModel.class);
questionsViewModel.getAllQuestions().observe(this, new Observer<List<Questions>>() {
#Override
public void onChanged(#Nullable final List<Questions> words) {
// Update the cached copy of the words in the adapter.
mQuestions = words;
//Collections.shuffle(mQuestions);
Collections.addAll(mQuestions);
}
});
}
private void fetchQuestions() {
DataServiceGenerator dataServiceGenerator = new DataServiceGenerator();
Service service = DataServiceGenerator.createService(Service.class);
Call<List<QuestionsModel>> call = service.getQuestions();
call.enqueue(new Callback<List<QuestionsModel>>() {
#Override
public void onResponse(Call<List<QuestionsModel>> call, Response<List<QuestionsModel>> response) {
if (response.isSuccessful()){
if (response != null){
List<QuestionsModel> questionsModelList = response.body();
for (int i = 0; i < questionsModelList.size(); i++){
String question = questionsModelList.get(i).getQuestion();
String answer = questionsModelList.get(i).getAnswer();
String opta = questionsModelList.get(i).getOpta();
String optb = questionsModelList.get(i).getOptb();
String optc = questionsModelList.get(i).getOptc();
Questions questions = new Questions(question, answer, opta, optb, optc);
questionsViewModel.insert(questions);
}
handler = new Handler();//add this
handler.postDelayed(runnable,3000);
/* Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
takeAction();
}
}, 3000); */
}
}else{
}
}
#Override
public void onFailure(Call<List<QuestionsModel>> call, Throwable t) {
}
});
}
private void setQuestionView()
{
txtQuestions.setText(currentQ.getQuestion());
rda.setText(currentQ.getOptA());
rdb.setText(currentQ.getOptB());
rdc.setText(currentQ.getOptC());
qid++;
}
private void startCountDown() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
timeLeftInMillis = 0;
updateCountDownText();
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}.start();
}
private void updateCountDownText() {
int minutes = (int) (timeLeftInMillis / 1000) / 60;
int seconds = (int) (timeLeftInMillis / 1000) % 60;
String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
textViewCountDown.setText(timeFormatted);
if (timeLeftInMillis < 10000) {
textViewCountDown.setTextColor(Color.RED);
} else {
textViewCountDown.setTextColor(textColorDefaultCd);
}
}
private void takeAction() {
relativeLayout.setVisibility(View.GONE);
linearLayout.setVisibility(View.VISIBLE);
textViewCountDown.setVisibility(View.VISIBLE);
timeLeftInMillis = COUNTDOWN_IN_MILLIS;
startCountDown();
currentQ = mQuestions.get(qid);
txtQuestions = (TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
btnNext=(Button)findViewById(R.id.button1);
setQuestionView();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
if (grp.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(),
"Please Select an Answer",
Toast.LENGTH_SHORT)
.show();
return;
}else{
// countDownTimer.cancel();
}
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
grp.clearCheck();
//Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getAnswer().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}else{
}
if(qid<10){
currentQ=mQuestions.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onPause() {
super.onPause();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onStop() {
super.onStop();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
public void onBackPressed() {
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
}
Try this code
#Override
public void onBackPressed() {
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}

Android MediaPlayer seekBar not working correctly

Currently, I'm developing a media player and I need seekBar to work together, at the moment, it's everything okay! but, when I touch at determinated position of the seekbar, the mediaplayer must follow and set the song to this determinated position, but the song and seekBar back to the start and I don't know why it's happening.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Handler mHandler = new Handler();
public TextView song_detail;
public TextView time1;
public TextView time2;
private String player_status = "playing";
private ImageButton player_img;
public static SeekBar seekBar;
private static MediaPlayer mediaPlayer;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
song_detail = findViewById(R.id.song_detail);
song_detail.setVisibility(View.GONE);
time1 = findViewById(R.id.time_1);
time2 = findViewById(R.id.time_2);
seekBar = findViewById(R.id.seekBar);
final Runnable mRunnable = new Runnable() {
#Override
public void run() {
if(mediaPlayer != null){
int CurrentPosition = mediaPlayer.getCurrentPosition();
String m_1;
String s_1;
seekBar.setProgress(CurrentPosition/1000);
final int minutes_1 = (CurrentPosition/1000)/60;
final int seconds_1 = ((CurrentPosition/1000)%60);
if (minutes_1 < 10) {
m_1 = "0" + minutes_1;
} else {
m_1 = "" + minutes_1;
}
if (seconds_1 < 10) {
s_1 = "0" + seconds_1;
} else {
s_1 = "" + seconds_1;
}
time1.setText(m_1 + ":" + s_1);
int Duration = mediaPlayer.getDuration();
String m_2;
String s_2;
final int minutes_2 = (Duration/1000)/60;
final int seconds_2 = ((Duration/1000)%60);
if (minutes_2 < 10) {
m_2 = "0" + minutes_2;
} else {
m_2 = "" + minutes_2;
}
if (seconds_2 < 10) {
s_2 = "0" + seconds_2;
} else {
s_2 = "" + seconds_2;
}
time2.setText(m_2 + ":" + s_2);
}
mHandler.postDelayed(this, 1000);
}
};
mRunnable.run();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser){
Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
});
seekBar.setMax(mediaPlayer.getDuration()/1000);
mediaPlayer.start();
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void pauseAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.pause();
}
}
public static void startAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.start();
}
}
}
This is the part of code that I'm using to work with mediaPlayer and seekBar
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser){
Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
But as I have said, instead of mediaPlayer seek and continue the audio from the position that I've clicked, the audio simply back to the start. What I'm doing wrong?
Thank you.
The max value for progress is 100. The seekTo function takes time in milliseconds. This is why it seeks to the start (almost) of the audio.
So instead of mediaPlayer.seekTo(progress);, you need to do:
long newTime = (progress/100.0) * total_audio_duration_in_millisecond;
mediaPlayer.seekTo(newTime);

app is crashing because of an Activity invokation

I'm trying to invoke an activity from the MainActivity via a button with OnClickListener
The first activity is responding and works, the second activity doesn't work and crashes the application
Please help me to find the solution
Thanks!!!
here is the code:
class Layout{
public Layout(){
btnStopWatch = (Button)findViewById(R.id.btnStopWatch);
btnTimer = (Button)findViewById(R.id.btnTimer);
}
Button btnStopWatch, btnTimer;
}
class Event{
public Event(){
l.btnStopWatch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), StopWatchActivity.class);
startActivity(i);
}
});
l.btnTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), TimerActivity.class);
startActivity(i);
}
});
}
}
Layout l; Event e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = new Layout(); e = new Event();
}}
First Activity that works:
public class StopWatchActivity extends AppCompatActivity {
class Layout{
public Layout(){
tvHours = (TextView)findViewById(R.id.tvHours);
tvMinutes = (TextView)findViewById(R.id.tvMinutes);
tvSeconds = (TextView)findViewById(R.id.tvSeconds);
tvBack = (TextView)findViewById(R.id.tvBack);
btnStartStop = (Button)findViewById(R.id.btnStartStop);
btnReset = (Button)findViewById(R.id.btnReset);
}
TextView tvHours, tvMinutes, tvSeconds, tvBack;
Button btnStartStop, btnReset;
}
class Event{
public Event(){
l.btnStartStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isStarted){
Stop();
}else {
Start();
}
}
});
l.btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Reset();
}
});
l.tvBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
}
Layout l; Event e;
boolean isStarted = false;
int sec = 0, min = 0, hour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stop_watch);
l = new Layout(); e = new Event();
}
public void Start(){
l.btnStartStop.setText("Stop");
isStarted = true;
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (isStarted){
try{
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(isStarted){
MoveTime();
}
}
});
}catch (InterruptedException e){
}
}
}
});
t.start();
}
public void MoveTime(){
sec++;
if (sec >= 59){
sec = 0;
min++;
if(min >= 59){
min = 0;
hour++;
}
}
UpdateScreen();
}
public void UpdateScreen(){
l.tvHours.setText(Format(hour));
l.tvMinutes.setText(Format(min));
l.tvSeconds.setText(Format(sec));
}
public void CleanScreen(){
l.tvHours.setText("00");
l.tvMinutes.setText("00");
l.tvSeconds.setText("00");
}
public String Format(int i){
if (i<=9){
return "0" + i;
}else{
return Integer.toString(i);
}
}
public void Stop(){
isStarted = false;
l.btnStartStop.setText("Start");
}
public void Reset(){
if(isStarted)
Stop();
CleanScreen();
sec = 0;
min = 0;
hour = 0;
}}
second activity that doesn't work:
public class TimerActivity extends AppCompatActivity {
class Layout {
public Layout() {
etHour = (EditText) findViewById(R.id.etHour);
etHour.setFilters(new InputFilter[]{new InputFilterMinMax("0", "24")});
etMin = (EditText) findViewById(R.id.etMin);
etMin.setFilters(new InputFilter[]{new InputFilterMinMax("0", "59")});
etSec = (EditText) findViewById(R.id.etSec);
etSec.setFilters(new InputFilter[]{new InputFilterMinMax("0", "59")});
btnStartStop = (Button) findViewById(R.id.btnStartStop);
btnReset = (Button) findViewById(R.id.btnReset);
tvBack1 = (TextView)findViewById(R.id.tvBack);
}
EditText etHour, etMin, etSec;
Button btnStartStop, btnReset;
TextView tvBack1;
}
class Event {
public Event() {
l.btnStartStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isStarted) {
Stop();
} else {
Start();
}
}
});
l.btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Reset();
}
});
l.tvBack1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
}
Layout l;
Event e;
boolean isStarted = false;
int sec = 0, min = 0, hour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
l = new Layout();
e = new Event();
}
public void Start() {
l.btnStartStop.setText("Stop");
isStarted = true;
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (isStarted) {
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (isStarted) {
MoveTime();
}
}
});
} catch (InterruptedException e) {
}
}
}
});
t.start();
}
public void MoveTime() {
sec = Integer.valueOf(l.etSec.getText().toString());
min = Integer.valueOf(l.etMin.getText().toString());
hour = Integer.valueOf(l.etHour.getText().toString());
sec--;
if (sec < 0) {
sec = 59;
min--;
if (min < 0) {
min = 59;
hour--;
}
}
UpdateScreen();
if (hour == 0) {
if (min == 0) {
if (sec == 0) {
Stop();
}
}
}
}
public void UpdateScreen(){
l.etHour.setText(Format(hour));
l.etMin.setText(Format(min));
l.etSec.setText(Format(sec));
}
public void CleanScreen(){
l.etHour.setText("00");
l.etMin.setText("00");
l.etSec.setText("00");
}
public String Format(int i){
if (i<=9){
return "0" + i;
}else{
return Integer.toString(i);
}
}
public void Stop(){
isStarted = false;
l.btnStartStop.setText("Start");
}
public void Reset(){
if(isStarted)
Stop();
CleanScreen();
sec = 0;
min = 0;
hour = 0;
}}

setOnTouchListener issue

I have added a timer to my game but by doing so i keep getting the error "The method setOnTouchListener(View.OnTouchListener) in the type View is not applicable for the arguments (scene5.MyCountDownTimer)" I can not seem to fix it. This might just be me making a simple mistake but any solutions would be great. The error is about halfway down my code, I have tagged it with //THIS IS MY PROBLEM AREA!! Cheers guys
public class scene5 extends Activity implements OnClickListener {
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView text;
private final long startTime = 20 * 1000;
private final long interval = 1 * 1000;
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("FindIt")
.setMessage("Exit to main menu?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level5);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime/1000));
}
#Override
public void onClick(View v) {
startB.setVisibility(View.INVISIBLE);
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("RESTART");
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Intent intent = new Intent(scene5.this, timeUp.class);
scene5.this.startActivity(intent);
finish();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished/1000);
}
{
ImageView iv = (ImageView) findViewById (R.id.image);
if (iv != null) {
iv.setOnTouchListener (this); //THIS IS MY PROBLEM AREA!!
}
toast ("20 seconds to find IT!");}
}
public boolean onTouch (View v, MotionEvent ev)
{
boolean handledHere = false;
final int action = ev.getAction();
final int evX = (int) ev.getX();
final int evY = (int) ev.getY();
int nextImage = -1;
ImageView imageView = (ImageView) v.findViewById (R.id.image);
if (imageView == null) return false;
Integer tagNum = (Integer) imageView.getTag ();
int currentResource = (tagNum == null) ? R.drawable.levels : tagNum.intValue ();
switch (action) {
case MotionEvent.ACTION_DOWN :
if (currentResource == R.drawable.levels) {
nextImage = R.drawable.wrong5;
handledHere = true;
} else handledHere = true;
break;
case MotionEvent.ACTION_UP :
int touchColor = getHotspotColor (R.id.image_areas, evX, evY);
ColorTool ct = new ColorTool ();
int tolerance = 25;
nextImage = R.drawable.levels;
if (ct.closeMatch (Color.RED, touchColor, tolerance)){
Intent intent = new Intent(scene5.this, LevelComplete.class);
scene5.this.startActivity(intent);
}
if (currentResource == nextImage) {
nextImage = R.drawable.levels;
}
handledHere = true;
break;
default:
handledHere = false;
}
if (handledHere) {
if (nextImage > 0) {
imageView.setImageResource (nextImage);
imageView.setTag (nextImage);
}
}
return handledHere;
}
public int getHotspotColor (int hotspotId, int x, int y) {
ImageView img = (ImageView) findViewById (hotspotId);
if (img == null) {
Log.d ("ImageAreasActivity", "Hot spot image not found");
return 0;
} else {
img.setDrawingCacheEnabled(true);
Bitmap hotspots = Bitmap.createBitmap(img.getDrawingCache());
if (hotspots == null) {
Log.d ("ImageAreasActivity", "Hot spot bitmap was not created");
return 0;
} else {
img.setDrawingCacheEnabled(false);
return hotspots.getPixel(x, y);
}
}
}
public void toast (String msg)
{
Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_LONG).show ();
}
}
Your problem is here:
public class scene5 extends Activity implements OnClickListener, OnTouchListener {
...
#Override
public boolean onTouch(View v, MotionEvent event) {
...
}
}
You have to implements also OnTouchListener.
Use
scene5.this
instead of this
the problem is iv.setOnTouchListener (this);
the this context you are passing belongs to the timer task, You need to use iv.setOnTouchListener (scene5.this);
Also, I think you need to find the ImageView reference in the onCreate itself. What you are doing currently ImageView iv = (ImageView) findViewById (R.id.image); won't work.

Categories

Resources