Cant access the time in AsyncTask, the variable point doesn't change anymore
Here is my code:
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class GamePlayActivity extends Activity {
ArrayList<Player> arrPlayer = new ArrayList<Player>();
TextView tvLevel, tvPoint;
ImageView ivGuessedImage;
Button btn1stChoice, btn2ndChoice, btn3rdChoice, btn4thChoice;
int level = 1;
int point = 0;
Random rand = new Random(System.currentTimeMillis());
ProgressBar customProgress;
TextView progressDisplay;
int myProgress;
MediaPlayer mp1, mp2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_gameplayactivity);
mp1 = MediaPlayer.create(GamePlayActivity.this, R.raw.uefa_champion_league);
mp2 = MediaPlayer.create(GamePlayActivity.this, R.raw.the_time_of_our_life);
mp1.start();
mp1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp2.start();
}
});
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp1.start();
}
});
tvLevel = (TextView) findViewById(R.id.tvLevel);
tvPoint = (TextView) findViewById(R.id.tvPoint);
ivGuessedImage = (ImageView) findViewById(R.id.ivGuessedImage);
btn1stChoice = (Button) findViewById(R.id.btn1stChoice);
btn2ndChoice = (Button) findViewById(R.id.btn2ndChoice);
btn3rdChoice = (Button) findViewById(R.id.btn3rdChoice);
btn4thChoice = (Button) findViewById(R.id.btn4thChoice);
arrPlayer = createPlayer();
Collections.shuffle(arrPlayer);
int resID = getResources().getIdentifier(arrPlayer.get(0).getPlayerFile(), "drawable", getPackageName());
ivGuessedImage.setImageResource(resID);
btn1stChoice.setText(arrPlayer.get(0).getPlayerName());
btn2ndChoice.setText(arrPlayer.get(1).getPlayerName());
btn3rdChoice.setText(arrPlayer.get(2).getPlayerName());
btn4thChoice.setText(arrPlayer.get(3).getPlayerName());
customProgress = (ProgressBar)findViewById(R.id.customProgress);
progressDisplay = (TextView)findViewById(R.id.progressDisplay);
new ShowCustomProgressBarAsyncTask().execute();
if(myProgress < 1){
Intent intent = new Intent(GamePlayActivity.this, GameOverActivity.class);
startActivity(intent);
}
btn1stChoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btn1stChoice.getText().toString() == arrPlayer.get(0).getPlayerName()) {
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.right_answer);
mp.start();
point = point + 2;
tvPoint.setText(point + " Point");
createNewLevel();
myProgress = 100;
} else {
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.wrong_answer);
mp.start();
Intent intent = new Intent(GamePlayActivity.this, GameOverActivity.class);
intent.putExtra("Point", point);
startActivity(intent);
}
}
});
btn2ndChoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(btn2ndChoice.getText().toString() == arrPlayer.get(0).getPlayerName()){
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.right_answer);
mp.start();
point = point + 2;
tvPoint.setText(point + " Point");
createNewLevel();
myProgress = 100;
}
else{
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.wrong_answer);
mp.start();
Intent intent = new Intent(GamePlayActivity.this, GameOverActivity.class);
intent.putExtra("Point", point);
startActivity(intent);
}
}
});
btn3rdChoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(btn3rdChoice.getText().toString() == arrPlayer.get(0).getPlayerName()){
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.right_answer);
mp.start();
point = point + 2;
tvPoint.setText(point + " Point");
createNewLevel();
myProgress = 100;
}
else{
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.wrong_answer);
mp.start();
Intent intent = new Intent(GamePlayActivity.this, GameOverActivity.class);
intent.putExtra("Point", point);
startActivity(intent);
}
}
});
btn4thChoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(btn4thChoice.getText().toString() == arrPlayer.get(0).getPlayerName()){
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.right_answer);
mp.start();
point = point + 2;
tvPoint.setText(point + " Point");
createNewLevel();
myProgress = 100;
}
else{
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.wrong_answer);
mp.start();
Intent intent = new Intent(GamePlayActivity.this, GameOverActivity.class);
intent.putExtra("Point", point);
startActivity(intent);
}
}
});
}
public class ShowCustomProgressBarAsyncTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
myProgress = 100;
}
#Override
protected Void doInBackground(Void... params) {
while(myProgress>0){
myProgress--;
publishProgress(myProgress);
SystemClock.sleep(200);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
customProgress.setProgress(values[0]);
customProgress.setSecondaryProgress(values[0] + 1);
progressDisplay.setText(String.valueOf(myProgress)+"%");
}
#Override
protected void onPostExecute(Void result) {
}
}
public void createNewLevel(){
arrPlayer.remove(0);
Collections.shuffle(arrPlayer);
int randomButtonChoice = rand.nextInt(4);
int resID = getResources().getIdentifier(arrPlayer.get(0).getPlayerFile(), "drawable", getPackageName());
((BitmapDrawable)ivGuessedImage.getDrawable()).getBitmap().recycle();
ivGuessedImage.setImageResource(resID);
switch (randomButtonChoice){
case 0: {
btn1stChoice.setText(arrPlayer.get(0).getPlayerName());
btn2ndChoice.setText(arrPlayer.get(1).getPlayerName());
btn3rdChoice.setText(arrPlayer.get(2).getPlayerName());
btn4thChoice.setText(arrPlayer.get(3).getPlayerName());
break;
}
case 1: {
btn1stChoice.setText(arrPlayer.get(1).getPlayerName());
btn2ndChoice.setText(arrPlayer.get(0).getPlayerName());
btn3rdChoice.setText(arrPlayer.get(2).getPlayerName());
btn4thChoice.setText(arrPlayer.get(3).getPlayerName());
break;
}
case 2: {
btn1stChoice.setText(arrPlayer.get(1).getPlayerName());
btn2ndChoice.setText(arrPlayer.get(2).getPlayerName());
btn3rdChoice.setText(arrPlayer.get(0).getPlayerName());
btn4thChoice.setText(arrPlayer.get(3).getPlayerName());
break;
}
case 3: {
btn1stChoice.setText(arrPlayer.get(1).getPlayerName());
btn2ndChoice.setText(arrPlayer.get(2).getPlayerName());
btn3rdChoice.setText(arrPlayer.get(3).getPlayerName());
btn4thChoice.setText(arrPlayer.get(0).getPlayerName());
break;
}
}
level++;
tvLevel.setText("Level " + level);
}
}
}
You could do that with an interface
create an interface in your AsyncTask, and create a method which will be used as the callback
public class ShowCustomProgressBarAsyncTask extends AsyncTask<Void, Integer, Void> {
interface ProgressListner {
public void onProgressChanged(int progress);
}
private ProgressListner listner;
public ShowCustomProgressBarAsyncTask(ProgressListner listner) {
this.listner = listner;
}
//..your remaining codes
#Override
protected void onProgressUpdate(Integer... values) {
//..your remaining codes
listner.onProgressChanged(values[0]);
}
}
Then implement that interface in your activity.
Also pass an instance of the interface through the constructor to the AsyncTask.
Then using that instance you can callback a method which will pass the progress value
public class GamePlayActivity extends Activity implements ProgressListner{
//.. your remaining codes
new ShowCustomProgressBarAsyncTask(this).execute();
public void onProgressChanged(int progress) {
a = progress;
}
}
Related
I code a simple music player. all works fine but when I click next button the max value of seekbar becomes the previous track's duration.though Player is working fine and music is being streamed fine but I am having trouble in setting the seekbar to work. I am assuming that seekbar is directly related to getting correct duration through getDuration. how can I solve this?
Here is my code:
public class PlayerActivity extends AppCompatActivity {
AppCompatButton playbtn, pausebtn, nxtbtn, prevbtn, fastfrwrdbtn, rewindbtn;
TextView txtStrt, txtStop, txtSnName;
SeekBar musicSeek;
BarVisualizer barVisualizer;
String sname;
static MediaPlayer mediaPlayer;
int position;
ArrayList mySongs, mySongUri, mySongAlbumArtUri;
ImageView imageView;
Thread updateSeek;
String currentTime;
AudioManager mAudioManager;
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
if (barVisualizer != null) {
barVisualizer.release();
}
super.onDestroy();
}
int ii = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setTitle("Now Playing");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
playbtn = findViewById(R.id.playBtn);
nxtbtn = findViewById(R.id.nxtBtn);
prevbtn = findViewById(R.id.previousBtn);
fastfrwrdbtn = findViewById(R.id.forwardBtn);
rewindbtn = findViewById(R.id.rewaindBtn);
mAudioManager = null;
txtStrt = findViewById(R.id.txtstart);
txtStop = findViewById(R.id.txtend);
txtSnName = findViewById(R.id.txtsn);
musicSeek = findViewById(R.id.seekbar);
barVisualizer = findViewById(R.id.blast);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
Intent i = getIntent();
Bundle bundle = i.getExtras();
mySongs = (ArrayList) bundle.getParcelableArrayList("songs");
mySongUri = (ArrayList) bundle.getParcelableArrayList("uri");
mySongAlbumArtUri = (ArrayList) bundle.getParcelableArrayList("uriArt");
String songName = i.getStringExtra("songName");
position = bundle.getInt("position", 0);
txtSnName.setSelected(true);
Uri uri = Uri.parse(mySongUri.get(position).toString());
getSupportActionBar().setTitle(songName);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
sname = mySongs.get(position).toString();
txtSnName.setText(sname);
imageView = findViewById(R.id.imageView);
//imageView.setImageURI(uriart);
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
String endTime = creatTime(mediaPlayer.getDuration());
txtStop.setText(endTime);
int audioSessionId = mediaPlayer.getAudioSessionId();
if (audioSessionId != -1) {
barVisualizer.setAudioSessionId(audioSessionId);
}
threading();
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime = creatTime(mediaPlayer.getCurrentPosition());
txtStrt.setText(currentTime);
handler.postDelayed(this, delay);
}
}, delay);
setUpdateSeek();
nxt();
prev();
playbtn.setOnClickListener(v -> {
if (mediaPlayer.isPlaying()) {
playbtn.setBackgroundResource(R.drawable.ic_play_button);
mediaPlayer.pause();
} else {
playbtn.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
});
fastfrwrdbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 10000);
}
}
});
rewindbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 10000);
}
}
});
countinue();
}
public void startAnimation(View view) {
ObjectAnimator animator = ObjectAnimator.ofFloat(imageView, "rotation", 0f, 360);
animator.setDuration(1000);
AnimatorSet animationSet = new AnimatorSet();
animationSet.playTogether(animator);
animationSet.start();
}
public void startAnimationBack(View view) {
ObjectAnimator animator = ObjectAnimator.ofFloat(imageView, "rotation", 360, 0f);
animator.setDuration(1000);
AnimatorSet animationSet = new AnimatorSet();
animationSet.playTogether(animator);
animationSet.start();
}
public String creatTime(int duration) {
String time = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
time += min + ":";
if (sec < 10) {
time += "0";
}
time += sec;
return time;
}
public void setUpdateSeek() {
updateSeek.start();
musicSeek.setMax(mediaPlayer.getDuration());
musicSeek.getProgressDrawable().setColorFilter(getResources().getColor(R.color.black), PorterDuff.Mode.MULTIPLY);
musicSeek.getThumb().setColorFilter(getResources().getColor(R.color.black), PorterDuff.Mode.SRC_IN);
musicSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser){
mediaPlayer.seekTo(position);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
seekBar.setMax(mediaPlayer.getDuration());
}
});
}
#Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
public void countinue() {
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
nxtbtn.performClick();
//musicSeek.setMax(mediaPlayer.getDuration());
}
});
}
public void nxt() {
nxtbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
position = ((position + 1) % mySongs.size());
Uri u = Uri.parse(mySongUri.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
sname = mySongs.get(position).toString();
txtSnName.setText(sname);
String endTime1 = creatTime(mediaPlayer.getDuration());
txtStop.setText(endTime1);
playbtn.setBackgroundResource(R.drawable.ic_pause);
startAnimation(imageView);
int audioSessionId = mediaPlayer.getAudioSessionId();
if (audioSessionId != -1) {
barVisualizer.setAudioSessionId(audioSessionId);
}
musicSeek.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
countinue();
}
});
}
public void prev() {
prevbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
position = ((position + 1) < 0) ? (mySongs.size() - 1) : (position - 1);
Uri u = Uri.parse(mySongUri.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
int i = mediaPlayer.getDuration();
String c = Integer.toString(i);
Toast.makeText(PlayerActivity.this, c, Toast.LENGTH_SHORT).show();
musicSeek.setMax(i);
sname = mySongs.get(position).toString();
txtSnName.setText(sname);
String endTime12 = creatTime(mediaPlayer.getDuration());
txtStop.setText(endTime12);
playbtn.setBackgroundResource(R.drawable.ic_pause);
startAnimationBack(imageView);
int audioSessionId = mediaPlayer.getAudioSessionId();
if (audioSessionId != -1) {
barVisualizer.setAudioSessionId(audioSessionId);
}
musicSeek.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
countinue();
}
});
}
public void threading() {
updateSeek = new Thread() {
#Override
public void run() {
int totalDuration = mediaPlayer.getDuration();
int currentPosition = 0;
while (currentPosition < totalDuration) {
try {
sleep(500);
currentPosition = mediaPlayer.getCurrentPosition();
musicSeek.setProgress(currentPosition);
} catch (InterruptedException | IllegalStateException e) {
e.printStackTrace();
}
}
}
};
}
}
can anyone please guide me to solve the issue?
I'm calling the service MusicaFundo in Splashscreen.class and want to pause/play it in MainActivity.class.
I'm trying with a sendBroadcast but the service is not receiving the intent, I have created the BroadcastReceiver, MyServiceReceiver, inside MusicaFundo.class, is it wrong to do like this?
MainActivity.class
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
boolean musicaTocar = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent svc = new Intent (this, MusicaFundo.class);
TextView titulo = findViewById(R.id.titulo);
final ImageView som = findViewById(R.id.som);
som.setBackgroundResource(R.drawable.volumeup);
final ImageView jogomem = findViewById(R.id.jogomem);
jogomem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Animation diminuir = (Animation) AnimationUtils.loadAnimation(MainActivity.this, R.anim.diminuir);
jogomem.startAnimation(diminuir);
Intent jogomemoria = new Intent(MainActivity.this, JogoMemoria.class);
startActivity(jogomemoria);
}
});
Animation deslocarD = (Animation) AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
titulo.startAnimation(deslocarD);
som.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!musicaTocar){
som.setBackgroundResource(R.drawable.volumemut);
playMusica();
musicaTocar = true;
}
else {
if (musicaTocar){
som.setBackgroundResource(R.drawable.volumeup);
pausarMusica();
musicaTocar = false;
}
}
}
});
}
private void pausarMusica() {
Intent pausar = new Intent();
pausar.setAction("pausar");
sendBroadcast(pausar);
}
private void playMusica() {
Intent tocar = new Intent();
tocar.setAction("tocarmusica");
sendBroadcast(tocar);
}
Inside MusicaFundo.class
public class MusicaFundo extends Service {
private MediaPlayer player;
public int posatual = 0;
private static final String TAG = "MusicaFundo";
public static Object getName() {
return null;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
player = MediaPlayer.create(this, R.raw.musicafundo);
player.setLooping(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player.seekTo(posatual);
player.start();
return START_STICKY;
}
public boolean onUnbind(Intent intent){
return false;
}
#Override
public void onDestroy() {
super.onDestroy();
if (player != null) {
if (player.isPlaying()) {
player.stop();
}
player.release();
}
}
public void resumeMusic(){
if (player != null) {
if (player.isPlaying() == false) {
player.seekTo(posatual);
player.start();
}
}
}
public void onPause(){
if (player != null) {
if (player.isPlaying()) {
posatual = player.getCurrentPosition();
player.pause();
}
}
}
public class MyServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String pausa = intent.getAction();
if(pausa.equals("pausar")){
onPause();
Log.d(TAG, "onReceive: " + pausa);
}
else if(pausa.equals("tocarmusica")){
resumeMusic();
Log.d(TAG, "onReceive: " + pausa);
}
}
}
Want to receive intent so it compares the string to pause or play.
Not sure if the code is just not complete in the question but you need to call registerReceiver in your service for the receiver to actually receive broadcasts.
Also, if this is mostly communication within the same process, I suggest using LocarBroadcastManager as it is more efficient and secure.
I Want to create a timer which will run for 10 seconds. If the user have entered the correct answer the timer should restart. For that I have added cancel.countdowntimer(). But it's not working. The app crashes. Where should I use that countdowntimer.cancel() function? Should I use a method for countdowntimer.cancel()?
package com.example.vignesh.work;
import android.os.CountDownTimer;
import android.os.Handler;
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.TextView;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button b1;
int loc;
int total=0;
int mark=0;
Runnable run;
Handler handler;
CountDownTimer countDownTimer;
TextView textView4,textView2,textView1,textView3;
Button b11,b22,b33,b44;
Random random = new Random();
ArrayList<Integer> answers = new ArrayList<Integer>();
public void nextQuestion() {
new CountDownTimer(10000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
textView3.setText(Long.toString(millisUntilFinished / 1000));
}
#Override
public void onFinish() {
textView3.setText("10");
}
}.start();
int a = random.nextInt(20) + 1;
int b = random.nextInt(20) + 1;
textView1.setText(Integer.toString(a) + "+" + Integer.toString(b));
loc = random.nextInt(4);
answers.clear();
for (int i = 0; i < 4; i++) {
if (i == loc) {
answers.add(a + b);
} else {
answers.add((a + b) + random.nextInt(10) + 1);
}
}
b11.setText(Integer.toString(answers.get(0)));
b22.setText(Integer.toString(answers.get(1)));
b33.setText(Integer.toString(answers.get(2)));
b44.setText(Integer.toString(answers.get(3)));
}
public void choose(View view)
{
if(view.getTag().toString().equals(Integer.toString(loc+1)))
{
textView4.setText("Correct");
mark++;
}
else
{
textView4.setText("Wrong");
}
total++;
try {
countDownTimer.cancel();
}
catch (Exception e)
{
Log.i("error",e.getMessage());
}
nextQuestion();
textView2.setText(Integer.toString(mark)+"/"+Integer.toString(total));
}
public void click(View view)
{
b1.setVisibility(view.INVISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.buttongo);
b11 = (Button)findViewById(R.id.optiona);
b22 = (Button)findViewById(R.id.optionb);
b33 = (Button)findViewById(R.id.option3);
b44 = (Button)findViewById(R.id.option4);
textView1=(TextView)findViewById(R.id.textView1);
textView2=(TextView)findViewById(R.id.textView2);
textView3=(TextView)findViewById(R.id.textView3);
textView4=(TextView)findViewById(R.id.textView4);
nextQuestion();
}
}
**AFTER ADDING EXCEPTIONAL HANDLING THE ERROR WAS:Attempt to invoke virtual method 'void android.os.CountDownTimer.cancel()' on a null object reference**
Thanks.
You instantiate your CountDownTimer in nextQuestion() method, however you do not assign it in the countDownTimer variable defined in the top of your class: CountDownTimer countDownTimer;
Change the code inside nextQuestion() method to:
countDownTimer = new CountDownTimer(10000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
textView3.setText(Long.toString(millisUntilFinished / 1000));
}
#Override
public void onFinish() {
textView3.setText("10");
}
};
countDownTimer.start();
Note that I am assigning the new CountDownTimer to countDownTimer variable and then start the timer by calling countDownTimer.start();.
Then check if countDownTimer is null before calling it to cancel:
if(countDownTimer != null) {
countDownTimer.cancel();
}
You are not initialising countDownTimer variable update your method like below and also check null before calling countDownTimer.cancel();
public void nextQuestion() {
countDownTimer = new CountDownTimer(10000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
textView3.setText(Long.toString(millisUntilFinished / 1000));
}
#Override
public void onFinish() {
textView3.setText("10");
}
}.start();
int a = random.nextInt(20) + 1;
int b = random.nextInt(20) + 1;
textView1.setText(Integer.toString(a) + "+" + Integer.toString(b));
loc = random.nextInt(4);
answers.clear();
for (int i = 0; i < 4; i++) {
if (i == loc) {
answers.add(a + b);
} else {
answers.add((a + b) + random.nextInt(10) + 1);
}
}
b11.setText(Integer.toString(answers.get(0)));
b22.setText(Integer.toString(answers.get(1)));
b33.setText(Integer.toString(answers.get(2)));
b44.setText(Integer.toString(answers.get(3)));
}
In my code, I have implemented the sliding layouts. I have a front page which runs a video, while the user interaction is being done with layouts sliding up and down. Here's the code:
package org.udoo.androidadkdemobidirect;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.VideoView;
import java.io.DataOutputStream;
import java.io.IOException;
//import org.udoo.androidadkdemobidirect.sAdkManager;
public class MainActivity extends Activity{
// private static final String TAG = "UDOO_AndroidADKFULL";
private static String mAdkManager=null;
private VideoView myVideoView;
private MediaController mediaControls=null;
private int position = 0;
private String ppm_val=null;
private ToggleButton buttonLED;
private TextView distance;
private Button res_nextBtn;
private TextView res_tv;
private AdkReadTask mAdkReadTask;
private int myInt = -10;
private TextView tv;
private FrameLayout current=null;
private Animation slide_down;
private Animation slide_up;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
//hideNavigationBar();
buttonLED = (ToggleButton) findViewById(R.id.toggleButtonLed);
distance = (TextView) findViewById(R.id.textViewIntro);
buttonLED.setVisibility(View.INVISIBLE);
tv = (TextView) findViewById(R.id.ppm_unique);
if (mediaControls == null) {
mediaControls = new MediaController(this);
}
slide_down = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.slide_down);
slide_up = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.slide_up);
res_nextBtn = (Button) findViewById(R.id.result_next_btn);
res_tv = (TextView) findViewById(R.id.result_number_text);
myVideoView = (VideoView) findViewById(R.id.videoView);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
myVideoView.getHolder().setFixedSize(size.x, size.y);
tv.setText(""+size.x+":"+size.y);
final Animation animation1 = new AlphaAnimation(0.0f, 1.0f);
animation1.setDuration(1000);
animation1.setStartOffset(000);
final Animation animation2 = new AlphaAnimation(1.0f, 0.0f);
animation2.setDuration(1000);
animation2.setStartOffset(500);
//animation1 AnimationListener
animation1.setAnimationListener(new Animation.AnimationListener(){
#Override
public void onAnimationEnd(Animation arg0) {
// start animation2 when animation1 ends (continue)
distance.startAnimation(animation2);
}
#Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated method stub
}
});
//animation2 AnimationListener
animation2.setAnimationListener(new Animation.AnimationListener(){
#Override
public void onAnimationEnd(Animation arg0) {
// start animation1 when animation2 ends (repeat)
distance.startAnimation(animation1);
}
#Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated method stub
}
});
distance.startAnimation(animation1);
try {
myVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound_758));
} catch (Exception e) {
}
// myVideoView.requestFocus();
//we also set an setOnPreparedListener in order to know when the video file is ready for playback
myVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
// close the progress bar and play the video
//progressDialog.dismiss();
//if we have a position on savedInstanceState, the video playback should start from here
mediaPlayer.setLooping(true);
myVideoView.seekTo(position);
if (position == 0) {
myVideoView.start();
} else {
//if we come from a resumed activity, video playback will be paused
myVideoView.pause();
}
}
});
((MyApplication) this.getApplication()).init(this);
((MyApplication) this.getApplication()).open();
if (mAdkReadTask==null) {
mAdkReadTask = new AdkReadTask();
mAdkReadTask.execute();
}
}
/************************************************************************************************
* *
* OnClickEvents *
* *
************************************************************************************************/
public void BR_onBuyClick(View view) {
next((FrameLayout) findViewById(R.id.flavours_inc_layout));
}
public void Flavours_onBackClick(View v){
next((FrameLayout) findViewById(R.id.br_inc_layout));
}
public void Flavours_onF1Click(View view) {
next((FrameLayout) findViewById(R.id.ty_inc_layout));
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
home();
}
},
5000);
}
public void Flavours_onF2Click(View view) {
next((FrameLayout) findViewById(R.id.ty_inc_layout));
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
home();
}
},
5000);
}
public void Flavours_onF3Click(View view) {
next((FrameLayout) findViewById(R.id.ty_inc_layout));
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
home();
}
},
5000);
}
private void home() {
current.startAnimation(slide_down);
current.setVisibility(View.INVISIBLE);
current=null;
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
distance.startAnimation(slide_up);
distance.setVisibility(View.VISIBLE);
final Animation animation1 = new AlphaAnimation(0.0f, 1.0f);
animation1.setDuration(1000);
animation1.setStartOffset(000);
final Animation animation2 = new AlphaAnimation(1.0f, 0.0f);
animation2.setDuration(1000);
animation2.setStartOffset(500);
//animation1 AnimationListener
animation1.setAnimationListener(new Animation.AnimationListener(){
#Override
public void onAnimationEnd(Animation arg0) {
// start animation2 when animation1 ends (continue)
distance.startAnimation(animation2);
}
#Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated method stub
}
});
//animation2 AnimationListener
animation2.setAnimationListener(new Animation.AnimationListener(){
#Override
public void onAnimationEnd(Animation arg0) {
// start animation1 when animation2 ends (repeat)
distance.startAnimation(animation1);
}
#Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated method stub
}
});
distance.startAnimation(animation1);
((MyApplication) getApplication()).write("1");
}
},
1000);
}
public void BR_onRecycleClick(View view) {
next((FrameLayout) findViewById(R.id.ready_inc_layout));
}
public void proc_onDoneClick(View v){
next((FrameLayout) findViewById(R.id.delay_inc_layout));
onDelay();
}
public void proc_onCancelClick(View v){
next((FrameLayout) findViewById(R.id.br_inc_layout));
}
private void onDelay() {
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.delay_progressBar);
progressBar.setProgress(0);
progressBar.setVisibility(View.VISIBLE);
ValueAnimator animator = new ValueAnimator();
animator.setObjectValues(0, 100);
animator.setDuration(7000);
final TextView tv = (TextView) findViewById(R.id.delay_textPoints);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
tv.setText("" + animation.getAnimatedValue() +"%");
}
});
animator.addListener(new AnimatorListenerAdapter(){
#Override
public void onAnimationEnd(Animator animator) {
progressBar.setVisibility(View.INVISIBLE);
((MyApplication) getApplication()).write("4");
next((FrameLayout) findViewById(R.id.result_inc_layout));
((MyApplication) getApplication()).write("8");
res_nextBtn.setVisibility(View.INVISIBLE);
}
});
animator.start();
}
public void Res_onNextClick(View v){
next((FrameLayout) findViewById(R.id.points_inc_layout));
onPoints();
}
private void onPoints() {
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.points_progressBar);
progressBar.setProgress(0);
progressBar.setVisibility(View.VISIBLE);
final ValueAnimator animator = new ValueAnimator();
if (myInt>=0) {
animator.setObjectValues(0, (myInt) * 5);
}
else{
animator.setObjectValues(0, 1);
}
animator.setDuration(2000);
final TextView tv = (TextView) findViewById(R.id.points_textPoints);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
tv.setText("" + animation.getAnimatedValue());
}
});
animator.addListener(new AnimatorListenerAdapter(){
#Override
public void onAnimationEnd(Animator animator) {
progressBar.setVisibility(View.INVISIBLE);
}
});
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
animator.start();
}
},
1500);
}
public void pts_onConfirmClick(View v){
next((FrameLayout) findViewById(R.id.end_inc_layout));
((MyApplication) getApplication()).write("3");
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
home();
}
},
5000);
}
public void Ready_onYesClick(View v){
((MyApplication) this.getApplication()).write("2");
next((FrameLayout) findViewById(R.id.processing_inc_layout));
onProcessing();
}
private void onProcessing() {
final int[] i = {0};
final int[] drawablearray = new int[]{R.drawable.processing_butts_3, R.drawable.processing_butts_2, R.drawable.processing_butts_1, R.drawable.processing_butts_0};
final ImageView backgroundImageView = (ImageView) findViewById(R.id.processing_textButts);
backgroundImageView.postDelayed(new Runnable() {
public void run() {
backgroundImageView.setImageResource(drawablearray[i[0]++ % drawablearray.length]);
backgroundImageView.postDelayed(this, 1000);
}
}, 1500);
}
public void Ready_onCancelClick(View v){
next((FrameLayout) findViewById(R.id.br_inc_layout));
}
#Override
public void onResume() {
super.onResume();
((MyApplication) this.getApplication()).write("1");
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void hideNavigationBar() {
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
/*
enable = enable navigation bar
disable = disable navigation bar
*/
os.writeBytes("pm enable com.android.systemui\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
process.waitFor();
//////////////////////////////////////
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String output="";
/*
* We put the readSerial() method in an AsyncTask to run the
* continuous read task out of the UI main thread
*/
private class AdkReadTask extends AsyncTask<Void, String, String> {
private boolean running = true;
public void pause(){
running = false;
}
public void start(){
running = true;
}
#Override
protected String doInBackground(Void... params) {
while(running) {
if (this.isCancelled())
break;
String s = ((MyApplication) getApplication()).read();
publishProgress(s);
}
return output;
}
#Override
protected void onProgressUpdate(String... progress) {
if(progress[0].charAt(0)=='P') {
/*
TODO: change text+ppm_val to image+text
TODO: send ppm values to server
*/
tv.setText("Air quality: " + progress[0].substring(1, progress[0].length()));
ppm_val = progress[0].substring(1, progress[0].length());
((MyApplication) getApplication()).setPPM(ppm_val);
}
else if (progress[0].charAt(0)=='R'){
/*
TODO: add server verification of RFID
*/
distance.startAnimation(slide_down);
distance.setVisibility(View.GONE);
next((FrameLayout) findViewById(R.id.br_inc_layout));
}
else if (progress[0].charAt(0)=='C'){
/*
TODO: send data to server
*/
res_tv.setText(""+(int) progress[0].charAt(1));
myInt = (int) progress[0].charAt(1);
res_nextBtn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onPostExecute(String result){
}
}
private void next(final FrameLayout fl) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) fl.getLayoutParams();
if (fl == (FrameLayout) findViewById(R.id.flavours_inc_layout)){
params.height = (int) (size.y*0.6);
}
else{
params.height = (int) (size.y*0.3);
}
params.width = size.x;
int delay_delta = 1000;
// Set it back.
fl.setLayoutParams(params);
if(current!=null){
current.startAnimation(slide_down);
current.setVisibility(View.INVISIBLE);
delay_delta=0;
}
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
fl.startAnimation(slide_up);
fl.setVisibility(View.VISIBLE);
current = fl;
}
},
1200-delay_delta);
}
}
And everything worked fine before I tried changing the slide-up height. After I set up a special case for a layout 0.6*y instead of 0.3*y. The layout is being not displayed above 0.3 mark. It does function, and when I click the supposed button place it displays just before sliding down.
Ok, it was solved by accident. I changed all View.INVISIBLE to View.GONE and it works like swiss watch. I guess there's some black magic involved and I would really appreciate (and accept the answer of course) if someone could explain to me why it works. Thanks.
I'm creating piano app but I got problem when i click on the button to play many times i can't hear sound when i click on the button again. After i click on the button many times all the sounds are not heard how to solve this problem?
public class Music_piano extends Activity {
Button btn_s_ddo,btn_s_re,btn_s_mi,btn_s_fa,btn_s_so,btn_s_la,btn_s_si,btn_ldo;
MediaPlayer mp = new MediaPlayer();
MediaPlayer mp1,mp2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_music_piano);
}
public void btn_sound_ddo(View v){
mp = MediaPlayer.create(this, R.raw.ddo);
mp.start();
}
public void btn_sound_re(View v){
mp = MediaPlayer.create(this, R.raw.re);
mp.start();
}
public void btn_sound_mi(View v){
mp = MediaPlayer.create(this, R.raw.mi);
mp.start();
}
public void btn_sound_fa(View v){
mp = MediaPlayer.create(this, R.raw.fa);
mp.start();
}
public void btn_sound_so(View v){
mp = MediaPlayer.create(this, R.raw.sol);
mp.start();
}
public void btn_sound_la(View v){
mp = MediaPlayer.create(this, R.raw.la);
mp.start();
}
public void btn_sound_si(View v){
mp = MediaPlayer.create(this, R.raw.si);
mp.start();
}
public void btn_sound_ldo(View v){
mp = MediaPlayer.create(this, R.raw.ddo_last);
mp.start();
}
}
Can you please try below code ? I have tried it, worked well for me.
Button btnOne = (Button)findViewById(R.id.btnOne);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mPlayer = MediaPlayer.create(TempActivity.this, R.raw.mysoundfile);
mPlayer.start();
}
});
Hope it will help you.
its better to create single instance of MediaPlayer and reuse it
MediaPlayer mMediaPlayer = new MediaPlayer(); // global variable
//write below code on buttons onclick method
AssetFileDescriptor assetFile = context.getAssets().openFd(audioFile);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(assetFile.getFileDescriptor(),
assetFile.getStartOffset(), assetFile.getLength());
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
I wrote a simple SoundManager class with a demo activity. No comment whatsoever as I think its pretty easy to read. Refer to SoundPool for details.
SoundManager class
package com.makeez.sfx;
import android.content.Context;
import android.media.SoundPool;
import java.util.HashMap;
import java.util.Map;
public class SoundManager {
private final Map<Integer, Integer> sfxId = new HashMap<>();
private SoundPool sfx;
public SoundManager(int maxStreams, int streamType, int srcQuality) {
sfx = new SoundPool(maxStreams, streamType, srcQuality);
}
public void load(Context context, int... resources) {
if (context == null) {
throw new NullPointerException("Context must not be null.");
}
if (resources == null) {
return;
}
for (int resource : resources) {
int soundId = sfx.load(context, resource, 1);
sfxId.put(resource, soundId);
}
}
public void play(int resId) {
Integer soundId = sfxId.get(resId);
if (soundId != null) {
sfx.play(soundId, 1.0f, 1.0f, 0, 0, 1.0f);
}
}
public void release() {
if (sfx != null) {
sfx.autoPause();
sfx.release();
sfx = null;
}
}
}
Demo activity
package com.makeez.sfx;
import android.media.AudioManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private SoundManager manager;
private int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = new SoundManager(1, AudioManager.STREAM_MUSIC, 0);
manager.load(this, R.raw.sfx_0001, R.raw.sfx_0002, R.raw.sfx_0003, R.raw.sfx_0004, R.raw.sfx_0005);
Button button = (Button) findViewById(R.id.play);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (position) {
case 0: manager.play(R.raw.sfx_0001); break;
case 1: manager.play(R.raw.sfx_0002); break;
case 2: manager.play(R.raw.sfx_0003); break;
case 3: manager.play(R.raw.sfx_0004); break;
case 4: manager.play(R.raw.sfx_0005); break;
}
if (++position >= 5) {
position = 0;
}
}
});
}
#Override
protected void onDestroy() {
manager.release();
super.onDestroy();
}
}