Settext Method of Textview - android

I am working on implementing a stopwatch by using a Chronometer and a Textview. The problem i am facing is that the Settext method refreshes the UI which disturbs the offsettopandbottom method i am using for animation on my ListView.
Is there any way that the Settext method only refreshes the Textview or does not disturb my Listview.
Code for the chronometer
stopwatch.setOnChronometerTickListener(new OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer arg0) {
int countup = (int) ((SystemClock.elapsedRealtime() - arg0
.getBase()) / 1000);
String asText = (countup / 60) + ":" + (countup % 60);
tvtimer.setText("Time Elapsed :- " + asText);
}

Create a handler and use that as to set your TextView's text.
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
String message = (String) msg.obj.toString();
// Set your UI mods here
tvtimer.setText("Time Elapsed :- " + message);
super.handleMessage(msg);
}
};
// Then in your TickListener, do this:
stopwatch.setOnChronometerTickListener(new OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer arg0) {
int countup = (int) ((SystemClock.elapsedRealtime() - arg0
.getBase()) / 1000);
String asText = (countup / 60) + ":" + (countup % 60);
// Send a message to your handler
Message msg = new Message();
msg.obj = asText;
handler.sendMessage(msg);
}
Hope it helps :)

Related

Set progressbar position

I need progress bar witch position depends on two timestamp values in millis, so it depends on future timestamp, past timestamp and current timestamp.
For example, I have timestamp of 08:46:11 30.06.2019 and 10:46:11 30.06.2019. But current time is 09:46:11 30.06.2019, so now progressbar should be filled on 50% and going up to 100 until 10:46:11 30.06.2019
I have tried the next code but now I have understood that using CountDownTimer is useless and it is not for my task which described above:
private void progressBar(){
prBar.setProgress(i);
mCountDownTimer=new CountDownTimer(ltimestampStop * 1000,ltimestampStart * 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress"+ i+ millisUntilFinished);
i++;
int Start = ltimestampStart.intValue();
int Stop = ltimestampStop.intValue();
prBar.setProgress((int)i*100/(Stop/Start));
}
#Override
public void onFinish() {
//Do what you want
i++;
prBar.setProgress(100);
}
};
mCountDownTimer.start();
}
So what should I done for creating progressbar on certain position which depends on future time, past time and present time?
You can try to following:
long startTimeInMillis = ...; // 08:46:11 30.06.2019
long stopTimeInMillis = ...; // 10:46:11 30.06.2019
long currentTimeInMillis = ...; // 09:46:11 30.06.2019
long totalTimeInMilis = stopTimeInMillis - startTimeInMillis;
// Standart logic
long remainingTimeInMillis = stopTimeInMillis - currentTimeInMillis;
// But this line assures remaining time is not greater than total time
long remainingTimeInMillis = currentTimeInMillis < startTimeInMillis ?
totalTimeInMilis : stopTimeInMillis - currentTimeInMillis;
// Update every second
long countDownIntervalInMillis = 1000;
// Alternatively you can adjust interval such that it is called only in integer percent changes
int remainingSteps = (int) (((double) remainingTimeInMillis / totalTimeInMilis) * 100);
long countDownIntervalInMillis = remainingTimeInMillis / remainingSteps;
mCountDownTimer = new CountDownTimer(remainingTimeInMillis, countDownIntervalInMillis) {
#Override
public void onTick(long millisUntilFinished) {
int completedPercent = (int) ((1 - (double) millisUntilFinished / totalTimeInMilis) * 100);
prBar.setProgress(completedPercent);
}
#Override
public void onFinish() {
// Do what you want
prBar.setProgress(100);
}
};
mCountDownTimer.start();

Android Chronometer - Save time

I´m using a Chronometer in my Android App. I can start it, stop it and continue counting after pushing the start button again:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_projektbeschreibung, container, false);
if (savedInstanceState != null){
stoppedmillis = savedInstanceState.getLong(STATE_TIME);
hh = savedInstanceState.getString(STATE_HH);
mm = savedInstanceState.getString(STATE_MM);
ss = savedInstanceState.getString(STATE_SS);
}
mChronometer = (Chronometer) rootView.findViewById(R.id.chronometer2);
mChronometer.setText(hh + ":" + mm + ":" + ss);
mChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer cArg) {
long time = SystemClock.elapsedRealtime() - cArg.getBase() ;
int h = (int) (time / 3600000);
int m = (int) (time - h * 3600000) / 60000;
int s = (int) (time - h * 3600000 - m * 60000) / 1000;
hh = h < 10 ? "0" + h : h + "";
mm = m < 10 ? "0" + m : m + "";
ss = s < 10 ? "0" + s : s + "";
cArg.setText(hh + ":" + mm + ":" + ss);
}
});
((Button) rootView.findViewById(R.id.startbutton)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if first start
if(stoppedmillis == 0) {
mChronometer.setBase(SystemClock.elapsedRealtime());
} else {//Point A
long pausetime = (SystemClock.elapsedRealtime() - stoppedmillis);
mChronometer.setBase(mChronometer.getBase() + pausetime);
}
mChronometer.start();
}
});
((Button) rootView.findViewById(R.id.stopbutton)).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
mChronometer.stop();
stoppedmillis = SystemClock.elapsedRealtime();
}
});
After a screen rotation (so the Activity restarts) the chronometer starts counting from the point of 00:00:00 again. My first try was to save the stoppedmillis with a onSaveInstanceState method like the following:
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putLong(STATE_TIME, stoppedmillis);
savedInstanceState.putString(STATE_HH, hh);
savedInstanceState.putString(STATE_MM, mm);
savedInstanceState.putString(STATE_SS,ss);
super.onSaveInstanceState(savedInstanceState);
}
Now, I can get the value of the stoppedmillis after a restart, but I don't know how to set the Base for the Chronometer with the help of the stoppedmillis. At Point A in the Code you can see how it works with stopping the Chronometer with a button but this part of code does not working after a screen rotation.
I know that this is old. Although, I have created a simple application using a chronometer and done the following and it has kept counting across screen rotation. It is spot on with Andrew's original answer. Here is how I outlined it:
Chronometer mChronometer; // this is a global variable
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mChronometer = (Chronometer)findViewById(R.id.chronometer);
if(savedInstanceState != null){
mChronometer.setBase(savedInstanceState.getLong("ChronoTime"));
mChronometer.start();
}
}
Now set up onSaveInstanceState:
#Override
public void onSaveInstanceState (Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putLong("ChronoTime", mChronometer.getBase());
}
Fast solution, using this class:
https://github.com/ahmedrizwan/ChronometerPersist/blob/master/chronometerpersist/src/main/java/library/minimize/com/chronometerpersist/ChronometerPersist.java
ChronometerPersist chronometerPersist = ChronometerPersist.getInstance(chronometer, sharedPreferences);
//Starting the chronometer
startChronometer();
//Stoping the chronometer
stopChronometer();
//Pausing the chronometer
pauseChronometer();
I have lost much time trying to restore the current time with the android chronometer widget.
This is how i solved saving the state of the Chronometer.
private static final int TIME_MULTIPLIER = 60;
Step 1: Convert time to Seconds:
NOTE: If you don't like my method of converting time to second you could do your ways.
private static int convertTimeToSeconds(Long... time) {
int seconds = 0;
if (time.length == 2) {
seconds += time[0] * TIME_MULTIPLIER + time[1];
} else if (time.length == 3) {
seconds += (time[0] * TIME_MULTIPLIER) + (time[1] * TIME_MULTIPLIER) + (time[2]);
}
return seconds;
}
Step 2: Setting and starting time of Chronometer
NOTE: I'm saving the data in a custom object persist that object with any database / SharedPreference / your wish.
public static void setAndStartTime(final Chronometer chronometer) {
long second = 0;
// i have multiple time saved into map. You could save just 1 time and reuse that time.
for (DailyData data : DailyData.DailyDataHolder.getDailyDataMap().values()) {
second += data.getDailyTimeSpent();
}
chronometer.setBase(SystemClock.elapsedRealtime() - (second * 1000));
chronometer.start();
}
Step 3: Saving Time:
public static void saveTime(String timeText) {
String[] timeParts = timeText.split("[:]");
long savedTime = 0;
if (timeParts.length == 2) {
savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]));
} else if (timeParts.length == 3) {
savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]), Long.parseLong(timeParts[2]));
}
DailyData.DailyDataHolder.getDailyData().setDailyTimeSpent(savedTime);
}
Calling the saved method:
ChronoHelper.saveTime(chronometer.getText().toString());
COMPLETE CLASS:
public class ChronoHelper {
private static final int TIME_MULTIPLIER = 60;
public static void setAndStartTime(final Chronometer chronometer) {
long second = 0;
for (DailyData data : DailyData.DailyDataHolder.getDailyDataMap().values()) {
second += data.getDailyTimeSpent();
}
chronometer.setBase(SystemClock.elapsedRealtime() - (second * 1000));
chronometer.start();
}
public static void saveTime(String timeText) {
String[] timeParts = timeText.split("[:]");
long savedTime = 0;
if (timeParts.length == 2) {
savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]));
} else if (timeParts.length == 3) {
savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]), Long.parseLong(timeParts[2]));
}
DailyData.DailyDataHolder.getDailyData().setDailyTimeSpent(savedTime);
}
private static int convertTimeToSeconds(Long... time) {
int seconds = 0;
if (time.length == 2) {
seconds += time[0] * TIME_MULTIPLIER + time[1];
} else if (time.length == 3) {
seconds += (time[0] * TIME_MULTIPLIER) + (time[1] * TIME_MULTIPLIER) + (time[2]);
}
return seconds;
}
public static String secondsToTimeText(DailyData dailyData) {
long savedSeconds = dailyData.getDailyTimeSpent();
long minutes = savedSeconds / TIME_MULTIPLIER;
long seconds = savedSeconds % TIME_MULTIPLIER;
long hours = minutes / TIME_MULTIPLIER;
return hours + ":" + minutes + ":" + seconds;
}
}
Save the base time of the chronometer in onSaveInstanceState and set it back in onRestoreInstanceState like this:
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putLong("ChronoTime", mChronometer.getBase());
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState){
if((savedInstanceState !=null) && savedInstanceState.containsKey("ChronoTime"))
mChronometer.setBase(savedInstanceState.getLong("ChronoTime"));
super.onRestoreInstanceState(savedInstanceState);
}

CountDownTimer not working properly

for (int i=0; i<HisXArray.size(); i++) {
ycoord2 = HisYArray.get(i);
major2 = HisMajorArray.get(i);
xcoord2 = HisXArray.get(i);
minor2 = HisMinorArray.get(i);
time3 = TimeArray.get(i);
timer = new CountDownTimer(time3, 1000) {
#Override
public void onFinish() {
Log.e("Timer", xcoord2 + " " + ycoord2 + " " + time3);
mView.mFadePaint.setColor(Color.BLACK);
mView.drawOval(mView.mCanvas, xcoord2, ycoord2, 2*major2, 2*minor2, mView.mFadePaint);
mView.invalidate();
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
}.start();
When I'm trying to draw something using timer, onFinish called only when time3 = 0 and when i = HisXArray.size() - 1, i.e. the last.
Implement any intermediate steps in onTick(). By design, onFinish() is only called when the countdown is complete.

Count down timer in android

I am new to android.I am having an app which can be used for exam management.Users can insert the date of every subjects and the app will provide time(in hours) for each subject.There is countdown timer which will start from the time allocated for each subject(for eg,48 hours) and should go to zero.when it hits zero an alarm should be played showing that time allocated for that subject has got over.this is my code.
public class Alarmpage extends Activity{
TextView hourshow,minshow,secshow;
SQLiteDatabase database_read;
sampleDatabase samp;
Cursor cur;
Handler handler;
int initStart;
Runnable updater;
int t;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm);
hourshow=(TextView)findViewById(R.id.hr);
samp=new sampleDatabase(getApplicationContext());
database_read=samp.getReadableDatabase();
minshow=(TextView)findViewById(R.id.min);
secshow=(TextView)findViewById(R.id.sec);
cur=database_read.query(sampleDatabase.TABLE_SEC, null, null, null, null, null, null);
}
public void onResume() {
super.onResume();
if(cur.moveToFirst())
{
t=cur.getInt(3);
Log.e("time", String.valueOf(t));
}
handler=new Handler();
initStart = (int) SystemClock.elapsedRealtime();
Log.e("init", String.valueOf(initStart));
updater = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
int sec,minute,hour;
int diff = t*60*60;
Log.e("time in sec", String.valueOf(diff));
System.out.println(diff);
/*if(diff>=1)
{
hour= diff/3600;
}
else {hour = 00; }
hourshow.setText(String.valueOf(hour));
Log.e("diff after hour", String.valueOf(diff));
Log.e("hour", String.valueOf(hour));
minute = (diff % 3600) / 60;
minshow.setText(":"+String.valueOf(minute));
sec= (diff % 60);
secshow.setText(":"+String.valueOf(sec));*/
if (diff >= 1) {
sec = (int) (diff%60);
} else {
sec=00;
}
secshow.setText(":"+String.valueOf(sec));
diff = diff/60;
if (diff >= 1) {
minute = (int) (diff%60);
} else {
minute=00;
}
minshow.setText(":"+String.valueOf(minute));
diff = diff/60;
if (diff >= 1) {
hour = (int) (diff%24);
} else {hour = 00; }
hourshow.setText(String.valueOf(hour));
t=(t*60*60)-1;
handler.postDelayed(this, 1000);
}
};
handler.post(updater);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
handler.removeCallbacks(updater);
}
}
but its showing some values.but they are not correct.kindly help me.I dont understand error in this code.Thanks in advance

Android saved activity state in onResume?

How do I record the start time of the stopWatch using system.currentTimeMillis? when your activity onResume() or onStart() is called, how do I update the watch to show the time that elapsed from the time it's saved? Thanks. What I have tried so far without onResume():
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.stopwatch);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.clock32);
// initializes controls
initControls();
// sets format for chronometer
chronometer.setText( "00:00:00" );
}
private void initControls(){
// initializes buttons & chronometer
pause = ( Button ) findViewById ( R.id.btStopWatchPause );
stop = ( Button ) findViewById ( R.id.btStopWatchStop );
start = ( Button) findViewById ( R.id.btStopWatchStart );
reset = ( Button ) findViewById ( R.id.btStopWatchReset );
chronometer = ( Chronometer ) findViewById ( R.id.chronometer );
// sets listeners for buttons and chronometer
pause.setOnClickListener(this);
stop.setOnClickListener(this);
start.setOnClickListener(this);
reset.setOnClickListener(this);
chronometer.setOnChronometerTickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch( v.getId() )
{
case R.id.btStopWatchStart:
chronometer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
chronometer.start();
break;
case R.id.btStopWatchStop:
chronometer.stop();
break;
case R.id.btStopWatchReset:
chronometer.setBase(SystemClock.elapsedRealtime());
break;
case R.id.btStopWatchPause:
timeWhenStopped = chronometer.getBase() - SystemClock.elapsedRealtime();
chronometer.stop();
break;
} // end of switch statement
}
public void onChronometerTick(Chronometer c) {
// TODO Auto-generated method stub
CharSequence text = c.getText();
if ( text.length() == 5 ) {
c.setText( "00:" + text );
} else if ( text.length() == 7 ) {
c.setText( "0" + text );
}
} // end of onChronometerTick method
#Override
protected void onResume() {
super.onResume();
TimeForActivity.StartTimer(AccountingTab.this);
public class TimeForActivity implements Constants{
public static void StartTimer(Context context, TextView aTvTime, Button aBtUserStatus, ProgressDialog aProgressDialog, String sessionID) {
mHandler.removeCallbacks(mUpdateTimeTask);
activity = context;
tvTime = aTvTime;
btUserStatus = aBtUserStatus;
tvTime.setText("");
btUserStatus.setText(statusItems[userStatus - 1]);
btUserStatus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showStatusDialog();
}
});
progressDialog = aProgressDialog;
reStartTimer();
}
private static void reStartTimer() {
if (pageConfig.getUserStatusTime() != null && StatusService.methodType != StatusService.GO_OUT) {
if (mStartTime == null)
mStartTime = pageConfig.getUserStatusTime() * 60 * 1000 - SystemClock.elapsedRealtime();
//CommonHelper.showToastMsg(activity, Long.toString(SystemClock.elapsedRealtime()));
//tvUserStatus.setText(Long.toString(SystemClock.uptimeMillis()) + " mStarTime: " + mStartTime);
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
private static Runnable mUpdateTimeTask = new Runnable() {
public void run() {
try {
final long start = mStartTime;
long millis = SystemClock.elapsedRealtime() + start;
long seconds = (long) (millis / 1000);
long hours = seconds / 3600;
seconds -= hours * 3600;
long minutes = seconds / 60;
seconds = seconds % 60;
tvTime.setText(CommonHelper.getTwoDigitTime(hours) + ":" + CommonHelper.getTwoDigitTime(minutes));
//+ ":" + CommonHelper.getTwoDigitTime(seconds));
//java.lang.System.out.println(tvTime.getText().toString());
if (userStatus == StatusService.GO_OUT){
tvTime.setText("");
stopTimer();
}
if (StatusService.methodType != StatusService.GO_OUT)
mHandler.postAtTime(this, SystemClock.elapsedRealtime() + 60*1000);
} catch (Exception e) {
// TODO: handle exception
}
}
};
}

Categories

Resources