Android Java: Timer With CountDown

How To Shot It!!
  1. Create  a SeekBar to choose the time in seconds
  2. Update the time in minutes and seconds from the choosen SeekBar progress value
  3. Display time in proper format
  4. Set a CountDownTimer
    1. Starting point as choosen SeekBar progress and interval as 1 second
    2. Update display time on each tick
    3. Once complete, play a siren and reset the timer values
//"Create a SeekBar"
seekBar = (SeekBar) findViewById(R.id.seekBarId);
seekBar.setMax(600);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
timeUpdate(progress);
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

}
});
//"Display minutes and seconds in proper format"
public String timeDisplay(long number){
if(number <10) return "0"+String.valueOf(number) ;

else return String.valueOf(number);
}

//"Update time "
private void timeUpdate(int progress) {
minutes = progress/60;
seconds = progress%60;
timerValue.setText(timeDisplay(minutes) + ":" + timeDisplay(seconds), TextView.BufferType.NORMAL);

}

 

//"Button Onclick Function for start and stop timer"
public void timerOnClick(View view) throws InterruptedException {
//"On starting the timer"
if(!isTimerRunning) {
isTimerRunning = true;
seekBar.setEnabled(false);
buttonId.setText("Stop");
//"Set the timer"
timer = new CountDownTimer(seekBar.getProgress() * 1000, 1000) {

@Override
public void onTick(long millisUntilFinished) {
//"update time on each tick"
timeUpdate((int) (millisUntilFinished / 1000));
}

@Override
public void onFinish() {
//"play a siren on timer completion"
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.airhorn);
mediaPlayer.start();
//"reset the timer"
timerReset();
}
}.start();
}else{
//"On stopping the timer , reset the timer
timerReset();
}

}
//"Reset the timer"
private void timerReset() {
seekBar.setEnabled(true);
isTimerRunning = false;
buttonId.setText("Go");
timerValue.setText("00:00");
timer.cancel();
}

 

 

Happy Coding!!

Android Java : ListView With ArrayAdapter

 

How to shot It!
  1. Create a ListView
  2. Create an ArrayList of items to be displayed
  3. Create an ArrayAdapter inialized with the ArrayList
  4. Assign the ArrayAdaper to the ListView
  5. Use Listeners for grabbing items from the ListView
ListView myListView = findViewById(R.id.listView);

final ArrayList coffeeList =
        new ArrayList(asList("Mocha","Latte","Espresso"));

ArrayAdapter arrayAdapter =
        new ArrayAdapter(this,android.R.layout.simple_list_item_1,coffeeList);

myListView.setAdapter(arrayAdapter);

myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView adapterView, View view, int position, long id) {

        Toast.makeText(getApplicationContext(),"Get a " + coffeeList.get(position),Toast.LENGTH_SHORT).show();

    }
});

 

P.S

Updating ListView items

//"update the arraylist"
for(int index=0;index<coffeeList.size();++index){
coffeeList.set(index, cofeeList.get(index) +" Shots");
}
//"Reset the adapter to listview"
myListView.setAdapter(arrayAdapter);

}

Happy Coding!!

Android Java Animate : Fade In Fade Out

How To Shot It!
  1. Create an ImageView with the image to be animated
  2. Set the alpha attribute of the image with a value 0 (The image will disappear from the screen)
  3. Apply animation
    1. Bring back the image by setting alpha attribute value to 1 within 1 sec
    2. Fade Out the image by setting alpha back to 0 with setInterpolator()
ImageView logoImage = (ImageView) findViewById(R.id.imageViewId);
logoImage.animate().alpha(1).setDuration(1000).setInterpolator(new DecelerateInterpolator())
        .withEndAction(new Runnable() {
             @Override
                public void run() {
                       logoImage.animate().alpha(0).setDuration(1000);
                }
                }).start();

P.S Fade In Fade Out with alpha attribute doesn’t work with following code.

<del>ImageView logoImage = (ImageView) findViewById(R.id.imageViewId);
logoImage.animate().alpha(0).setDuration(1000).alpha(1).setDuration(1000);</del>

All animations applied with animate() happens all at a time. For executing different animations one after the other, setInterpolator() function is used , where a new thread is created with the runnable task of next animation code and executed right after the execution of previous animation.

Happy Coding!!

Android Java Animate : Translation and Rotation

 

View Animation Video

How To Shot It!
  1. Create an ImageView for the image to be animated
  2. Translate the image to far left
  3. Apply animation
    1. Bring back the image from left with rotation within 6secs
ImageView logoImage = (ImageView)findViewById(R.id.logoImageId);
logoImage.setX(-1000);
logoImage.animate().translationXBy(1000).rotation(3600).setDuration(6000);

Happy coding!!

Android Java: Play & Pause Sound With Volume And Scrub Seek Bar

 

 

Playing a sound file and including controlling options is not easy as playing a video file. Android Oreo doesn’t provide any MediaController instance for the purpose.

How To Shot It!
  1. Create a folder named “raw” (any name) under the resource folder(app->res->raw) and save the sound file. Save all required image files (play and pause image) under the drawable folder
  2. Create a MediaPlayer instance for the sound file
  3. Create an onClick() method named “play” for the play and pause image views
  4. Include a srub seek bar for progress control
  5. Create an AudioManger instance and seek bar for volume control
//"Create MediaPlayer instance"
mediaPlayer = MediaPlayer.create(this, R.raw.soundFileName);
boolean controlStatus = true;

//"onClick method play()"
public  void play(View view){
    ImageView controlButton= findViewById(R.id.controlButtonImageViewId);

//"if play is active change to pause"
    if(controlStatus){
        controlButton.setImageResource(R.drawable.pauseImageFileName);
        mediaPlayer.start();
        controlStatus = false;
    }
//"if pause is active change it to play"
    else{
        controlButton.setImageResource(R.drawable.playImageFileName);
        mediaPlayer.pause();
        controlStatus = true;
    }
}
//"Scrub Seek Bar for progress control"
final SeekBar scrubSeekBar  = (SeekBar) findViewById(R.id.scrubSeekBarId);

//"set the duration for seekbar to be the duration of sound file playing"
scrubSeekBar.setMax(mediaPlayer.getDuration());

//"set the actions on scrolling the seek bar"
scrubSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

@Override
//"Change the sound file progress to match the seek bar progress"
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
          mediaPlayer.seekTo(progress);
    }

    @Override
    //"Pause the sound while scrolling the seek bar"
    public void onStartTrackingTouch(SeekBar seekBar) {
         mediaPlayer.pause();

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mediaPlayer.start();

    }
});

//"set the seek bar progress in accordance to the sound play progress"
new Timer().scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        scrubSeekBar.setProgress(mediaPlayer.getCurrentPosition());
    }
},0,100);

 

//"Volume SeekBar"
//"Create an AudioManager instance for accessing the system audio"
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

//"grab system's max and current volume"
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

//"assign system volume to seekbar volume"
SeekBar volumeControl = (SeekBar) findViewById(R.id.volumeSeekBarId);
volumeControl.setMax(maxVolume);
volumeControl.setProgress(currentVolume);
volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

Log.i("seekbar changed" , Integer.toString(progress));
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,0);

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

}
});

Happy Coding!!

Android Java: Play Video

How To Shot It!
  1. Create a folder named “raw” (whatever name) under app->res folder and save the video file in it.
  2. Create a VideoView
  3. Assign the video file path
  4. Set a MediaController for play, pause, forward options
  5. Start the VideoView

VideoView videoView = (VideoView) findViewById(R.id.videoViewId);
videoView.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.videoFileName);
MediaController mediaController = new MediaController(this);
videoView.setMediaController(mediaController);
videoView.start();

P.S : if you come across any compiler error regarding raw folder, just ignore and build the app, the error should be corrected by that time.

Happy Coding!!