Want to use saveEventually() if save() not successful in Android - android

I need to save an object in parse. I want to use save() with timeout . If save() is not successful then it should use saveEventually(). Can I instead use saveEventually() with a timer if the timer expires before getting the callback from saveEventually() it should show a message.
userQuestions = new ParseObject("UserQuestions");
userQuestions.put("questionAsked", edt_askQuestion.getText().toString());
userQuestions.put("askedByUser", SignInActivity.pUser);
userQuestions.saveEventually(new SaveCallback() {
#Override
public void done(ParseException e) {
//cancel the timeout timer
countDownTimer.cancel();
Intent intent = new Intent(AActivity.this, DActivity.class);
intent.putExtra(Constants.Extras.INTENT_EXTRA_QUESTION, edt_askQuestion.getText().toString());
startActivity(intent);
}
});
//countdown timer for timeout
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
LogUtil.d("seconds remaining: ", String.valueOf(millisUntilFinished / 1000));
}
public void onFinish() {
//if timer is triggered before saving object
Toast.makeText(AActivity.this, "Problem with net connectivity question will be saved when net is connected", Toast.LENGTH_SHORT).show();
}
}.start();
is this correct or is there any other way?

Related

a good way to check if timer already run repeatedly

I'm working on React Native and i want to create a never ending service that run every (n) seconds on Native Modules (on this topic is android).
I've create a simple service like this
public void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.v(TAG, "SERVICE RUN");
try{
if(haveNetworkConnection()){
db.openDB();
if(db.countRowNewStructure()>0){
//send data to server
} else{
Log.v(TAG, "No data should be send to server");
}
} else {
Log.v(TAG, "Ga ada sinyal");
}
} catch (JSONException e){
e.printStackTrace();
}
}
}, 0, 1000);
}
above code run every second to check, but i'm facing the problem when i re-run the service from React Native, the log showing me those code every 0.5 seconds
the simulation may be like :
0----------------1 //seconds
startTimer()
re-run startTimer() conscious
0----------------1 //seconds
startTimer()
//now i have two startTimer() that will run every 1 sec on different interval
I want to keep my startTimer() just running once even I trigger startService() every 0.5 sec.
how can i do that? is it possible?
this may help you. Timmer to perform the certain action in android after the particular time.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask timertaskforsynctime = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
// your action here
}
});
}
};
timer.schedule(timertaskforsynctime,5000,10000);// decide the time when it will start and after how much time it will run continusly.
}`
for one time
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
// your code that will run after 1 sec
}
}, 1000);
You could make use of the cancel method to cancel the previous Timer.
public class YourModule extends ReactContextBaseJavaModule {
Timer tim = new Timer();
public void startTimer() {
tim.cancel();
tim = new Timer();
tim.scheduleAtFixedRate(
new TimerTask() {
public void run() {
// Run tasks
}
},
0,
1000);
}
}

Saving countTimer() on interrupts (Android)

I am creating a game and I put a timer to onCreate method to display time to user and make an action when it reaches to 0. My way works correctly but since I wrote it to onCreate the time continues to count down and if I rotate screen etc it resets the timer seconds. I know why this happens but I could not find a way to stop it when app is paused and make it continue from where it left of when application continues. Here is my code
new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
question.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
question.setText("done!");
Intent i2 = new Intent(getApplicationContext(), CategoryActivity.class);
startActivity(i2);
}
}.start();
Should I save milisUntilFinished to savedInstanceState and make the timer start depending on the savedInstanceState or is there an easier solution
Edit: So I updated my code to reflect the thing I ve asked. This way I can save the last state of timer when the phone is rotated, but timer still does not stop when I open the menu (pause the application.)
if(savedInstanceState!=null){
seconds = savedInstanceState.getInt("seconds");
new CountDownTimer(seconds * 1000, 1000) {
public void onTick(long millisUntilFinished) {
seconds = (int) millisUntilFinished;
question.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
question.setText("done!");
Intent i2 = new Intent(getApplicationContext(), CategoryActivity.class);
startActivity(i2);
}
}.start();
}else {
new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
seconds = (int) millisUntilFinished;
question.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
question.setText("done!");
Intent i2 = new Intent(getApplicationContext(), CategoryActivity.class);
startActivity(i2);
}
}.start();
}
CounDwonTimer mCountTimer;
int seconds = 0;
then just cancel the mCountTimer in onPause and start in `onResme'
protected void onResume(){
super.onReusme();
mCountTimer = new CountDownTimer(seconds*1000,1000){
//......record the seconds
}
}
protected void onPause(){
if(mCountTimer != null)
mCountTimer.cancel();
}
if your activity will destory when rotate the screen,you need onSaveInstanceState.otherwise you do not need this method
I hope the following code will help you,
private long startTime = 0L;
private boolean threadStop = false;
private Handler myHandler = new Handler();
private Runnable updateTimerMethod = new Runnable() {
public void run() {
if (isAdded()) {
timeInMillies = SystemClock.uptimeMillis() - startTime;
//finalTime = timeSwap + timeInMillies;
time.setText(miliSecondToMinSec(timeInMillies));
if (!threadStop)
myHandler.postDelayed(this, 1000);
}
}
};
#Override
public void onStart() {
super.onStart();
if (threadStop) {
threadStop = false;
startTime = SystemClock.uptimeMillis() - timeInMillies;
myHandler.postDelayed(updateTimerMethod, 0);
}
}
#Override
public void onStop() {
threadStop = true;
super.onStop();
}

Intent with Countdown crashes android app

My Android app crashes when it reaches countdown 0. Below is the part of code related to it.
final CountDownTimer countdown=new CountDownTimer(60000, 1000){
public void onTick(long millisUntilFinished)
{
tvTime.setText((millisUntilFinished / 1000)+"'s");
}
public void onFinish()
{
try{
tvTime.setText("Time Over");
this.cancel();
Toast.makeText(getApplicationContext(),"Answer: "+ OriginalWord, Toast.LENGTH_LONG).show();
Intent i=new Intent(LastJumble.this,ScoreCard.class);
i.putExtra("username",username);
i.putExtra("totalQues", totalQues);
i.putExtra("count", count);
startActivity(i);
}
catch (Exception e) {
// TODO: handle exception
}
}
}.start();
this.cancel() will try to cancel the CountDownTimer. Since the timer is finished this will break. If you mean to call a cancel method in your outer class you should reference it as OuterClass.this.cancel() where OuterClass is the name of the class.

Android CountDownTimer and Runnable

what I'm trying to do:
My app connects with a Bluetooth accelerometer and gets acceleration data every 50ms. I want to check for these with a Runnable. And this worked fine. However, for the complete app I added two CountDownTimers:
1) introTimer(), which runs in an AlertDialog and counts down from 3. OnFinish() calls (i) my Runnable, that deals with new acceleration data and (ii) a second timer called
2) mainTimer(), which counts down from 20 and refreshes a TextView on the UI.
My problem is, that my Runnable is only executed once when it is first called. Why is that? Apparently I have not yet understood the threading principles behind this. My next step (probably going to be complicated) is to refresh ImageViews every 50ms (or maybe less often, but still with a relatively high frequency) on the UI, depending on the accelerometer data.
I have thought about deleting the Runnable and putting my calculations in the CountDownTimer, but this might be difficult or inaccurate with the timing/frequency/periods. What do you think?
Here are the code parts. If you think other parts are relevant, I can post them as well:
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
View promptView = layoutInflater.inflate(R.layout.intro_timer_prompt, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final TextView introTimer = (TextView) promptView.findViewById(R.id.introTimer);
builder.setView(promptView);
AlertDialog alertD = builder.create();
alertD.show();
introTimer(introTimer, alertD);
}
private void introTimer(final TextView introTimer, final AlertDialog alertD) {
new CountDownTimer(4*1000, 1000) {
public void onTick(long millisUntilFinished) {
introTimer.setText( ""+ (millisUntilFinished / 1000));
}
public void onFinish() {
alertD.cancel();
// mainTimer();
clearArrayLists();
mHandler = new Handler();
mHandlerTask.run();
mainTimer();
}
}.start();
}
private void mainTimer() {
new CountDownTimer((int)DURATION*1000, 10) {
public void onTick(long millisUntilFinished) {
//mTimerView.setText("seconds remaining: " + millisUntilFinished / 1000 + ":" + millisUntilFinished / 1000. );
long millisecs = Math.round(millisUntilFinished % 1000 / 100);
mTimerView.setText("seconds remaining: " + millisUntilFinished / 1000 + ":" + millisecs );
}
public void onFinish() {
String energy = new DecimalFormat("#.##").format(accumulatedKineticEnergy.get(accumulatedKineticEnergy.size()-1));
mTimerView.setText("Accumulated Energy is " + energy + " Joule.");
}
}.start();
}
Runnable mHandlerTask = new Runnable() {
#Override
public void run() {
Log.i(TAG, "executed only once :( ");
if (a_x.size() < DURATION/INTERVAL) {
try {
calcAccList();
//...calc things...;
mHandler.postDelayed(this, (long) (1000*INTERVAL));
} catch (Exception e) {
e.getMessage();
}
}
else {
mHandler.removeCallbacks(mHandlerTask);
}
}
};
A countdown timer doesn't repeat itself when it expires, but you need to start it again. Maybe you can use the AlarmManager in this case to have a better design.

Problems starting countdown timer from handler

I get notification with socket.io to start a countdown timer in my android app. I use a Handler to send data from the socket.io callbacks to the UI thread. Handler messages work perfect. But starting the countdown timer from the handler doesn't work (onTick() function won't called). If I start it with the UI element, everything is ok. What is the best way to do it, when the countdown timer is operated not from the UI thread?
mHandler = new Handler(){
public void handleMessage(Message inputMessage) {
mBattle = (Battle) inputMessage.obj;
switch (inputMessage.what) {
case NO_BATTLE:
System.out.println("got message NO_BATTLE");
break;
//.................
case START_BATTLE:
startCountdownTimer(mBattle.getCountdown());
System.out.println("got message START_BATTLE");
break;
}
}
and the countdown timer function:
private void startProgressBar(final int time){
if (time != 0) {
new CountDownTimer(time, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress " + i + " " +
+ millisUntilFinished);
i++;
}
#Override
public void onFinish() {
i=0;
}
}.start();
}
Did you print out the value of time when it's not working? If time < SystemClock.elapsedRealtime() + 1000, then onFinish will be called without calling the onTick.

Categories

Resources