I've got a Chronometer, but when I change my View (with ActionBar) it stops.
I don't really understand how to use AsyncTask, and I didn't find a Tutorial.
Is there something easy to solve my problem? I would really like an example with Chronometer...
Thanks very much!
Code so far:
public class BFragment extends SherlockFragment {
private Button start;
private View v;
private Chronometer chrono;
private Button pause;
private Button reset;
private long lastPause;
private Button resume;
private Boolean richtig;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.activity_bfragment, container, false);
start = (Button) v.findViewById(R.id.start);
chrono = (Chronometer) v.findViewById(R.id.chronometer1);
pause = (Button) v.findViewById(R.id.pause);
reset = (Button) v.findViewById(R.id.reset);
resume = (Button) v.findViewById(R.id.resume);
richtig = true;
new chronom().execute();
return v;
}
private class chronom extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
chrono.setBase(SystemClock.elapsedRealtime());
chrono.start();
System.out.println(SystemClock.elapsedRealtime());
richtig = false;
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
lastPause = SystemClock.elapsedRealtime();
chrono.stop();
richtig = true;
}
});
resume.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (richtig) {
chrono.setBase(chrono.getBase() + SystemClock.elapsedRealtime() - lastPause);
chrono.start();
} else {
}
}
});
reset.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
chrono.setBase(SystemClock.elapsedRealtime());
System.out.println(chrono.getBase());
richtig = false;
}
});
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
}
}
I just copied the code... (Chrono works, but not in Background)
Related
I am trying to add a toggle button, so that my image button switches the direction that it translates based on the status of the toggle button. However, I am running into problems when trying to add it to the media player, and when using the if statement.
public class MainActivity extends AppCompatActivity {
TextToSpeech tts1;
ToggleButton toggleButton;
public void changeTranslation(View view){
boolean on = ((ToggleButton)view).isChecked();
if(on){
toggleButton.setText("Speech-to-Farts");
Toast.makeText(getApplicationContext(),"Translating speech to farts.",Toast.LENGTH_SHORT);
} else{
toggleButton.setText("Farts-to-Speech");
Toast.makeText(getApplicationContext(),"Translating farts to speech.",Toast.LENGTH_SHORT);
}
}
private static final String TAG = "MainActivity";
private MediaPlayer mMediaPlayer;
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mediaPlayer){
releaseMediaPlayer();
}
};
private void releaseMediaPlayer(){
if(mMediaPlayer != null){
mMediaPlayer.release();
mMediaPlayer=null;
}
}
TextView tv1;
ImageButton b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(textView);
b1 = (ImageButton) findViewById(R.id.recordButton);
final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggle_button);
toggleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (toggleButton.isChecked()) {
toggleButton.setText("Farts-to-Speech");
} else {
toggleButton.setText("Speech-to-Farts");
}
}
});
tts1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
tts1.setLanguage(Locale.US);
}
}
});
b1.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
int[] fartLibrary={};
String[] speechLibrary={};
if(toggleButton==true) {
releaseMediaPlayer();
String randomTranslation = (speechLibrary[new Random().nextInt(speechLibrary.length)]);
tts1.speak(randomTranslation, TextToSpeech.QUEUE_FLUSH, null);
} else {
releaseMediaPlayer();
mMediaPlayer=MediaPlayer.create(this,fartLibrary);
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(mCompletionListener);
}
}
});
}
}
This is my Translations.java. I'm not sure if this is necessary anymore though
public class Translations{
private String mSpeechTranslation;
private int mFartTranslation;
public Translations(String speechTranslation, int fartTranslation){
mFartTranslation = fartTranslation;
mSpeechTranslation = speechTranslation;
}
public String getmSpeechTranslation(){ return mSpeechTranslation;}
public int getmFartTranslation(){ return mFartTranslation;}
}
This is part of the code in my MainActivity.
stopwatch1 is an image button called in MainActivity:
stopwatch1 = (ImageButton)findViewById(R.id.stopwatch1);
I have tried searching for clues on how to use dialog.setOnDismissListener, however, there aren't proper answers to help me with the killing of the audio after deliberate or accidental exit of the dialog. Any help would be appreciated.
stopwatch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog mmDialog1 = new Dialog(context);
mmDialog1.setContentView(R.layout.countdowntimer);
mmDialog1.setTitle("Stop-watch");
Button ddButton1 = (Button) mmDialog1.findViewById(R.id.countdown_exit);
final Button ddButton2 = (Button) mmDialog1.findViewById(R.id.countdown_start);
final TextView timeview = (TextView) mmDialog1.findViewById(R.id.timeview);
ddButton2.setTag(1);
ddButton2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final int status = (Integer) v.getTag();
if (status == 1) {
ddButton2.setText("Stop");
countDownTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
int time = (int) (millisUntilFinished/1000);
timeview.setText(Integer.toString(time));
}
#Override
public void onFinish() {
timeview.setText("60");
ddButton2.setText("Start");
MediaPlayer stop = MediaPlayer.create(context, R.raw.stop);
stop.start();
}
}.start();
v.setTag(0);
} else {
ddButton2.setText("Start");
timeview.setText("60");
countDownTimer.cancel();
v.setTag(1);
}
}
});
ddButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mmDialog1.dismiss();
}
});
mmDialog1.show();
}
});
My suggestion would be to implement an interface. When the dialog closes, have the callback shut off the media player.
A quick example is this.
interface
public interface DialogClosed {
void shutDownMediaPlayer();
}
then implement the interface in the calling activity
activity
public class MainActivity extends Activity implements DialogClosed {
....
#Override
public void shutDownMediaPlayer() {
//shut down media player here
}
}
Also, you may add a boolean to check if the dialog is showing like this
boolean isShowing = mDialog.isShowing();
and then you can just shut off the media player at any point if this is false.
So I've used some pointers from Jawascript and also edited my code a little, now it works:
stopwatch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog mmDialog1 = new Dialog(context);
mmDialog1.setContentView(R.layout.countdowntimer);
mmDialog1.setTitle("Stop-watch");
Button ddButton1 = (Button) mmDialog1.findViewById(R.id.countdown_exit);
final Button ddButton2 = (Button) mmDialog1.findViewById(R.id.countdown_start);
final TextView timeview = (TextView) mmDialog1.findViewById(R.id.timeview);
final MediaPlayer stop = MediaPlayer.create(context, R.raw.stop);
ddButton2.setTag(1);
mmDialog1.setCancelable(false);
if (mmDialog1.isShowing() == false) {
stop.stop();
}
ddButton2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
final int status = (Integer) v.getTag();
if (status == 1) {
ddButton2.setText("Stop");
countDownTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
int time = (int) (millisUntilFinished/1000);
timeview.setText(Integer.toString(time));
}
#Override
public void onFinish() {
timeview.setText("60");
ddButton2.setText("Start");
try {
stop.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
stop.start();
}
}.start();
v.setTag(0);
} else {
ddButton2.setText("Start");
timeview.setText("60");
countDownTimer.cancel();
v.setTag(1);
stop.stop();
}
}
});
ddButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mmDialog1.dismiss();
}
});
mmDialog1.show();
}
});
in this app the Content of the TextView should change/update every second with a sleep thread.
The whole process starts when the button is clicked.
Firstable here is the normal code without the threads:
public class MainActivity extends ActionBarActivity {
Button btn;
TextView tw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
tw = (TextView) findViewById(R.id.tw);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tw.setText("1"); //This is the TextView Content, it should update every second with a sleep thread
tw.setText("2");
tw.setText("3");
}
});
}
}
This is the code added ( not working ) sleep threads:
public class MainActivity extends ActionBarActivity {
Button btn;
TextView tw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
tw = (TextView) findViewById(R.id.tw);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tw.setText("1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tw.setText("2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tw.setText("3");
}
});
}
}
ThankĀ“s
The problem is that you are block the main UI(sleep) thread thus giving you unexpected result.
You need to use handler for this if you want to update this each second
sample:
public class MainActivity extends ActionBarActivity {
Button btn;
TextView tw;
int incre = 1;
Handler handler;
Runnable run;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
tw = (TextView) findViewById(R.id.tw);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tw.setText(incre++ + "");
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
tw.setText(incre++ + ""); //set the textview text HERE every 1 second
if(incre != 3) //checks if it is not already 3 second
handler.postDelayed(run, 1000); //run the method again
else
incre -= 2;
}
};
handler.postDelayed(run, 1000); //will call the runnable every 1 second
}
});
}
}
I've got a Fragment (ActionBarSherlock Tabs), and I want to run a Chronometer in Background:
public class BFragment extends SherlockFragment {
private Button start;
private View v;
private Chronometer chrono;
private Button pause;
private Button reset;
private long lastPause;
private Button resume;
private boolean isChronometerRunning = false;
private boolean richtig = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.activity_bfragment, container, false);
start = (Button) v.findViewById(R.id.start);
chrono = (Chronometer) v.findViewById(R.id.chronometer1);
pause = (Button) v.findViewById(R.id.pause);
reset = (Button) v.findViewById(R.id.reset);
resume = (Button) v.findViewById(R.id.resume);
new ChronoBackground().execute();
return v;
}
void StartTimer() {
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
chrono.setBase(SystemClock.elapsedRealtime());
chrono.start();
isChronometerRunning = true;
System.out.println(SystemClock.elapsedRealtime());
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
lastPause = SystemClock.elapsedRealtime();
chrono.stop();
isChronometerRunning = false;
richtig = true;
}
});
resume.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (isChronometerRunning == false && richtig) {
chrono.setBase(chrono.getBase() + SystemClock.elapsedRealtime() - lastPause);
chrono.start();
richtig = false;
} else {
}
}
});
reset.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
chrono.setBase(SystemClock.elapsedRealtime());
System.out.println(chrono.getBase());
}
});
}
}
And here is my ChronBackground class/code:
public class ChronoBackground extends AsyncTask<Void, Void, Void> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
StartTimer();
return null;
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
#Override
protected void onPostExecute(Void result) {
return ;
}
#Override
protected void onPreExecute() {
return ;
}
}
Now there's an error, and I'm not really sure if my chrono is working this way... The error is at ChronoBackground: StartTimer() not defined.
The mistake is perhaps in the fact, that ChronoBackground is not an innerclass of BFragment and doesn't see the method?
public class Talk extends Activity {
private ProgressDialog progDialog;
int typeBar;
TextView text1;
EditText edit;
Button respond;
private String name;
private String textAtView;
private String savedName;
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.dorothydialog);
text1 = (TextView)findViewById(R.id.dialog);
edit = (EditText)findViewById(R.id.repsond);
respond = (Button)findViewById(R.id.button01);
respond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text1.setText("Welcome! Enter your name!");
respond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = edit.getText().toString();
text1.setText("Cool! your name is "+name);
}
});
}
});
}
}
Okay so i want to figure out how i would save the state of this activity. this is just a small snippet from my code to show you guys an example. So i want to save the state so when the activity is destroyed the user will come back where they left off.
Second thing, I would like to show a quick 5 second Progress dialog spinner between each button click.
For the second thing
This should work:
public class TestActivity extends Activity implements Runnable, OnClickListener {
private TextView tv;
private ProgressDialog pd;
private Button btn;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
tv = (TextView) this.findViewById(R.id.tv);
btn = (Button)findViewById(R.id.btn);
tv.setText("initial text");
btn.setOnClickListener(this);
}
public void onClick(View v) {
pd = ProgressDialog.show(TestActivity.this, "Please wait...", "Details here", true, false);
Thread thread = new Thread(TestActivity.this);
thread.start();
}
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
pd.dismiss();
tv.setText("text after 5 sec passed");
}
};
}