I have this code where I made 2 buttons, one to set an alarm and one for checking the time left until the alarm going off. Currently, I'm struggling with the second button which checking the timer. Can someone help me out?
Here's my code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
Button button2 = (Button) findViewById(R.id.button2);
final TextView lefty = (TextView)findViewById(R.id.left);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
Long preTime = calendar.getTimeInMillis();
calendar.add(Calendar.HOUR_OF_DAY,8);
Long postTime = calendar.getTimeInMillis();
Long delay = postTime - preTime;
Intent intent = new Intent(getApplicationContext(),NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
CountDownTimer timer = new CountDownTimer(delay, 1) {
#Override
public void onTick(long millisUntilFinished) {
final int seconds = (int) (millisUntilFinished / 1000) % 60;
final int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
final int hour = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
runOnUiThread(new Runnable() {
#Override
public void run() {
lefty.setText( hour + " : " + minutes + " : " + seconds);
}
});
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
timer.start();
}
});
button2.setOnClickListener(new View.OnClickListener() {
"some code"
}
}
For do my answer and help you, i will completing your code and add a TextView for exemple for put the time on it.
public class MainActivity extends AppCompatActivity {
// modify here
private Calendar myTimer = null;
private TextView myTextView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
Button button2 = (Button) findViewById(R.id.button2);
final TextView lefty = (TextView)findViewById(R.id.left);
// modify here
myTextView = (TextView) findViewById(R.id.my_text_view);
myTimer = Calendar.getInstance();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
Long preTime = calendar.getTimeInMillis();
calendar.add(Calendar.HOUR_OF_DAY, 8);
Long postTime = calendar.getTimeInMillis();
Long delay = postTime - preTime;
Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
CountDownTimer timer = new CountDownTimer(delay, 1) {
#Override
public void onTick(long millisUntilFinished) {
final int seconds = (int) (millisUntilFinished / 1000) % 60;
final int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
final int hour = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
// modify here
myTimer.set(Calendar.SECOND, seconds);
myTimer.set(Calendar.MINUTE, minutes);
myTimer.set(Calendar.HOUR, hour);
runOnUiThread(new Runnable() {
#Override
public void run() {
lefty.setText(hour + " : " + minutes + " : " + seconds);
}
});
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
timer.start();
}
});
// modify here
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myString = new SimpleDateFormat("hh : mm : ss").format(myTimer);
myTextView.setText(myString);
}
});
}
}
Related
am getting a black screen when loading a new activity which contains mediaplayer with an mp3 from a URL. if internet is fast e.g 4G , everything is okay and it takes a few seconds to load. but if internet is slow. e.g 2g and 3g , it takes very long and brings a black screen . i need the activity to load without internet, without the black screen. please help me with what i can change on this code
Button download;
private ImageView imagePlayPause;
private TextView textCurrentTime, textTotalDuration;
private SeekBar playerSeekBar;
private MediaPlayer mediaPlayer;
private final Handler handler = new Handler();
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ct);
download = findViewById(R.id.download);
download.setOnClickListener(view -> gotoUrl("https://www.facebook.com/davidsibandeRN"));
ImageView imageView3=findViewById(R.id.ImageView3);
String url ="https://dl.dropboxusercontent.com/s/ruo77t7o3dyggpd/parotitis.png?dl=1";
Picasso.get().load(url).placeholder(R.drawable.ic_launcher_background).into(imageView3);
imagePlayPause = findViewById(R.id.imagePlayPause);
textCurrentTime = findViewById(R.id.textCurrentTime);
textTotalDuration = findViewById(R.id.textTotalDuration);
playerSeekBar = findViewById(R.id.playerSeekBar);
mediaPlayer = new MediaPlayer();
playerSeekBar.setMax(100);
imagePlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mediaPlayer.isPlaying()) {
handler.removeCallbacks(updater);
mediaPlayer.pause();
imagePlayPause.setImageResource(R.drawable.ic_baseline_play_arrow_24);
} else {
mediaPlayer.start();
imagePlayPause.setImageResource(R.drawable.ic_baseline_pause_24);
updateSeekBar();
}
}
});
prepareMediaPlayer();
playerSeekBar.setOnTouchListener(new View.OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
SeekBar seekBar = (SeekBar) view;
int playPosition = (mediaPlayer.getDuration() / 100) * seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
textCurrentTime.setText(milliSecondsToTimer(mediaPlayer.getCurrentPosition()));
return false;
}
});
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
playerSeekBar.setSecondaryProgress(i);
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
playerSeekBar.setProgress(0);
imagePlayPause.setImageResource(R.drawable.ic_baseline_play_arrow_24);
textCurrentTime.setText(R.string.zero);
textTotalDuration.setText(R.string.zero);
mediaPlayer.reset();
prepareMediaPlayer();
}
});
}
private void gotoUrl(String s) {
Uri uri = Uri.parse(s);
startActivity(new Intent(Intent.ACTION_VIEW,uri));
}
private void prepareMediaPlayer() {
try {
mediaPlayer.setDataSource("https://dl.dropboxusercontent.com/s/tnl4o8isv74rcjb/5.%20parotitis.mp3?dl=1");
mediaPlayer.prepare();
textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
} catch (Exception exception) {
Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private final Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
long currentDuration = mediaPlayer.getCurrentPosition();
textCurrentTime.setText(milliSecondsToTimer(currentDuration));
}
};
private void updateSeekBar() {
if (mediaPlayer.isPlaying()) {
playerSeekBar.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration()) * 100));
handler.postDelayed(updater, 1000);
}
}
private String milliSecondsToTimer(long milliSeconds) {
String timerString = "";
String secondString;
int hours = (int) (milliSeconds / (1000 * 60 * 60));
int minutes = (int) (milliSeconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliSeconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
if (hours > 0) {
timerString = hours + ":";
}
if (seconds < 10) {
secondString = "0" + seconds;
} else {
secondString = "" + seconds;
}
timerString = timerString + minutes + ":" + secondString;
return timerString;
}
#Override
public void onBackPressed() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
super.onBackPressed();
}
}
I am making a reminder app. It has an activity where you see your alarms and a floating action button in it to add new alarm. From that button my custom dialog opens up to set an alarm. It is supposed to return the hour and minute selected in the TimePicker but instead it returns the current hour and minute
This is the class:
public class AlarmKurDialog extends AppCompatDialogFragment {
TimePicker timePicker;
SeekBar seekBar;
TextView bardakAdetiTxt;
Button alarmEkleBtn;
int quantity;
int hour;
int minute;
AlarmKurDialogListener listener;
public interface AlarmKurDialogListener{
void alarmBilgisiGetir(int hour, int minute, int quantity);
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_alarm_kur, null);
builder.setView(view);
timePicker = view.findViewById(R.id.timePicker1);
seekBar = view.findViewById(R.id.seekBar);
bardakAdetiTxt = view.findViewById(R.id.txt_adet);
alarmEkleBtn = view.findViewById(R.id.button);
timePicker.setIs24HourView(true);
if (Build.VERSION.SDK_INT >= 23 ) {
// getHour and getMinute returns current hour and minute
hour = timePicker.getHour();
minute = timePicker.getMinute();
Log.i("mert", "getHour:getMinute - " + hour + ":" + minute);
}
else {
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
Log.i("mert", "getCurrentHour:getCurrentMinute - " + hour + ":" + minute);
}
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
quantity = 1 + progress;
bardakAdetiTxt.setText(String.valueOf(quantity));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
alarmEkleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.alarmBilgisiGetir(hour, minute, quantity);
dismiss();
}
});
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
listener = (AlarmKurDialogListener) context;
}catch (ClassCastException e){
throw new ClassCastException(context.toString() + "AlarmKurDialogListener implement etmek gerekli");
}
}}
What am I doing wrong here?
try this :
alarmEkleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hour = timePicker.getHour();
minute = timePicker.getMinute();
listener.alarmBilgisiGetir(hour, minute, quantity);
dismiss();
}
});
This portion of your code is inside of onCreateDialog method:
if (Build.VERSION.SDK_INT >= 23 ) {
// getHour and getMinute returns current hour and minute
hour = timePicker.getHour();
minute = timePicker.getMinute();
Log.i("mert", "getHour:getMinute - " + hour + ":" + minute);
}
else {
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
Log.i("mert", "getCurrentHour:getCurrentMinute - " + hour + ":" + minute);
}
Which means that you are assigning a value to hour and minute AT THE MOMENT of the dialog's creation, at which point it just returns the current time. What you want to do is move that whole block of code inside of the submit button's on click listener:
alarmEkleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// --------------->>>>>PUT THAT CODE HERE INSTEAD! <<<<<-------------------------
listener.alarmBilgisiGetir(hour, minute, quantity);
dismiss();
}
});
This way you'll actually get the latest set value from the picker.
I am trying to set a timer in my Snackbar, I have tried this so far and gotten the timer to work but not in the getTime() method which I think might be the case which is why this isn't working.
I am sorry if this is too bad of a question, I only do Android as a side project.
public class MainActivity extends AppCompatActivity {
private static final String AUDIO_RECORDER_FILE_EXT = ".3gp";
private static final String AUDIO_RECORDER_FOLDER = "VRemind";
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_format = MediaRecorder.OutputFormat.THREE_GPP;
private String file_ext = AUDIO_RECORDER_FILE_EXT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CountDownTimer t;
t = new CountDownTimer( Long.MAX_VALUE , 1000) {
int cnt=0;
#Override
public void onTick(long millisUntilFinished) {
cnt++;
long millis = cnt;
int seconds = (int) (millis / 60);
setTime(cnt);
Log.d("Count:", ""+cnt);
}
#Override
public void onFinish() {
}
};
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Snackbar snackbar = Snackbar.make(findViewById(R.id.root_layout), getTime(), Snackbar.LENGTH_INDEFINITE);
final FloatingActionButton fabAdd = (FloatingActionButton) findViewById(R.id.fabAdd);
final FloatingActionButton fabStop = (FloatingActionButton) findViewById(R.id.fabStop);
fabAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.start();
fabAdd.setVisibility(View.GONE);
fabStop.setVisibility(View.VISIBLE);
snackbar.show();
snackbar.setAction("CANCEL", new View.OnClickListener() {
#Override
public void onClick(View v) {
snackbar.dismiss();
fabAdd.setVisibility(View.VISIBLE);
fabStop.setVisibility(View.GONE);
}
});
}
});
fabStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
snackbar.dismiss();
fabStop.setVisibility(View.GONE);
fabAdd.setVisibility(View.VISIBLE);
}
});
}
private String display;
public void setTime(int rawCount) {
int rc = rawCount;
int minutes = (rc - (rc % 60)) / 60;
int seconds = (rc % 60);
String mins = String.format(Locale.ENGLISH, "%02d", minutes);
String secs = String.format(Locale.ENGLISH, "%02d", seconds);
display = mins+ ":" +secs;
Log.d("CountTwo:",display);
getTime();
}
public String getTime() {
Log.d("Count getTime:", display);
return display;
}
Are you getting this message?
java.lang.NullPointerException: println needs a message
If yes it is because you try to log a null message like this:
Log.d("Count getTime:", display);
You have to initialize the display variable to have a value for the first run.
private String display = "";
I looked into it and the problem was that the String display was inaccessible to the Snackbar and also the Snackbar test was unable to update dynamically so I did both of those and made a few changes here and there and here's my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CountDownTimer t;
t = new CountDownTimer( Long.MAX_VALUE , 1000) {
int cnt=0;
#Override
public void onTick(long millisUntilFinished) {
cnt++;
long millis = cnt;
int seconds = (int) (millis / 60);
setTime(cnt);
Log.d("Count:", ""+cnt);
}
#Override
public void onFinish() {
cnt = 0;
}
};
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
snackbar = Snackbar.make(findViewById(R.id.root_layout), "", Snackbar.LENGTH_INDEFINITE);
final FloatingActionButton fabAdd = (FloatingActionButton) findViewById(R.id.fabAdd);
final FloatingActionButton fabStop = (FloatingActionButton) findViewById(R.id.fabStop);
fabAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.start();
fabAdd.setVisibility(View.GONE);
fabStop.setVisibility(View.VISIBLE);
snackbar.show();
snackbar.setAction("CANCEL", new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
t.onFinish();
// setTime(0);
snackbar.dismiss();
fabAdd.setVisibility(View.VISIBLE);
fabStop.setVisibility(View.GONE);
}
});
}
});
fabStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
t.onFinish();
// setTime(0);
snackbar.dismiss();
fabStop.setVisibility(View.GONE);
fabAdd.setVisibility(View.VISIBLE);
}
});
}
/*
public void Duration() {
*//* Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
int count;
#Override
public void run() {
setTime(count);
count++;
Log.d("Count:", ""+count);
}
});
}
};*//* //Old code removed on 22Apr17#11:41PM
}*/ //Old code Duration method
String display="";
public void setTime(int rawCount) {
// int rc = rawCount;
int minutes = (rawCount - (rawCount % 60)) / 60;
int seconds = (rawCount % 60);
String mins = String.format(Locale.ENGLISH, "%02d", minutes);
String secs = String.format(Locale.ENGLISH, "%02d", seconds);
display = mins+ ":" +secs;
Log.d("CountTwo:",display);
snackbar.setText(display);
}
/*public String getTime() {
Log.d("Count getTime:", display);
return display;
}*/
I'm very new to Android Studio and I am building a simple countdown timer app. I have 2 activities. The first activity(Login) the user picks a date through date picker, the second activity(Profile) shows a countdown timer. The countdown timer works perfectly when I set a date for it in the java class, but i'm having trouble trying to retrieve the date from the login activity. My code for both activities is below.
I know I have to alter the Date futureDate = dateFormat.parse("2016-8-10"); but I'm not sure how.
LOGIN.CLASS
public class Login extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, OnClickListener {
//private SharedPreferences sp;
EditText enterusername;
Button continuetoprofile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
/*sp = getSharedPreferences("myPreference" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("myKey" , "I am data to store");
editor.commit();
Writing data to SharedPreferences*/
enterusername = (EditText) findViewById(R.id.enterusername);
continuetoprofile=(Button) findViewById(R.id.continuetoprofile);
continuetoprofile.setOnClickListener(this);
}
//SHARED PREFERENCES
/*public void saveInfo(View view){
SharedPreferences save = getSharedPreferences("name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = save.edit();
editor.putString("username",enterusername.getText().toString());
editor.apply();
}*/
public void onClick (View v){
Intent intent = new Intent(this,Profile.class);
intent.putExtra("username", enterusername.getText().toString());
startActivity(intent);
}
public void datePicker(View view){
DatePickerFragment fragment = new DatePickerFragment();
fragment.show(getSupportFragmentManager(), "date");
}
private void setDate(final Calendar calendar) {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
((TextView) findViewById(R.id.showDate)).setText(dateFormat.format(calendar.getTime()));
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar cal = new GregorianCalendar(year, month, day);
setDate(cal);
}
public static class DatePickerFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(),
(DatePickerDialog.OnDateSetListener)
getActivity(), year, month, day);
}
}
Intent intent = getIntent();
public void privPol(View view){
Intent intent = new Intent(this, PrivacyPolicy.class);
startActivity(intent);
}
public void TOU(View view){
Intent intent = new Intent(this, TermsOfUse.class);
startActivity(intent);
}
public void toProfile(View view){
Intent intent = new Intent(this, Profile.class);
startActivity(intent);
}
PROFILE.CLASS
public class Profile extends AppCompatActivity {
//private SharedPreferences spref;
//TextView nameofuser;
TextView nameofuser;
private TextView daystxt, hourstxt, minutestxt, secondstxt;
private Handler handler;
private Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
initUI();
countDownStart();
nameofuser = (TextView)findViewById(R.id.nameofuser);
Intent intent = getIntent();
String username = intent.getStringExtra("username");
nameofuser.setText("Welcome, " + username);
}
#SuppressLint("SimpleDateFormat")
private void initUI() {
daystxt = (TextView) findViewById(R.id.days);
hourstxt = (TextView) findViewById(R.id.hours);
minutestxt = (TextView) findViewById(R.id.minutes);
secondstxt = (TextView) findViewById(R.id.seconds);
}
public void countDownStart() {
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 1000);
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Here Set your Event Date
Date futureDate = dateFormat.("2016-8-10");
Date currentDate = new Date();
if (!currentDate.after(futureDate)) {
long diff = futureDate.getTime()
- currentDate.getTime();
long days = diff / (24 * 60 * 60 * 1000);
diff -= days * (24 * 60 * 60 * 1000);
long hours = diff / (60 * 60 * 1000);
diff -= hours * (60 * 60 * 1000);
long minutes = diff / (60 * 1000);
diff -= minutes * (60 * 1000);
long seconds = diff / 1000;
daystxt.setText("" + String.format("%02d", days));
hourstxt.setText("" + String.format("%02d", hours));
minutestxt.setText("" + String.format("%02d", minutes));
secondstxt.setText("" + String.format("%02d", seconds));
} else {
handler.removeCallbacks(runnable);
// handler.removeMessages(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.postDelayed(runnable, 0);
}
Intent intent = getIntent();
public void toMenu(View view) {
Intent intent = new Intent(this, Menu.class);
startActivity(intent);
}
public void tostartdate(View view) {
Intent intent = new Intent(this, EditStartdate.class);
startActivity(intent);
}
//Get the date
Date buttonDate = SimpleDateFormat.getDateInstance().parse(mDate.getText().toString());
and
//Create a bundle to pass the date and send your date as Long
Bundle currentDate = new Bundle();
currentDate.putLong("setDate", buttonDate.getTime());
and
//Read the passed bundle from the next activity get Long and convert it to Date
Bundle setDate = this.getArguments();
Long currDate = setDate.getLong("setDate");
Note :
The Date constructor accepts the time as long in milliseconds, not seconds. You need to multiply it by 1000 and make sure that you supply it as long.
conversion
Date d = new Date(1220227200L * 1000);
Try using the putExtras() method to pass it through the Intent in a Bundle.
The following code will help out:
Sending Data through Bundle
Intent i = new Intent(this, ActivityTwo.class);
Bundle bundle = new Bundle();
bundle.putExtras("Date",YOUR_DATE);
i.putExtras(bundle);
startActivity(i);
Getting Data in new Activity
Bundle bundle = getIntent().getExtras();
String date = bundle.getString(“Date”);
This will help
I am supernoob programmer. I'm trying to make an adroid interval timer, where user inputs rounds, work time and break time. I can't find a way to start break timer after work timer, they start running at the same time. How should I go about it?
Thanks!
public class MainActivity extends Activity {
EditText rundy, praca, przerwa;
Button start;
TextView timer;
boolean timerHasStarted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rundy = (EditText) findViewById(R.id.rundy); // rounds
praca = (EditText) findViewById(R.id.praca); // work time
przerwa = (EditText) findViewById(R.id.przerwa); // break time
start = (Button) findViewById(R.id.start);
timer = (TextView) findViewById(R.id.timer);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int rundyL = Integer.parseInt(rundy.getText().toString())*1000;
long pracaL = Long.parseLong(praca.getText().toString()) * 1000;
long przerwaL = Long.parseLong(przerwa.getText().toString())*1000;
MyCountDownTimer countDownTimerPraca = new MyCountDownTimer(pracaL, 1000);
MyCountDownTimer countDownTimerPrzerwa = new MyCountDownTimer(przerwaL,1000);
for(int i = 0; i<rundyL; i++){
countDownTimerPraca.start();
countDownTimerPrzerwa.start();
}
}
class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long pracaL, long interval) {
super(pracaL, interval);
}
#Override
public void onTick(long millisUntilFinished) {
timerHasStarted = true;
long minutes = (millisUntilFinished / 1000)/60;
long seconds = (millisUntilFinished/1000)%60;
timer.setText( String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
}
#Override
public void onFinish() {
timerHasStarted = false;
timer.setText("Times up");
}
}
});
}
}
public class MainActivity extends Activity {
EditText rundy, praca, przerwa;
Button start;
TextView timer;
boolean timerHasStarted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rundy = (EditText) findViewById(R.id.rundy); // rounds
praca = (EditText) findViewById(R.id.praca); // work time
przerwa = (EditText) findViewById(R.id.przerwa); // break time
start = (Button) findViewById(R.id.start);
timer = (TextView) findViewById(R.id.timer);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int rundyL = Integer.parseInt(rundy.getText().toString())*1000;
long pracaL = Long.parseLong(praca.getText().toString()) * 1000;
long przerwaL = Long.parseLong(przerwa.getText().toString())*1000;
MyCountDownTimer countDownTimerPrzerwa = new MyCountDownTimer(przerwaL,1000);
MyCountDownTimer countDownTimerPraca = new MyCountDownTimer(countDownTimerPrzerwa,pracaL, 1000);
for(int i = 0; i<rundyL; i++){
countDownTimerPraca.start();
}
}
class MyCountDownTimer extends CountDownTimer {
private MyCountDownTimer mytimer;
public MyCountDownTimer(long pracaL, long interval) {
super(pracaL, interval);
}
public MyCountDownTimer(MyCountDownTimer timer, long pracaL, long interval) {
this(pracaL, interval);
this.timer = timer;
}
#Override
public void onTick(long millisUntilFinished) {
timerHasStarted = true;
long minutes = (millisUntilFinished / 1000)/60;
long seconds = (millisUntilFinished/1000)%60;
timer.setText( String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
}
#Override
public void onFinish() {
timerHasStarted = false;
timer.setText("Times up");
if(mytimer!=null)
mytimer.start();
}
}
});
}
}