Simple Interest Calculator calculate button error - android

I am very new to Android development and have been trying to make a simple interest calculator. It uses a SeekBar to take the number of years input. The App crashes as I click the Calculate Button.
I am using Eclipse and trying to run the app directly on the device without any emulator.
package com.sevendaytutorials.interestcalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener, OnSeekBarChangeListener{
private EditText principal_amount;
private EditText rate;
private SeekBar seekbar;
private TextView seekBarValue;
private Button calculate;
private TextView result;
private String Principal, Rate;
private int number_of_years;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
principal_amount = (EditText)findViewById(R.id.principal_amount);
Principal = principal_amount.getText().toString();
rate = (EditText)findViewById(R.id.interest_rate);
Rate = rate.getText().toString();
seekbar = (SeekBar)findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener(this);
seekBarValue = (TextView) findViewById(R.id.number_of_years);
calculate = (Button) findViewById(R.id.calculate_button);
calculate.setOnClickListener(this);
result = (TextView) findViewById(R.id.result_textview);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == calculate) {
Calculate();
}
}
private void Calculate() {
// TODO Auto-generated method stub
double p = Double.parseDouble(Principal);
double R = Double.parseDouble(Rate);
double r = R/100.0;
double A = p*(1+r*number_of_years);
double I = A - p;
result.setText("The amount of interest after " +
Integer.toString(number_of_years)+" year(s) would be " + Double.toString(I));
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(Integer.toString(progress));
number_of_years = progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}

in your onCreate(), you did these-
Principal = principal_amount.getText().toString();
and
Rate = rate.getText().toString();
Now both of your values are null as nothing are typed during onCreate()
Now when are you calling Calculate(), you are doing these-
double p = Double.parseDouble(Principal);
double R = Double.parseDouble(Rate);
as we can see, you didn't assign any proper value to Principal & Rate yet anywhere, so you should get Exception at these lines. you should modify to-
private void Calculate() {
// TODO Auto-generated method stub
Principal = principal_amount.getText().toString();
Rate = rate.getText().toString();
if (Principal == null || Principal.isEmpty() || Rate == null || Rate .isEmpty())
{
// user are yet to fill the edittext, validation error
}else{
double p = Double.parseDouble(Principal);
double R = Double.parseDouble(Rate);
double r = R/100.0;
double A = p*(1+r*number_of_years);
double I = A - p;
result.setText("The amount of interest after " +
Integer.toString(number_of_years)+" year(s) would be " + Double.toString(I));
}
}

Local variables
SeekBar seek1, seek2, seek3;
float amount, rate, time, interest, total;
TextView tv1, tv2, tv3, tv4, tv5;
Button calculate;
String val, val1, val2, inter, totall;
In onCreate() find ids
seekBar1 = findViewById(R.id.seek1);
seekBar2 = findViewById(R.id.seek2);
seekBar3 = findViewById(R.id.seek3);
calculate = findViewById(R.id.calculate);
tvAmount = findViewById(R.id.tv1);
tvRate = findViewById(R.id.tv2);
tvtime = findViewById(R.id.tv3);
tvEMI = findViewById(R.id.tv4);
tvInterest = findViewById(R.id.tv5);
Apply setOnClickListener() on Button
calculate.setOnClickListener(this);
Apply setOnSeekBarChangeListener() using anonymous class and implement
all methods
seek1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
Get Value of SeekBar in String Variable and set on text view.
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
val = String.valueOf(1000 + i * 1000);
tv1.setText(val);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
});
seek2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
val1 = String.valueOf(5 + i * .5);
tv2.setText(val1);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
});
seek3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
val2 = String.valueOf(i);
tv3.setText(val2);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
});
Set maximum limit of Seek Bars
seek1.setMax(99);
seek2.setMax(30);
seek3.setMax(100);
Implement onClick() for button click Action
#Override
public void onClick(View view)
{
calInterest();
tv4.setText(": ₹"+inter);
tv5.setText(": ₹"+totall);
}
Create a method for calculation calInterest() which is called at time
of button Click see onClick()
public void calInterest()
{
amount = Float.parseFloat(val);
rate = Float.parseFloat(val1);
time = Float.parseFloat(val2);
interest = (amount * rate * (time / 12))/100;
total =interest+amount;
inter = String.valueOf(interest);
totall = String.valueOf(total);
}

Related

Stop Android CountDownTimmer when another button is pressed

So I designed an Android application about a year ago now in Android Studio to take care of some things at my college. However, I never "completely finished" it. The one thing that it is missing for me is when I click a button it starts a timer and outputs a string. However, if I press another button before that timer is up, it will say both at the same time. In looking online, I haven't found exactly what I was looking for so I thought I would open it up to the Stackoverflow community and maybe you can guide me in the right direction. Now for the code.
package com.example.james.texttospeech;
import android.os.Bundle;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
import android.widget.EditText;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.content.Intent;
import java.util.Locale;
import android.widget.Toast;
import android.os.CountDownTimer;
public class MainActivity extends Activity implements OnClickListener, OnInitListener {
//TTS object
private TextToSpeech myTTS;
//status check code
private int MY_DATA_CHECK_CODE = 0;
//create the Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get a reference to the button element listed in the XML layout
Button speakButton = (Button)findViewById(R.id.speak);
//listen for clicks
speakButton.setOnClickListener(this);
//check for TTS data
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
}
//respond to button clicks
public void onClick(View v) {
//get the text entered
EditText enteredText = (EditText)findViewById(R.id.enter);
String words = enteredText.getText().toString();
speakWords(words);
}
public void BRC (View view) {
new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words1 = ("BRC will form up in" + millisUntilFinished / 6000 + " minutes");
speakWords(words1);
}
public void onFinish() {
String words2 = ("BRC will form up right away");
speakWords(words2);
}
}.start();
}
public void SRC (View view1) {
new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words3 = ("SRC will form up in" + millisUntilFinished / 6000 +" minutes");
speakWords(words3);
}
public void onFinish() {
String words4=("SRC will form up right away");
speakWords(words4);
}
}.start();
}
public void Taps (View view2) {
new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words5 = ("Taps will sound in" + millisUntilFinished / 6000 +" minutes");
speakWords(words5);
}
public void onFinish() {
String words6=("Attention inside and outside of barracks the status in barracks is now Taps C C Q at the beginning of this turnout there was a status check");
speakWords(words6);
}
}.start();
}
public void Penalty_Tours (View view3) {
new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words7 = ("P Tees will form up in" + millisUntilFinished / 6000 +" minutes");
speakWords(words7);
}
public void onFinish() {
String words8=("P Tees will form up right away");
speakWords(words8);
}
}.start();
}
public void Colors (View view4) {
String words9 = ("Colors Colors Colors");
speakWords(words9);
}
public void PTT (View view5) {
new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words10 = ("P T T will form up in" + millisUntilFinished / 6000 +" minutes");
speakWords(words10);
}
public void onFinish() {
String words11=("P T T will form up right away");
speakWords(words11);
}
}.start();
}
//speak the user text
private void speakWords(String speech) {
//speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
//act on result of TTS data check
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
//the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
}
else {
//no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
//setup TTS
public void onInit(int initStatus) {
//check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
}
else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
}
}
}
Any help would be greatly appreciated.
public void BRC(View view) {
int totaltime = 6500;
CountDownTimer mTimer = new CountDownTimer(totaltime, 6000) {
public void onTick(long millisUntilFinished) {
String words1 = ("BRC will form up in" + millisUntilFinished / 6000 + " minutes");
speakWords(words1);
}
public void onFinish() {
String words2 = ("BRC will form up right away");
speakWords(words2);
}
}.start();
void SRC() {
mTimer.cancel();
}
}
In MainActivity function ,declare a variable to define the status of each counter. In onTick() of all counters, make it check for the variable
Hope this help.
public class MainActivity extends Activity implements OnClickListener, OnInitListener {
//TTS object
private Boolean isBRCRunning = false;
private Boolean isPTTRunning = false;
private static CountDownTimer myBRC;
private static CountDownTimer myPTT;
//
//respond to button clicks
public void onClick(View v) {
// .....
// If BRC button
if(BRC button){
BRC();
isBRCRunning = true;
} else if (PTT button){
BRC();
isBRCRunning = true;
}
}
public void BRC () {
myBRC = new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words1 = ("BRC will form up in" + millisUntilFinished / 6000 + " minutes");
MainActivity.logForDebug(MainActivity.TAG, words1);
// Control other timer
if(isPTTRunning){
myPTT.cancel();
isPTTRunning = false;
}
}
public void onFinish() {
String words2 = ("BRC will form up right away");
MainActivity.logForDebug(MainActivity.TAG, words2);
}
}.start();
}
public void PTT () {
myPTT = new CountDownTimer(65000, 6000) {
public void onTick(long millisUntilFinished) {
String words1 = ("BRC will form up in" + millisUntilFinished / 6000 + " minutes");
MainActivity.logForDebug(MainActivity.TAG, words1);
// Control other timers
if(isBRCRunning){
myBRC.cancel();
isBRCRunning = false;
}
}
public void onFinish() {
String words2 = ("BRC will form up right away");
MainActivity.logForDebug(MainActivity.TAG, words2);
}
}.start();
}
}

App stops after certain button click

I've (legally) copied and pasted some project code from an app called beatkeeper into my own app. I wanted to implement a metronome.
The app beatkeeper on itself works fine but as I soon as I copy the code and run my own app, it's stops working the moment I click the start/stop button...
04-07 09:25:05.126: E/AndroidRuntime(2708): FATAL EXCEPTION: main
04-07 09:25:05.126: E/AndroidRuntime(2708): Process: nl.ruudjanssenmusicservices.desaxofoonapp, PID: 2708
04-07 09:25:05.126: E/AndroidRuntime(2708): java.lang.NullPointerException
04-07 09:25:05.126: E/AndroidRuntime(2708): at nl.ruudjanssenmusicservices.desaxofoonapp.MetronomeActivity$6.handleMessage(MetronomeActivity.java:54)
04-07 09:25:05.126: E/AndroidRuntime(2708): at android.os.Handler.dispatchMessage(Handler.java:102)
04-07 09:25:05.126: E/AndroidRuntime(2708): at android.os.Looper.loop(Looper.java:136)
04-07 09:25:05.126: E/AndroidRuntime(2708): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-07 09:25:05.126: E/AndroidRuntime(2708): at java.lang.reflect.Method.invokeNative(Native Method)
04-07 09:25:05.126: E/AndroidRuntime(2708): at java.lang.reflect.Method.invoke(Method.java:515)
04-07 09:25:05.126: E/AndroidRuntime(2708): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-07 09:25:05.126: E/AndroidRuntime(2708): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-07 09:25:05.126: E/AndroidRuntime(2708): at dalvik.system.NativeStart.main(Native Method)
Source main activity:
package nl.ruudjanssenmusicservices.desaxofoonapp;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
public class MetronomeActivity extends Activity {
private final short minBpm = 40;
private final short maxBpm = 208;
private short bpm = 100;
private short noteValue = 4;
private short beats = 4;
private short volume;
private short initialVolume;
private double beatSound = 2440;
private double sound = 6440;
private AudioManager audio;
private MetronomeAsyncTask metroTask;
private Button plusButton;
private Button minusButton;
private TextView currentBeat;
private Handler mHandler;
// have in mind that: http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler
// in this case we should be fine as no delayed messages are queued
private Handler getHandler() {
return new Handler() {
#Override
public void handleMessage(Message msg) {
String message = (String)msg.obj;
if(message.equals("1"))
currentBeat.setTextColor(Color.GREEN);
else
currentBeat.setTextColor(getResources().getColor(R.color.yellow));
currentBeat.setText(message);
}
};
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
metroTask = new MetronomeAsyncTask();
/* Set values and listeners to buttons and stuff */
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
TextView timeSignatureText = (TextView) findViewById(R.id.timesignature);
timeSignatureText.setText(""+beats+"/"+noteValue);
plusButton = (Button) findViewById(R.id.plus);
plusButton.setOnLongClickListener(plusListener);
minusButton = (Button) findViewById(R.id.minus);
minusButton.setOnLongClickListener(minusListener);
// currentBeat = (TextView) findViewById(R.id.currentBeat);
//currentBeat.setTextColor(Color.GREEN);
Spinner beatSpinner = (Spinner) findViewById(R.id.beatspinner);
ArrayAdapter<Beats> arrayBeats =
new ArrayAdapter<Beats>(this,
android.R.layout.simple_spinner_item, Beats.values());
beatSpinner.setAdapter(arrayBeats);
beatSpinner.setSelection(Beats.four.ordinal());
arrayBeats.setDropDownViewResource(R.layout.spinner_dropdown);
beatSpinner.setOnItemSelectedListener(beatsSpinnerListener);
Spinner noteValuesdSpinner = (Spinner) findViewById(R.id.notespinner);
ArrayAdapter<NoteValues> noteValues =
new ArrayAdapter<NoteValues>(this,
android.R.layout.simple_spinner_item, NoteValues.values());
noteValuesdSpinner.setAdapter(noteValues);
noteValues.setDropDownViewResource(R.layout.spinner_dropdown);
noteValuesdSpinner.setOnItemSelectedListener(noteValueSpinnerListener);
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
initialVolume = (short) audio.getStreamVolume(AudioManager.STREAM_MUSIC);
volume = initialVolume;
SeekBar volumebar = (SeekBar) findViewById(R.id.volumebar);
volumebar.setMax(audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumebar.setProgress(volume);
volumebar.setOnSeekBarChangeListener(volumeListener);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public synchronized void onStartStopClick(View view) {
Button button = (Button) view;
String buttonText = button.getText().toString();
if(buttonText.equalsIgnoreCase("start")) {
button.setText(R.string.stop);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
metroTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
else
metroTask.execute();
} else {
button.setText(R.string.start);
metroTask.stop();
metroTask = new MetronomeAsyncTask();
Runtime.getRuntime().gc();
}
}
private void maxBpmGuard() {
if(bpm >= maxBpm) {
plusButton.setEnabled(false);
plusButton.setPressed(false);
} else if(!minusButton.isEnabled() && bpm>minBpm) {
minusButton.setEnabled(true);
}
}
public void onPlusClick(View view) {
bpm++;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
maxBpmGuard();
}
private OnLongClickListener plusListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
bpm+=20;
if(bpm >= maxBpm)
bpm = maxBpm;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
maxBpmGuard();
return true;
}
};
private void minBpmGuard() {
if(bpm <= minBpm) {
minusButton.setEnabled(false);
minusButton.setPressed(false);
} else if(!plusButton.isEnabled() && bpm<maxBpm) {
plusButton.setEnabled(true);
}
}
public void onMinusClick(View view) {
bpm--;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
minBpmGuard();
}
private OnLongClickListener minusListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
bpm-=20;
if(bpm <= minBpm)
bpm = minBpm;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
minBpmGuard();
return true;
}
};
private OnSeekBarChangeListener volumeListener = new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
volume = (short) progress;
audio.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private OnItemSelectedListener beatsSpinnerListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Beats beat = (Beats) arg0.getItemAtPosition(arg2);
TextView timeSignature = (TextView) findViewById(R.id.timesignature);
timeSignature.setText(""+beat+"/"+noteValue);
metroTask.setBeat(beat.getNum());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
private OnItemSelectedListener noteValueSpinnerListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
NoteValues noteValue = (NoteValues) arg0.getItemAtPosition(arg2);
TextView timeSignature = (TextView) findViewById(R.id.timesignature);
timeSignature.setText(""+beats+"/"+noteValue);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
#Override
public boolean onKeyUp(int keycode, KeyEvent e) {
SeekBar volumebar = (SeekBar) findViewById(R.id.volumebar);
volume = (short) audio.getStreamVolume(AudioManager.STREAM_MUSIC);
switch(keycode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
volumebar.setProgress(volume);
break;
}
return super.onKeyUp(keycode, e);
}
public void onBackPressed() {
metroTask.stop();
// metroTask = new MetronomeAsyncTask();
Runtime.getRuntime().gc();
audio.setStreamVolume(AudioManager.STREAM_MUSIC, initialVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
finish();
}
private class MetronomeAsyncTask extends AsyncTask<Void,Void,String> {
Metronome metronome;
MetronomeAsyncTask() {
mHandler = getHandler();
metronome = new Metronome(mHandler);
}
protected String doInBackground(Void... params) {
metronome.setBeat(beats);
metronome.setNoteValue(noteValue);
metronome.setBpm(bpm);
metronome.setBeatSound(beatSound);
metronome.setSound(sound);
metronome.play();
return null;
}
public void stop() {
metronome.stop();
metronome = null;
}
public void setBpm(short bpm) {
metronome.setBpm(bpm);
metronome.calcSilence();
}
public void setBeat(short beat) {
if(metronome != null)
metronome.setBeat(beat);
}
}
}
I think there might be a problem with the 'private Handler getHandler' on line 48, but I have absolutely no clue how to solve this...
Edit: request to post the metronome-class:
package nl.ruudjanssenmusicservices.desaxofoonapp;
import android.os.Handler;
import android.os.Message;
public class Metronome {
private double bpm;
private int beat;
private int noteValue;
private int silence;
private double beatSound;
private double sound;
private final int tick = 1000; // samples of tick
private boolean play = true;
private AudioGenerator audioGenerator = new AudioGenerator(8000);
private Handler mHandler;
private double[] soundTickArray;
private double[] soundTockArray;
private double[] silenceSoundArray;
private Message msg;
private int currentBeat = 1;
public Metronome(Handler handler) {
audioGenerator.createPlayer();
this.mHandler = handler;
}
public void calcSilence() {
silence = (int) (((60/bpm)*8000)-tick);
soundTickArray = new double[this.tick];
soundTockArray = new double[this.tick];
silenceSoundArray = new double[this.silence];
msg = new Message();
msg.obj = ""+currentBeat;
double[] tick = audioGenerator.getSineWave(this.tick, 8000, beatSound);
double[] tock = audioGenerator.getSineWave(this.tick, 8000, sound);
for(int i=0;i<this.tick;i++) {
soundTickArray[i] = tick[i];
soundTockArray[i] = tock[i];
}
for(int i=0;i<silence;i++)
silenceSoundArray[i] = 0;
}
public void play() {
calcSilence();
do {
msg = new Message();
msg.obj = ""+currentBeat;
if(currentBeat == 1)
audioGenerator.writeSound(soundTockArray);
// else
// audioGenerator.writeSound(soundTickArray);
if(bpm <= 120)
mHandler.sendMessage(msg);
audioGenerator.writeSound(silenceSoundArray);
if(bpm > 120)
mHandler.sendMessage(msg);
currentBeat++;
if(currentBeat > beat)
currentBeat = 1;
} while(play);
}
public void stop() {
play = false;
audioGenerator.destroyAudioTrack();
}
public double getBpm() {
return bpm;
}
public void setBpm(int bpm) {
this.bpm = bpm;
}
public int getNoteValue() {
return noteValue;
}
public void setNoteValue(int bpmetre) {
this.noteValue = bpmetre;
}
public int getBeat() {
return beat;
}
public void setBeat(int beat) {
this.beat = beat;
}
public double getBeatSound() {
return beatSound;
}
public void setBeatSound(double sound1) {
this.beatSound = sound1;
}
public double getSound() {
return sound;
}
public void setSound(double sound2) {
this.sound = sound2;
}
}
currentBeat is null there in onHandleMessage();

Getters and setters in metronome

I have I think simple problem which I can't fix on my own. In the code below I need to set the loudBars variable to the other class. I made the setLoudBars() but it just doesn't work. Anyone sees any solution in this?
public class DrumActivity extends Activity {
private final short minBpm = 40;
private final short maxBpm = 208;
private short bpm = 100;
private short noteValue = 4;
private short beats = 4;
private short volume;
private short initialVolume;
private double beatSound = 2440;
private double sound = 6440;
private AudioManager audio;
private MetronomeAsyncTask metroTask;
private Button plusButton;
private Button minusButton;
private TextView currentBeat;
private Handler mHandler;
private int loudBars = 2;
private short silentBars = 1;
// have in mind that: http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler
// in this case we should be fine as no delayed messages are queued
private Handler getHandler() {
return new Handler() {
#Override
public void handleMessage(Message msg) {
String message = (String)msg.obj;
if(message.equals("1")) {
currentBeat.setTextColor(Color.GREEN);
}else {
currentBeat.setTextColor(getResources().getColor(R.color.yellow));
}
currentBeat.setText(message);
}
};
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drum);
metroTask = new MetronomeAsyncTask();
/* Set values and listeners to buttons and stuff */
TextView eLoudBars = (TextView) findViewById(R.id.eLoudBars);
eLoudBars.setText(""+loudBars);
TextView eSilentBars = (TextView) findViewById(R.id.eSilentBars);
Button minusLoud = (Button) findViewById(R.id.lbminus);
minusLoud.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loudBars--;
if(loudBars < 1)
loudBars = 1;
TextView eLoudBars = (TextView) findViewById(R.id.eLoudBars);
eLoudBars.setText(""+loudBars);
metroTask.setLoudBars(loudBars);
}
});
Button plusLoud = (Button) findViewById(R.id.lbplus);
plusLoud.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loudBars++;
TextView eLoudBars = (TextView) findViewById(R.id.eLoudBars);
eLoudBars.setText(""+loudBars);
metroTask.setLoudBars(loudBars);
}
});
Button minusSilent = (Button) findViewById(R.id.sbminus);
Button plusSilent = (Button) findViewById(R.id.sbplus);
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
TextView timeSignatureText = (TextView) findViewById(R.id.timesignature);
timeSignatureText.setText(""+beats+"/"+noteValue);
plusButton = (Button) findViewById(R.id.plus);
plusButton.setOnLongClickListener(plusListener);
minusButton = (Button) findViewById(R.id.minus);
minusButton.setOnLongClickListener(minusListener);
currentBeat = (TextView) findViewById(R.id.currentBeat);
currentBeat.setTextColor(Color.GREEN);
Spinner beatSpinner = (Spinner) findViewById(R.id.beatspinner);
ArrayAdapter<Beats> arrayBeats =
new ArrayAdapter<Beats>(this,
android.R.layout.simple_spinner_item, Beats.values());
beatSpinner.setAdapter(arrayBeats);
beatSpinner.setSelection(Beats.four.ordinal());
arrayBeats.setDropDownViewResource(R.layout.spinner_dropdown);
beatSpinner.setOnItemSelectedListener(beatsSpinnerListener);
Spinner noteValuesdSpinner = (Spinner) findViewById(R.id.notespinner);
ArrayAdapter<NoteValues> noteValues =
new ArrayAdapter<NoteValues>(this,
android.R.layout.simple_spinner_item, NoteValues.values());
noteValuesdSpinner.setAdapter(noteValues);
noteValues.setDropDownViewResource(R.layout.spinner_dropdown);
noteValuesdSpinner.setOnItemSelectedListener(noteValueSpinnerListener);
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
initialVolume = (short) audio.getStreamVolume(AudioManager.STREAM_MUSIC);
volume = initialVolume;
SeekBar volumebar = (SeekBar) findViewById(R.id.volumebar);
volumebar.setMax(audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumebar.setProgress(volume);
volumebar.setOnSeekBarChangeListener(volumeListener);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public synchronized void onStartStopClick(View view) {
Button button = (Button) view;
String buttonText = button.getText().toString();
if(buttonText.equalsIgnoreCase("start")) {
button.setText(R.string.stop);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
metroTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
else
metroTask.execute();
} else {
button.setText(R.string.start);
metroTask.stop();
metroTask = new MetronomeAsyncTask();
Runtime.getRuntime().gc();
}
}
private void maxBpmGuard() {
if(bpm >= maxBpm) {
plusButton.setEnabled(false);
plusButton.setPressed(false);
} else if(!minusButton.isEnabled() && bpm>minBpm) {
minusButton.setEnabled(true);
}
}
public void onPlusClick(View view) {
bpm++;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
maxBpmGuard();
}
private OnLongClickListener plusListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
bpm+=20;
if(bpm >= maxBpm)
bpm = maxBpm;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
maxBpmGuard();
return true;
}
};
private void minBpmGuard() {
if(bpm <= minBpm) {
minusButton.setEnabled(false);
minusButton.setPressed(false);
} else if(!plusButton.isEnabled() && bpm<maxBpm) {
plusButton.setEnabled(true);
}
}
public void onMinusClick(View view) {
bpm--;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
minBpmGuard();
}
private OnLongClickListener minusListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
bpm-=20;
if(bpm <= minBpm)
bpm = minBpm;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
minBpmGuard();
return true;
}
};
private OnSeekBarChangeListener volumeListener = new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
volume = (short) progress;
audio.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private OnItemSelectedListener beatsSpinnerListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Beats beat = (Beats) arg0.getItemAtPosition(arg2);
TextView timeSignature = (TextView) findViewById(R.id.timesignature);
timeSignature.setText(""+beat+"/"+noteValue);
metroTask.setBeat(beat.getNum());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
private OnItemSelectedListener noteValueSpinnerListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
NoteValues noteValue = (NoteValues) arg0.getItemAtPosition(arg2);
TextView timeSignature = (TextView) findViewById(R.id.timesignature);
timeSignature.setText(""+beats+"/"+noteValue);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
#Override
public boolean onKeyUp(int keycode, KeyEvent e) {
SeekBar volumebar = (SeekBar) findViewById(R.id.volumebar);
volume = (short) audio.getStreamVolume(AudioManager.STREAM_MUSIC);
switch(keycode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
volumebar.setProgress(volume);
break;
}
return super.onKeyUp(keycode, e);
}
public void onBackPressed() {
metroTask.stop();
// metroTask = new MetronomeAsyncTask();
Runtime.getRuntime().gc();
audio.setStreamVolume(AudioManager.STREAM_MUSIC, initialVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
finish();
}
private class MetronomeAsyncTask extends AsyncTask<Void,Void,String> {
Metronome metronome;
MetronomeAsyncTask() {
mHandler = getHandler();
metronome = new Metronome(mHandler);
}
protected String doInBackground(Void... params) {
metronome.setBeat(beats);
metronome.setNoteValue(noteValue);
metronome.setBpm(bpm);
metronome.setBeatSound(beatSound);
metronome.setSound(sound);
metronome.setLoudBars(loudBars);
metronome.play();
return null;
}
public void stop() {
metronome.stop();
metronome = null;
}
public void setBpm(short bpm) {
metronome.setBpm(bpm);
metronome.calcSilence();
}
public void setBeat(short beat) {
if(metronome != null)
metronome.setBeat(beat);
}
public void setLoudBars(int loudBars) {
if(metronome != null)
metronome.setLoudBars(loudBars);
}
}
}

SeekBar and CountDownTimer

i'm trying to use a SeekBar to control the speed of the CountDownTimer and i'm stopped in 2 issues.
1 - The DownTimerInterval doesn't reset when i change the seekbar progress...but add the progress value every time i change.
2 - I want to stop the countdown when the seekbar progress is set to 0....and it don't work.
How to fix that?
Here is my code
rolagem.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
rolagemAutomatica();
}
});
private void rolagemAutomatica() {
barra = (SeekBar)findViewById(R.exibir_musica.barraFonte);
barra.setVisibility(1);
barra.setMax(4);
barra.setProgress(0);
barra.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
String[] VR = {"0","10","50","75","100"};
//Define crono +1 cause position 0 crash the app
int crono = Integer.parseInt(VR[progress]+1);
CountDownTimer test = new CountDownTimer(400000 , crono) {
#Override
public void onTick(long millisUntilFinished) {
scroll_letra.smoothScrollBy(0,
(int) (millisUntilFinished / 300000));
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
if(crono-1 != 0){
test.start();
}else{
test.cancel();
}
}
});
}
Hold the CountDownTimer as an instance field so that you can cancel it when you need to. If starting one with a tick timer of 0 crashes you, then just don't start one when the speed is 0.
Something like this:
barra.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
String[] VR = {"0","10","50","75","100"};
int crono = Integer.parseInt(VR[progress]);
if (fromUser) {
this.countDownTimer.cancel();
if (crono > 0) {
this.countDownTimer = new CountDownTimer(400000 , crono) {
#Override
public void onTick(long millisUntilFinished) {
scroll_letra.smoothScrollBy(0,
(int) (millisUntilFinished / 300000));
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
if(crono-1 != 0){
test.start();
}else{
test.cancel();
}
}
}
}
});
There are some more optimizations you could do. For example, you could probably define VR as just an array of ints so you don't have to parse them, and you could keep them on the instance so you don't have to create the array over and over, etc.:
int[] VR = new int[] {0, 10, 50, 75, 100};
I found the solution for this issue.
i declare the countDownTimer as a global variable.
CountDownTimer ctimer = null;
after that...i create a method
private void timerRol(int contador) {
if (contador == 0){
Log.v(String.valueOf(contador), "Stopped");
}else{
ctimer = new CountDownTimer(400000, contador) {
#Override
public void onTick(long millisUntilFinished) {
scroll_letra.smoothScrollBy(0, (int) (millisUntilFinished / 300000));
}
#Override
public void onFinish() {
}
};
ctimer.start();
}
}
after created the method...i call it on OnCreate passing a value as parameter...and stop it after the call.
timerRol(100);
ctimer.cancel();
after that i create the seekbar and call the method when the user change the position.
barraRolagem = (SeekBar) findViewById(R.exibir_musica.barraRolagem);
barraRolagem.setVisibility(1);
barraRolagem.setMax(5);
barraRolagem.setProgress(0);
final int[] crono = { 0, 750, 500, 100, 50, 1};
barraRolagem.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
if((crono[progress] == 0)) {
ctimer.cancel();
}else{
Log.v(String.valueOf(crono[progress]), "valor do crono");
ctimer.cancel();
timerRol(crono[progress]);
}
}
});

Pop up count down alert with images (android)

I'm trying to create a countdown timer that will pop up and show a different image every second so it goes "3, 2, 1, Start" then starts a different activity. I've tried this numerous ways but can't get any to work.. if anyone could point me in the right direction that'd be great !
package com.practice;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.ImageView;
public class Practice2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final long delayCount = 1000;
final long delayIncrement = 1000;
final long delayCount1 = 1000;
final long delayIncrement1 = 1000;
final long delayCount2 = 1000;
final long delayIncrement2 = 1000;
final Dialog dialog = new Dialog (Practice2.this,
android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog.setTitle("Get ready to play DrawTastic!");
final CountDownTimer timer = new CountDownTimer(delayCount, delayIncrement) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
ImageView three = (ImageView) dialog.findViewById(R.id.iv3);
three.setImageResource(R.drawable.three);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
ImageView two = (ImageView)dialog.findViewById(R.id.iv2);
two.setImageResource(R.drawable.two);
timer1.start();
}
final CountDownTimer timer1 = new CountDownTimer(delayCount1, delayIncrement1) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
ImageView one = (ImageView) dialog.findViewById(R.id.iv1);
one.setImageResource(R.drawable.one);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
ImageView play = (ImageView) dialog.findViewById(R.id.ivPlay);
play.setImageResource(R.drawable.play);
timer2.start();
}
final CountDownTimer timer2 = new CountDownTimer(delayCount2, delayIncrement2) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
ImageView play = (ImageView) dialog.findViewById(R.id.ivPlay);
play.setImageResource(R.drawable.play);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
ImageView play = (ImageView) dialog.findViewById(R.id.ivPlay);
play.setImageResource(R.drawable.play);
dialog.dismiss();
}
};
};
};
timer.start();
dialog.show();
}
}
Make use of Handler. You'll need to show 4 different images at a time interval of 1 second each. Something like -
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
imageView.setBackgroundResource(R.id.nextImage);
}
}, 1000);
But, I'd suggest you to use TextView as shown in API demos.
Go to Views->TextSwitcher in API demos.

Categories

Resources