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);
}
Related
I have a quiz app which has a timer for the whole game-activity where in you should answer as 20 questions and every qustion have 10 sec ..
after the assigned 20 is over, it will take you to the results activity which shows your score. even after calling score activity toast from main activty will show and score activity will open agian and again.
int score = 0;
int unanswer = 0;
int questionasked = 1;
int maxquestion = 20;
TextView first, operator, second, timeview;
Button A, B, C, D;
int ans = 0;
String t;
DecimalFormat df;
CountDownTimer mCountDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeview = findViewById(R.id.time);
A = findViewById(R.id.A);
A.setOnClickListener(this);
B = findViewById(R.id.B);
B.setOnClickListener(this);
C = findViewById(R.id.C);
C.setOnClickListener(this);
D = findViewById(R.id.D);
D.setOnClickListener(this);
first = findViewById(R.id.first);
second = findViewById(R.id.second);
operator = findViewById(R.id.operator);
df = new DecimalFormat("###.##");
starTimer();
fillValue();
}
main activity code
private void fillValue() {
if (questionasked > maxquestion)
showscore();
questionasked++;
int a = (int) (Math.random() * 50 + 1);
int b = (int) (Math.random() * 50 + 1);
int op = (int) (Math.random() * 4 + 1);
int buttonoption = (int) (Math.random() * 4 + 1);
char operatorcharter = '+';
switch (op) {
case 1:
ans = a + b;
operatorcharter = '+';
break;
case 2:
ans = a - b;
operatorcharter = '-';
break;
case 3:
ans = a * b;
operatorcharter = 'X';
break;
case 4:
ans = (a) / b;
operatorcharter = '/';
break;
//default:
//Toast.makeText(this,op+"",Toast.LENGTH_SHORT).show();
}
//Toast.makeText(this,a+" "+operatorcharter+" "+b+" "+ans+" "+buttonoption,Toast.LENGTH_LONG).show();
operator.setText(operatorcharter + "");
first.setText(a + "");
second.setText(b + "");
t = df.format(ans);
int temp = 0;
switch (buttonoption) {
case 1:
A.setText(t);
break;
case 2:
B.setText(t);
break;
case 3:
C.setText(t);
break;
case 4:
D.setText(t);
break;
//default:
// Toast.makeText(this,buttonoption+" butt",Toast.LENGTH_SHORT).show();
}
for (int i = 1; i <= 4; i++) {
if (i == buttonoption)
continue;
temp = (int) (Math.random() * ans + 1);
if (temp == ans) ;
temp += 5;
String temp1 = df.format(temp);
if (i == 1)
A.setText(temp1 + "");
else if (i == 2)
B.setText(temp1 + "");
else if (i == 3)
C.setText(temp1 + "");
else if (i == 4)
D.setText(temp1 + "");
}
mCountDownTimer.start();
}
private void showscore() {
Intent i = new Intent(this, final_activity.class);
i.putExtra(Contact.maxquestion, maxquestion);
i.putExtra(Contact.score, score);
i.putExtra(Contact.unanswer, unanswer);
mCountDownTimer.cancel();
Toast.makeText(this, "new activity open", Toast.LENGTH_LONG).show();
startActivity(i);
this.finish();
}
#Override
public void onClick(View v) {
Button b = (Button) v;
String clickbuttonvalue = (String) b.getText();
if (clickbuttonvalue.equals(t))
score++;
//Toast.makeText(this,score+" "+clickbuttonvalue ,Toast.LENGTH_LONG).show();
mCountDownTimer.cancel();
fillValue();
}
public void starTimer() {
mCountDownTimer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
timeview.setText("seconds remaining: " + millisUntilFinished / 1000);
Toast.makeText(MainActivity.this, "new" + millisUntilFinished / 1000, Toast.LENGTH_LONG).show();
}
public void onFinish() {
unanswer++;
fillValue();
}
}.start();
}
}
this is my code even after opening new activity and open new activity check method showscore()
plz, help!
You need to override the onDestroy method which will be triggered when the activity is finished(don't forget to add finish() after the startActivty()).
#Override
public void onDestroy() {
super.onDestroy();
mCountDownTimer.cancel();
}
I have tried to make an countdown timer in a list veiw implementation. Each list item has a separate countdown timer that can be started or stopped. However I have noticed that if I add the first timer in list and set its time. When I start the timer it starts two seconds less than the actual time. e.g If I added a count down of 12 seconds. Then it will start counting from 10. But when the countdown is taking place and I add another new timer and set its time, it starts on the exact given time. The new counter starts at the wrong time only when either there is no other counter in the list or when all counters are already stopped and not counting down. Similarly it will only start the right time only when other timers are counting down. Would really appreciate if someone can help me figure out where is the problem. I have been looking at the code for days.
Here's my Adapter class
public class CustomAdapterCounter extends ArrayAdapter<CounterData> {
private final LayoutInflater mInflater;
Context context;
Uri sound = Uri.parse("android.resource://com.tattooalarmclock.free/" + R.raw.counter);
String counterString = "";
private List<ViewHolder> lstHolders;
private List<CounterData> list = new ArrayList<CounterData>();
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
// if(!holder.counterData.isStopped)
holder.updateTimeRemaining(System.currentTimeMillis());
}
}
}
};
public CustomAdapterCounter(Context context, List<CounterData> l) {
super(context, 0, l);
this.context = context;
lstHolders = new ArrayList<>();
list = l;
mInflater = LayoutInflater.from(context);
for(int i=0; i<list.size(); i++) {
CounterData[] array = list.toArray(new CounterData[list.size()]);
if(!array[i].isStopped)
startUpdateTimer();
}
}
public double getScreenSize() {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
int dens = dm.densityDpi;
double wi = (double) width / (double) dens;
double hi = (double) height / (double) dens;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
double screenInches = Math.sqrt(x + y);
return screenInches;
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
T[] arr = new Gson().fromJson(s, clazz);
return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}
public boolean getListSharedPreferences() {
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getString("CL", null) != null) {
counterString = sharedPreferences.getString("CL", null);
Gson gson = new Gson();
TypeToken<List<CounterData>> token = new TypeToken<List<CounterData>>() {};
list = gson.fromJson(counterString, token.getType());
return true;
}
else
return false;
}
public void saveListSharedPreferences(List counterList) {
Gson gson = new Gson();
counterString = gson.toJson(counterList);
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("CL", counterString).commit();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
if(getScreenSize() <= 4 )
convertView = mInflater.inflate(R.layout.list_view_counter_small, parent, false);
else
convertView = mInflater.inflate(R.layout.list_view_item_counter, parent, false);
holder.counterTextView = (TextView) convertView.findViewById(R.id.counterTextView);
holder.stopCounter = (Button) convertView.findViewById(R.id.counterStopInList);
holder.startCounter = (Button) convertView.findViewById(R.id.counterStartInList);
holder.deleteCounter = (Button) convertView.findViewById(R.id.deleteCounter);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.setData2(getItem(position));
final ViewHolder finalHolder = holder;
holder.stopCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long store = finalHolder.counterData.expirationTime - System.currentTimeMillis();
finalHolder.counterData.isStopped = true;
finalHolder.counterData.expirationTime = store;
finalHolder.stopCounter.setEnabled(false);
finalHolder.stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
/* if(getListSharedPreferences()) {
System.out.println("List before change in stop button " + list.toString());
list = stringToArray(counterString, CounterData[].class);
list.set(position, finalHolder.counterData);
System.out.println("List before change in stop button " + list.toString());
saveListSharedPreferences(list);
}
else {
System.out.println(list.toString());
list.set(position, finalHolder.counterData);
System.out.println(list.toString());
saveListSharedPreferences(list);
}
*/
}
});
holder.startCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
finalHolder.counterData.isStopped = false;
//finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
//finalHolder.setData(finalHolder.counterData);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.stopCounter.setEnabled(true);
finalHolder.stopCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
startUpdateTimer();
/* if(getListSharedPreferences()) {
list = stringToArray(counterString, CounterData[].class);
System.out.println("List before change in start button " + list.toString());
list.set(position, finalHolder.counterData);
System.out.println("List after change in start button " + list.toString());
saveListSharedPreferences(list);
}
else {
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
} */
}
});
final ViewHolder finalHolder1 = holder;
holder.deleteCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* if(finalHolder1.mediaPlayer.isPlaying()) {
finalHolder.mediaPlayer.stop();
// finalHolder.counterData.isSoundPlayedBefore = true;
} */
list.remove(position);
notifyDataSetChanged();
saveListSharedPreferences(list);
}
});
return convertView;
}
}
class ViewHolder {
public TextView counterTextView;
//public List<Long> l;
CounterData counterData;
Button startCounter;
Button stopCounter;
Button deleteCounter;
boolean stop = false;
long timeDiff;
// Context context;
// MediaPlayer mediaPlayer;
// List<CounterData> counterDataList;
public void setData(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void setData2(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void updateTimeRemaining(long currentTime) {
if (!counterData.isStopped) {
timeDiff = counterData.expirationTime - currentTime;
//System.out.println("Time Diff Inside Method " + timeDiff);
if (timeDiff > 0) {
int seconds = (int) (timeDiff / 1000) % 60;
int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(timeDiff);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
stopCounter.setEnabled(true);
stopCounter.getBackground().setColorFilter(null);
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
} else {
counterTextView.setText("Times Up");
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
// Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
// v.vibrate(5000);
/* if(!counterData.isSoundPlayedBefore) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
}
});
counterData.isSoundPlayedBefore = true;
if(findIndex(counterData) != -1) {
int index = findIndex(counterData);
counterDataList.set(index,counterData);
saveListSharedPreferences(counterDataList);
}
} */
}
}
else {
long store = counterData.expirationTime + System.currentTimeMillis() - currentTime;
int seconds = (int) (store / 1000) % 60;
int minutes = (int) ((store / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(store);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
startCounter.setEnabled(true);
startCounter.getBackground().setColorFilter(null);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
}
}
}
And here's my CounterData class
class CounterData {
long expirationTime;
boolean isStopped;
boolean isSoundPlayedBefore;
int id;
public CounterData(long expirationTime, int id) {
this.expirationTime = expirationTime;
isStopped = true;
isSoundPlayedBefore = false;
this.id = id;
}
public String toString() {
return String.valueOf("Remaining Time: " + TimeUnit.MILLISECONDS.toMinutes(this.expirationTime) + ":" + TimeUnit.MILLISECONDS.toSeconds(this.expirationTime));
}
public void setCounterID(int id) {
this.id = id;
}
public int getCounterID() {
return this.id;
}
}
And I add the time from number pickers of Hour, Minute and Second.
case R.id.counterStartStopButton:
long hour = TimeUnit.HOURS.toMillis(numberPickerHour.getValue());
long minute = TimeUnit.MINUTES.toMillis(numberPickerMinute.getValue());
long second = TimeUnit.SECONDS.toMillis(numberPickerSecond.getValue());
// if(getListSharedPreferences()) {
if(getCounterIDSharedPreferences()) {
counterID = counterID + 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
else {
counterID = 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
UPDATE
Here's the shared preferences code
public void saveCounterIDSharedPreferences(int id) {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putInt("Counter ID123", id).commit();
}
public boolean getCounterIDSharedPreferences() {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getInt("Counter ID123", -1) != -1) {
counterID = sharedPreferences.getInt("Counter ID123", -1);
return true;
}
else
return false;
}
What turned out to work for me was changing the timer task as following:
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 500, 500);
}
I wrote a little android program, there is a main activity with a broadcast listener, and i create another thread. The thread searches for prime numbers, and loading them into a long arraylist, and after every 3 seconds, sends the filled array to the main activity via broadcast. Everythings ok, until i'm trying to get the long array extra from the intent. It causes every time a nullpointerexception.
I tried with a string arraylist, it worked, but i am curious because the intent has an "getlongarrayextra" method.
Here is my code:
public class MainActivity extends Activity {
public static String BROADCAST_THREAD_KEY = "broadcast_key";
public static String EXTRAARRAYID = "primes";
private static long MAXNUM = 2000000;
private PrimeCalculatorThread thread;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.numberstext);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(android.content.Context context,
android.content.Intent intent) {
String origitext = textView.getText().toString();
long[] primes = intent.getExtras().getLongArray(EXTRAARRAYID);
Log.d("ASD", "broadcast received" + primes.toString());
StringBuilder builder = new StringBuilder();
if (primes != null) {
for (long prime : primes) {
builder.append(prime + " - ");
}
textView.setText(origitext + "\n" + builder.toString());
}
};
};
#Override
protected void onResume() {
Log.d("ASD", "ONRESUME");
initReceiverAndStartThread();
super.onResume();
}
private void initReceiverAndStartThread() {
IntentFilter filter = new IntentFilter(BROADCAST_THREAD_KEY);
registerReceiver(receiver, filter);
thread = new PrimeCalculatorThread(getBaseContext(), MAXNUM);
thread.start();
Log.d("ASD", "THREAD STARTED");
}
and the second thread:
public class PrimeCalculatorThread extends Thread {
private Context context;
private long maxnum;
List<Long> primes;
boolean isrunning;
public void setIsrunning(boolean isrunning) {
this.isrunning = isrunning;
}
private long counter = 0;
private long DELAYBETWEENBROADCAST = 3000;
public PrimeCalculatorThread(Context c, long maxnum) {
this.context = c;
this.maxnum = maxnum;
primes = new ArrayList<Long>();
}
#Override
public void run() {
long startTime = System.currentTimeMillis();
long estimatedTime;
isrunning = true;
for (long i = 0; i < maxnum; i++) {
Log.d("ASD", Boolean.toString(isrunning));
if (!isrunning)
break;
Log.d("ASD", i + "");
estimatedTime = System.currentTimeMillis() - startTime;
if (isPrime(i)) {
primes.add(i);
Log.d("ASD", i + "is a prime");
} else {
Log.d("ASD", i + "is not a prime");
}
if (estimatedTime > counter * DELAYBETWEENBROADCAST
+ DELAYBETWEENBROADCAST) { // elapsed another period
Log.d("ASD", primes.toString() + " will be sending.");
sendBroadCast();
primes.clear();
counter++;
}
try { //for debug purposes
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void sendBroadCast() {
Intent intent = new Intent(MainActivity.BROADCAST_THREAD_KEY);
intent.putExtra(MainActivity.EXTRAARRAYID, primes.toArray());
context.sendBroadcast(intent);
Log.d("ASD", "BROADCAST SENT" + primes.toString());
}
boolean isPrime(long n) {
if (n < 2)
return false;
if (n == 2 || n == 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
long sqrtN = (long) Math.sqrt(n) + 1;
for (long i = 6L; i <= sqrtN; i += 6) {
if (n % (i - 1) == 0 || n % (i + 1) == 0)
return false;
}
return true;
}
}
The problem is that you are managing a list of Long objects and passing it in putExtra, which means you are invoking putExtra(String name, Serializable value). Then you try to get that value using getLongArray(), but you haven't put any long array extra, you see! To solve this, replace
intent.putExtra(MainActivity.EXTRAARRAYID, primes.toArray());
with
long[] primesArray = new long[primes.size()];
for (int i = 0; i < primes.size(); i++) {
primesArray[i] = primes.get(i);
}
intent.putExtra(MainActivity.EXTRAARRAYID, primesArray);
This will invoke the correct putExtra(String name, long[] value) method.
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
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
}
}
};
}