I want find the seconds between the current time and a date selected from a a calendar view. My current method goes as follows
mCalculateButton = (Button) findViewById(R.id.calcButton);
mDatePicker = (CalendarView) findViewById(R.id.calendarView);
mCalculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Grabbing the date selected from the CalendarView to send to intent
long age = mDatePicker.getDate();
startCalculation(age);
}
});
}
private void startCalculation(long age){
Intent intent = new Intent(this, CalcActivity.class);
intent.putExtra("key_age", age);
startActivity(intent);
}
and in the calculations activity
Intent intent = getIntent();
//Date selected in MSUE
mSelectedTime = intent.getLongExtra("key_age", 0);
//Current date in MSUE
mCurrTime = System.currentTimeMillis();
mSecondsInfo = (TextView) findViewById(R.id.secondsInfo);
mDaysInfo = (TextView) findViewById(R.id.daysInfo);
mMonthsInfo = (TextView) findViewById(R.id.monthsInfo);
mYearsInfo = (TextView) findViewById(R.id.yearsInfo);
//Replacing format specifiers with desired age information
mSecondsInfo.setText(mSecondsInfo.getText().toString().replace("%i%", Long.toString(ageInSeconds(mSelectedTime, mCurrTime))));
mDaysInfo.setText(mDaysInfo.getText().toString().replace("%i%", Long.toString(ageInDays(mSelectedTime, mCurrTime))));
mMonthsInfo.setText(mMonthsInfo.getText().toString().replace("%i%", Long.toString(ageInMonths(mSelectedTime, mCurrTime))));
mYearsInfo.setText(mYearsInfo.getText().toString().replace("%i%", Long.toString(ageInYears(mSelectedTime, mCurrTime))));
}
private long ageInSeconds(long mil, long currTime){
return (currTime - mil) / 1000;
}
private long ageInDays(long mil, long currTime){
return (currTime - mil)/ 1000 / 60 / 60 / 24;
}
private long ageInMonths(long mil, long currTime){
return (currTime - mil) / 1000 / 60 / 60 / 24/ 30;
}
private long ageInYears(long mil, long currTime){
return (currTime - mil) / 1000 / 60 / 60 / 24/ 30 / 12;
}
The issue is that the time returned by mDatePicker.getDate only increases by ~4000 milliseconds each day that it increments and I have no idea why. Any ideas as of to why this does not work?
CalendarView is not storing the selected date, but you can listen to the selection event and store it yourself.
mDatePicker .setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
storedDate = new GregorianCalendar(year,month,dayOfMonth);
}
});
mCalculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startCalculation(storedDate.getTimeInMillis());
}
});
Related
I am trying to create a timer for user-generated posts that is displayed on the posts. I am using Firestore to store all of the information about the posts.
The code I have does display the timer but when multiple posts are made by multiple users the timer flashes between the correct time and another count down which is unrelated as far as I can see. Here is what I have:
This is how I create each post.
post.setTimer(data.getStringExtra("timerDuration"));
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, setEndDate());
Date endtime = cal.getTime();
post.setTimerEndDate(endtime);
addPhotoInfoToDatabase();
finish();
My Adapter for the Fragment:
adapter = new FirestoreRecyclerAdapter<Post, PostViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull PostViewHolder postViewHolder, int position, #NonNull Post post) {
postViewHolder.setPost(post);
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_layout, parent, false);
return new PostViewHolder(view);
}
};
If there is more information you need please let me know. Thank you for any help.
Edit:
My app also contains a ViewPager and I have noticed that when I swipe away from the problem timer and swipe back the issue is fixed.
Update:
void setPost(final Post post) {
ImageView imageView1 = view.findViewById(R.id.firstImageCardView);
ImageView imageView2 = view.findViewById(R.id.secondImageCardView);
ImageView profilePic = view.findViewById(R.id.user_image);
TextView username = view.findViewById(R.id.user_name);
final TextView timer = view.findViewById(R.id.timer);
final Button chooseRight = view.findViewById(R.id.choose_right);
final Button chooseLeft = view.findViewById(R.id.choose_left);
final Button follow = view.findViewById(R.id.follow);
String displayName;
final String userId = currentUser.getUid();
final String postId = post.getUserId();
setProfilePicture(post);
final DocumentReference docRefUsers = db
.collection("users")
.document(currentUser.getUid());
final DocumentReference docRefFollowing = db
.collection("following")
.document(currentUser.getUid())
.collection("UserIsFollowing")
.document(post.getUserId());
final DocumentReference docRefPosts = db
.collection("posts")
.document(post.getUserId())
.collection("userPosts")
.document(post.getDate().toString());
if (userId.equals(postId)) {
displayName = "Me";
chooseLeft.setEnabled(false);
chooseRight.setEnabled(false);
follow.setText("");
follow.setEnabled(false);
} else if (post.getUsername() == null) {
displayName = "Anonymous";
} else {
displayName = post.getUsername();
}
if (post.getProfilePicture() != null) {
Picasso.get().load(post.getProfilePicture())
.transform(new CircleTransformActivity())
.fit()
.centerCrop()
.into(profilePic);
username.setText(displayName);
} else {
Picasso.get().load(R.drawable.blank_profile_pic)
.transform(new CircleTransformActivity())
.fit()
.into(profilePic);
}
/***********************************************************/
if(post.getTimerEndDate() != null) {
Date date = java.util.Calendar.getInstance().getTime();
long currentTime = date.getTime();
long endTime = post.getTimerEndDate().getTime();
long timeLeft = endTime - currentTime;
new CountDownTimer(timeLeft, 1000) {
#SuppressLint("DefaultLocale")
public void onTick(long millisUntilFinished) {
timer.setText(String.format("%02d:%02d:%02d",
(int) ((millisUntilFinished / (1000 * 60 * 60)) % 24),
(int) ((millisUntilFinished / (1000 * 60)) % 60),
(int) (millisUntilFinished / 1000) % 60));
//here you can have your logic to set text to edittext
}
public void onFinish() {
timer.setText("done!");
}
}.start();
}
Picasso.get()
.load(post.getImageUrl_1())
.fit()
.transform(new RoundedCornersTransformation(30, 30))
.into(imageView1);
Picasso.get()
.load(post.getImageUrl_2())
.fit()
.transform(new RoundedCornersTransformation(30, 30))
.into(imageView2);
if (!postId.equals(userId)) {
docRefFollowing.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if (documentSnapshot != null && documentSnapshot.exists()) {
follow.setText("Following");
follow.setEnabled(false);
}
}
});
}
follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Map<String, Object> following = new HashMap<>();
following.put("Exists", true);
docRefFollowing.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
docRefFollowing.set(following);
docRefUsers.update("following", FieldValue.increment(1));
}
}
});
db.collection("users")
.document(postId)
.update("followers", FieldValue.increment(1));
follow.setText("Following");
}
});
if (!postId.equals(userId)) {
docRefPosts.collection("voted")
.document(currentUser.getUid()).addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if (documentSnapshot != null && documentSnapshot.exists()) {
whichVoted = documentSnapshot.get("votedFor").toString();
}
if (whichVoted != null) {
switch (whichVoted) {
case ("left"):
chooseLeft.setEnabled(false);
chooseRight.setEnabled(true);
break;
case ("right"):
chooseRight.setEnabled(false);
chooseLeft.setEnabled(true);
break;
}
} else {
chooseRight.setEnabled(true);
chooseLeft.setEnabled(true);
}
}
});
}
chooseLeft.setText(post.getLeftText());
chooseRight.setText(post.getRightText());
chooseLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseLeft.setEnabled(false);
chooseRight.setEnabled(true);
upLeft(docRefPosts, chooseLeft);
}
});
chooseRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseRight.setEnabled(false);
chooseLeft.setEnabled(true);
upRight(docRefPosts, chooseRight);
}
});
}
Firstly, you should be aware that RecyclerView re-uses its viewholders each time you scroll past the last visible item on the screen.
Based on your implementation for every time a user scroll past the
last visible item or post on the screen, because it is inside a
RecyclerView the original first-item on the list and even other items
being scrolled past are recycled and the next item becomes the new
first-item but being populated with a different post-values as
expected.
But remember your code instantiates a new CountdownTimer for
every new post added to the list (where 50 posts equals 50
Countdowntimers and 50 posts does not necessarily mean 50 views because
some of the views would probably be recycled by the RecyclerView; you get the logic), hence it allows the
possibility for multiple CountdownTimer accessing same view which
causes the flash and will surely lead to a memory leak causing an
OutOfMemoryError when the user keeps scrolling continuously on a long
list.
Recommended Implementation
Create your CountDownTimer inside your ViewHolder Class
public static class PostViewHolder extends RecyclerView.ViewHolder {
...
CountDownTimer countdowntimer;
public FeedViewHolder(View itemView) {
...
}
}
Access the timer inside setPost method
void setPost(final Post post) {
...
long currentTime = date.getTime();
long endTime = post.getTimerEndDate().getTime();
long timeLeft = endTime - currentTime;
if (countdowntimer != null) {
//there is an existing timer so we cancel it to prevent duplicates
countdowntimer.cancel();
}
countdowntimer = new CountDownTimer(timeLeft, 1000) {
#SuppressLint("DefaultLocale")
public void onTick(long millisUntilFinished) {
timer.setText(String.format("%02d:%02d:%02d",
(int) ((millisUntilFinished / (1000 * 60 * 60)) % 24),
(int) ((millisUntilFinished / (1000 * 60)) % 60),
(int) (millisUntilFinished / 1000) % 60));
//here you can have your logic to set text to edittext
}
public void onFinish() {
timer.setText("done!");
}
}.start();
}
Each time you are creating a new timer when your items in the RecyclerView is getting recycled after scrolling. The timeLeft variable also changes each time you scroll the item and that initializes a new Timer which is the reason for the flashing I guess.
Hence I would like to recommend having an array in your adapter. This is for holding all of your CountDownTimers. In the constructor of your adapter, initialize that properly to have the correct values. Let us take a sample implementation like the following.
Declare two arrays like the following.
CountDownTimer[] timers = new CountDownTimer[data.size()];
Now in the constructor of your adapter do something like the following.
// Let us assume the list of Data is dataItems which is being passed to your adapter.
// Your constructor might take other parameters
public MyAdapter(ArrayList<Data> dataItems) {
for(int i = 0; i < dataItems.size(); i++) {
long timeLeft = getTimeLeftValue(dataItems.get(i));
timers[i] = new CountDownTimer(timeLeft, 1000) {
#SuppressLint("DefaultLocale")
public void onTick(long millisUntilFinished) {
timer.setText(String.format("%d:%d:%d",
(int) ((millisUntilFinished / (1000 * 60 * 60)) % 24),
(int) ((millisUntilFinished / (1000 * 60)) % 60),
(int) (millisUntilFinished / 1000) % 60));
//here you can have your logic to set text to edittext
}
public void onFinish() {
timer.setText("done!");
}
}.start();
}
}
private long getTimeLeftValue(Data post) {
Date date = java.util.Calendar.getInstance().getTime();
long currentTime = date.getTime();
long endTime = post.getTimerEndDate().getTime();
timeLeft = endTime - currentTime;
return timeLeft.
}
Now in your onBindViewHolder you need to set the timer as follows.
timerInstance = timers.get(position);
I am assuming that each of your items in the RecyclerView is having a timer instance which is showing the CountDownTimer.
You don't specify where exactly your logic is in your adapter.
The logic should be within onBindViewHolder(…). You can access the widgets using viewHolder.findViewById(...)
Also, CountDownTimer is its own thread, and editing a TextView or any widget can cause an exception. Wrap the timer.setText(…) call within runOnUiThread()
Sorry for the Google translator
What I want to implement is that the date that the user chooses is maintained even when the activity ends. So I hope the settings are retained when I rerun the activity.
I tried SharedPreferences, String succeeded but datapicker failed
What can I do to keep my data picker user selections?
This is the code I used.
public class Widget extends Activity {
/**
* Called when the activity is first created.
*/
private TextView ddayText;
private TextView todayText;
private TextView resultText;
private TextView nameText;
private Button dateButton;
private int tYear;
private int tMonth;
private int tDay;
private int dYear = 1;
private int dMonth = 1;
private int dDay = 1;
private long d;
private long t;
private long r;
private long w;
private int resultNumber = 0;
private int dayNumber = 0;
private SharedPreferences sf;
static final int DATE_DIALOG_ID = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.widget);
ddayText = (TextView) findViewById(R.id.dday);
todayText = (TextView) findViewById(R.id.today);
resultText = (TextView) findViewById(R.id.result);
dateButton = (Button) findViewById(R.id.dateButton);
nameText = (TextView) findViewById(R.id.name);
dateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(0);//----------------
}
});
sf = getSharedPreferences("sf", Activity.MODE_PRIVATE);
String str = sf.getString("name", "");
long dday = sf.getLong("dday", d);
nameText.setText(str);
Calendar calendar = Calendar.getInstance();
tYear = calendar.get(Calendar.YEAR);
tMonth = calendar.get(Calendar.MONTH);
tDay = calendar.get(Calendar.DAY_OF_MONTH);
Calendar dCalendar = Calendar.getInstance();
dCalendar.set(dYear, dMonth, dDay);
t = calendar.getTimeInMillis();
d = dCalendar.getTimeInMillis();
r = (d - t) / (7 * 24 * 60 * 60 * 1000L);
w = (d - t) / (24 * 60 * 60 * 1000L);
resultNumber = (int) r * (-1);
dayNumber = (int) w * (-1);
updateDisplay();
}//OnCreate end
private void updateDisplay() {
todayText.setText(String.format("%d년 %d월 %d일", tYear, tMonth + 1, tDay));
ddayText.setText(String.format("%d년 %d월 %d일", dYear, dMonth + 1, dDay));
if (resultNumber >= 0) {
resultText.setText(String.format("임신 %d주 %d일", resultNumber % 45L, dayNumber % 7L + 1));
} else {
int absR = Math.abs(resultNumber);
resultText.setText(String.format("임신 %d주 %d일", absR, dayNumber % 7L));
}
}
#Override
protected Dialog onCreateDialog(int id) {
if (id == DATE_DIALOG_ID) {
return new DatePickerDialog(this, dDateSetListener, tYear, tMonth, tDay);
}
return null;
}
private DatePickerDialog.OnDateSetListener dDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
final Calendar dCalendar = Calendar.getInstance();
dCalendar.set(year, monthOfYear, dayOfMonth);
long d = dCalendar.getTimeInMillis();
r = (d - t) / (7 * 24 * 60 * 60 * 1000L);
w = (d - t) / (24 * 60 * 60 * 1000L);
resultNumber = (int) r * (-1);
dayNumber = (int) w * (-1);
saveData(nameText.getText().toString(), d);
updateDisplay();
}
private void saveData(String str, long d) {
SharedPreferences.Editor editor = sf.edit();
editor.putString("name", str);
editor.putLong("dday", d);
editor.commit();
}
};
}
I think you'll want to save data within onDateSet to the SharedPreferences if you want to store it at the correct time.
For example, move the preferences to a field
// Store this as a field for later reference
private SharedPreferences sf;
private final Calendar mCalendar = Calendar.getInstance();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.widget);
nameText = (TextView) findViewById(R.id.name);
// Load any data you have
sf = getSharedPreferences("sf", Activity.MODE_PRIVATE);
String str = sf.getString("name", "");
long dday = sf.getLong("dday", -1);
// TODO: set mCalendar time using dday
// if dday == -1, then nothing is saved
// load the date picker values
tYear = mCalendar.get(Calendar.YEAR);
tMonth = mCalendar.get(Calendar.MONTH);
tDay = mCalendar.get(Calendar.DAY_OF_MONTH);
nameText.setText(str);
updateDisplay();
And use it within the listener. Add a helper method to extract out the logic that writes to the preferences
private DatePickerDialog.OnDateSetListener dDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mCalendar.set(year, monthOfYear, dayOfMonth);
long d = mCalendar.getTimeInMillis();
saveData(nameText.getText().toString(), d);
// updateDisplay();
}
private void saveData(String str, long d) {
SharedPreferences.Editor editor = sf.edit();
editor.putString("name", str);
editor.putLong("dday", d);
editor.commit();
}
This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
i want to find total number of days b/w "from date" to "To date". Thanks in advance
here is my complete code
public class Main2Activity extends AppCompatActivity {
EditText ed1,ed2,ed4,ed5,ed6;Button b1; int day_x;int month_x;int year_x;int DIALOG_ID = 1;
#Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main2); AlertDialog.Builder a_builder = new AlertDialog.Builder(Main2Activity.this);a_builder.setMessage("Please Enter your\n'Name' and 'Date of Birth'.").setCancelable(false).setTitle("Alert!!!").setNegativeButton("ok", new DialogInterface.OnClickListener() { #Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); }}).show();date_selector(); to_date();final Calendar cal = Calendar.getInstance(); year_x = cal.get(Calendar.YEAR); month_x = cal.get(Calendar.MONTH); day_x = cal.get(Calendar.DAY_OF_MONTH); } public void date_selector() {ed2 = (EditText) findViewById(R.id.editText2); ed5 = (EditText) findViewById(R.id.editText5);ed4 = (EditText) findViewById(R.id.editText4);ed6 = (EditText) findViewById(R.id.editText6);ed1 = (EditText) findViewById(R.id.editText1);ed2.setOnClickListener( new View.OnClickListener() { #Override public void onClick(View view) {showDialog(DIALOG_ID);
}
}
);
}
#Override
protected Dialog onCreateDialog(int ids) {
if (ids == DIALOG_ID)
return new DatePickerDialog(Main2Activity.this, dickerListener, year_x, month_x, day_x);
return null;
}
private DatePickerDialog.OnDateSetListener dickerListener =
new DatePickerDialog.OnDateSetListener() {
public long dateEvent;
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
year_x = i;
month_x = i1+1 ;
day_x = i2;
ed2.setText((day_x+"/"+month_x+"/"+year_x));//showing DOB
//String stores=ed2.getText().toString();
final Calendar cal = Calendar.getInstance();
int year_y = cal.get(Calendar.YEAR);
int month_y = cal.get(Calendar.MONTH);
int day_y = cal.get(Calendar.DAY_OF_MONTH);
int month_z=month_y+1;
// SimpleDateFormat df = new SimpleDateFormat("dd mm yyyy");
ed5.setText(day_y+"/"+ month_z+"/"+ year_y);
String value = ed2.getText().toString();
ed4.setText(value);
Daysss_check();
}
};
public void Daysss_check() { //total number of days???
ed5 = (EditText) findViewById(R.id.editText5);
ed4 = (EditText) findViewById(R.id.editText4);
ed6 = (EditText) findViewById(R.id.editText6);
ed2 = (EditText) findViewById(R.id.editText2);
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String firstDate = ed2.getText().toString();
String secondDate = ed5.getText().toString();
try {
Date date1 = df.parse(firstDate);
Date date2 = df.parse(secondDate);
long diff = date2.getTime() - date1.getTime();
long diffDays= TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
// float dayCount = (float) diff / (24 * 60 * 60 * 1000);
//String.valueOf((int) dayCount);
String myDaycount = String.valueOf(diffDays);
ed6.setText(myDaycount);
} catch (ParseException e) {
e.printStackTrace();
}
}
this is the output of my app and i want to find total number of days b/w "from date" to "To date". Thanks in advance
long diff = date1.getTime() - date2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
please try this. Hope it helps you
I had already tried the first two suggestions below, but I tried again and sincerely thanks for the help! The result is the same though. I´ll just edit the post to add more code info.
Hello there! I´m experimenting with a simple ToDo application and managed to change almost everything I wanted besides the date formatted that´s displayed once the user saves the task.
The task itself is added via the AddToDoActivity class which has the following resumed code:
public class AddToDoActivity extends Activity {
// 7 days in milliseconds - 7 * 24 * 60 * 60 * 1000
private static final int SEVEN_DAYS = 604800000;
private static final String TAG = "Lab-UserInterface";
private static String timeString;
private static String dateString;
private static TextView dateView;
private static TextView timeView;
private Date mDate;
private RadioGroup mPriorityRadioGroup;
private RadioGroup mStatusRadioGroup;
private EditText mTitleText;
private RadioButton mDefaultStatusButton;
private RadioButton mDefaultPriorityButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_todo);
mTitleText = (EditText) findViewById(R.id.title);
mDefaultStatusButton = (RadioButton) findViewById(R.id.statusNotDone);
mDefaultPriorityButton = (RadioButton) findViewById(R.id.medPriority);
mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup);
mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup);
dateView = (TextView) findViewById(R.id.date);
timeView = (TextView) findViewById(R.id.time);
// Set the default date and time
setDefaultDateTime();
// OnClickListener for the Date button, calls showDatePickerDialog() to show
// the Date dialog
final Button datePickerButton = (Button) findViewById(R.id.date_picker_button);
datePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog();
}
});
// OnClickListener for the Time button, calls showTimePickerDialog() to show
// the Time Dialog
final Button timePickerButton = (Button) findViewById(R.id.time_picker_button);
timePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog();
}
});
// OnClickListener for the Cancel Button,
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered cancelButton.OnClickListener.onClick()");
finish();
}
});
//OnClickListener for the Reset Button
final Button resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered resetButton.OnClickListener.onClick()");
setDefaultDateTime();
mTitleText.setText("");
mDefaultStatusButton.setChecked(true);
mDefaultPriorityButton.setChecked(true);
}
});
// OnClickListener for the Submit Button
// Implement onClick().
final Button submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered submitButton.OnClickListener.onClick()");
// Gather ToDoItem data
Priority priority = getPriority();
Status status = getStatus();
String titleString = mTitleText.getText().toString();
// Date
String fullDate = dateString + " " + timeString;
// Package ToDoItem data into an Intent
Intent data = new Intent();
ToDoItem.packageIntent(data, titleString, priority, status, fullDate);
setResult(Activity.RESULT_OK, data);
finish();
}
});
}
// Do not modify below here
// Use this method to set the default date and time
private void setDefaultDateTime() {
// Default is current time + 7 days
mDate = new Date();
mDate = new Date(mDate.getTime() + SEVEN_DAYS);
Calendar c = Calendar.getInstance();
c.setTime(mDate);
setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH),
c.get(Calendar.YEAR));
dateView.setText(dateString);
setTimeString(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
c.get(Calendar.MILLISECOND));
timeView.setText(timeString);
}
private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
// Increment monthOfYear for Calendar/Date -> Time Format setting
monthOfYear++;
String mon = "" + monthOfYear;
String day = "" + dayOfMonth;
if (monthOfYear < 10)
mon = "0" + monthOfYear;
if (dayOfMonth < 10)
day = "0" + dayOfMonth;
dateString = year + "-" + mon + "-" + day;
}
private static void setTimeString(int hourOfDay, int minute, int mili) {
String hour = "" + hourOfDay;
String min = "" + minute;
if (hourOfDay < 10)
hour = "0" + hourOfDay;
if (minute < 10)
min = "0" + minute;
timeString = hour + ":" + min + ":00";
}
private Priority getPriority() {
switch (mPriorityRadioGroup.getCheckedRadioButtonId()) {
case R.id.lowPriority: {
return Priority.LOW;
}
case R.id.highPriority: {
return Priority.HIGH;
}
default: {
return Priority.MED;
}
}
}
private Status getStatus() {
switch (mStatusRadioGroup.getCheckedRadioButtonId()) {
case R.id.statusDone: {
return Status.DONE;
}
default: {
return Status.NOTDONE;
}
}
}
// DialogFragment used to pick a ToDoItem deadline date
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int dayOfMonth, int monthOfYear,
int year) {
setDateString(dayOfMonth, monthOfYear, year);
dateView.setText(dateString);
}
}
// DialogFragment used to pick a ToDoItem deadline time
public static class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return
return new TimePickerDialog(getActivity(), this, hour, minute,
true);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setTimeString(hourOfDay, minute, 0);
timeView.setText(timeString);
}
}
private void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
private void showTimePickerDialog() {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
Here´s the ToDoItem, that actually reads the info from AddToDoActivity:
public class ToDoItem {
public static final String ITEM_SEP = System.getProperty("line.separator");
public enum Priority {
LOW, MED, HIGH
};
public enum Status {
NOTDONE, DONE
};
public final static String TITLE = "title";
public final static String PRIORITY = "priority";
public final static String STATUS = "status";
public final static String DATE = "date";
public final static String FILENAME = "filename";
public final static SimpleDateFormat FORMAT = new SimpleDateFormat(
"dd/MM/yyyy HH:mm:ss", Locale.US);
private String mTitle = new String();
private Priority mPriority = Priority.LOW;
private Status mStatus = Status.NOTDONE;
private Date mDate = new Date();
ToDoItem(String title, Priority priority, Status status, Date date) {
this.mTitle = title;
this.mPriority = priority;
this.mStatus = status;
this.mDate = date;
}
// Create a new ToDoItem from data packaged in an Intent
ToDoItem(Intent intent) {
mTitle = intent.getStringExtra(ToDoItem.TITLE);
mPriority = Priority.valueOf(intent.getStringExtra(ToDoItem.PRIORITY));
mStatus = Status.valueOf(intent.getStringExtra(ToDoItem.STATUS));
try {
mDate = ToDoItem.FORMAT.parse(intent.getStringExtra(ToDoItem.DATE));
} catch (ParseException e) {
mDate = new Date();
}
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority priority) {
mPriority = priority;
}
public Status getStatus() {
return mStatus;
}
public void setStatus(Status status) {
mStatus = status;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
// Take a set of String data values and
// package them for transport in an Intent
public static void packageIntent(Intent intent, String title,
Priority priority, Status status, String date) {
intent.putExtra(ToDoItem.TITLE, title);
intent.putExtra(ToDoItem.PRIORITY, priority.toString());
intent.putExtra(ToDoItem.STATUS, status.toString());
intent.putExtra(ToDoItem.DATE, date);
}
public String toString() {
return mTitle + ITEM_SEP + mPriority + ITEM_SEP + mStatus + ITEM_SEP
+ FORMAT.format(mDate);
}
public String toLog() {
return "Title:" + mTitle + ITEM_SEP + "Priority:" + mPriority
+ ITEM_SEP + "Status:" + mStatus + ITEM_SEP + "Date:"
+ FORMAT.format(mDate);
}
}
Oh well, after hours tweaking the
public final static SimpleDateFormat FORMAT = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.US);
method from ToDoItem, I still cannot successfully convert yyyy-MM-dd to dd/MM/yyyy.
First, I´ve tried the obvious, and changed the expression yyyy-MM-dd to dd/MM/yyyy.
After that, all I got after saving the task was today´s date, even though the date inputted on AddToDoActivity is months or years ahead. If I revert back to yyyy-MM-dd, the date shown on the Task List is the same inputted on AddToDoActivity.
Then I tried to change all mentions of dates on every class to match the exact format that I wanted.
That made everything look good on AddToDoActivity, but again, when I transported the date back to ToDoItem, the app just ignored the previously inputted date and showed today´s date again.
Can anyone help me with this one??
Thanks!!
You are calling setDateString with arguments in the order of year, month, day:
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
But your method has parameters in the order of day, month, year:
private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
...
}
I also think you made some errors while copying your code into the question, since the setDateString method is duplicated and there is no setTimeString method.
Change:
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
to:
setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH), c.get(Calendar.YEAR));
Modify the code as follows in the ToDoListAdapter file getView method
// TODO - Display Time and Date.
// Hint - use ToDoItem.FORMAT.format(toDoItem.getDate()) to get date and time String
final TextView dateView = (TextView) itemLayout.findViewById(R.id.dateView);
dateView.setText(ToDoItem.FORMAT.format(toDoItem.getDate()));
The output will be something similar the the following
Reference:
Completing UI Activity assignment
Hello I'm trying to calculate user's sleeping hours of 7.5.the app should suggest that the user should be at bed at an exact time. For example, she chooses 7:00 Am as her waking time, the app will suggest that by 11:30 Am she should be going to bed What I tried so far is this:
public class TimepickerActivity extends Activity implements TimePickerDialog.OnTimeSetListener {
Button btn1, btn2;
TimePicker picker;
TextView tv;
private int hour;
private int minute;
static final int TIME_DIALOG_ID = 999;
#Override
public void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView( R.layout.activity_timepicker );
btn1 = (Button) findViewById (R.id.btnShow);
btn2 = (Button) findViewById (R.id.btnSleepingTime);
tv = (TextView) findViewById (R.id.textView1);
picker = (TimePicker) findViewById (R.id.timePicker1);
setCurrentTimeOnView();
addListenerOnButton();
}
// display current time
public void setCurrentTimeOnView() {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
tv.setText( new StringBuilder().append(pad(hour))
.append(":").append(pad(minute)));
// set current time into timepicker
picker.setCurrentHour(hour);
picker.setCurrentMinute(minute);
}
public void addListenerOnButton() {
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR, - selectedHour);
c.add(Calendar.MINUTE, - selectedMinute);
// set current time into timepicker
picker.setCurrentHour(hour + 7);
picker.setCurrentMinute(minute + 30);
// set current time into textview
//tv.setText(new StringBuilder().append(pad(hour))
// .append(":").append(pad(minute)));
tv.setText( picker.getCurrentHour().toString() + ":" + picker.getCurrentMinute().toString() );
}
};
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
}
}
When I input 7:00 am as my waking time, the result is giving me 2:30 pm. But it should be 12:30 pm. Any help is appreciated thanks.
No, it's correct. If you input 7:00am + 7.5 hours = 14:30 = 2:30 am. The program is working correctly.
EDIT: you almost did it:
public class TimepickerActivity extends Activity implements TimePickerDialog.OnTimeSetListener {
private static final int SUB_HOUR = -7;
private static final int SUB_MINUTE = -30;
[...]
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
// Gets current time
Calendar c = Calendar.getInstance();
// Assign hour set in the picker
c.set(Calendar.HOUR, selectedHour)
c.set(Calendar.MINUTE, selectedMinute);
// Have Calendar calculate the substraction of hours and minutes
c.add(Calendar.HOUR, SUB_HOUR);
c.add(Calendar.MINUTE, SUB_MINUTE);
// Get the hour and the minute calculated
hour = c.get(Calendar.HOUR);
minute = c.get(Calendar.MINUTE);
[...]
Of course this means this previous assignment:
hour = selectedHour;
minute = selectedMinute;
is now useless and you can remove it.
By the way, you didn't take into account the day, e.g. choosing 1:30 am would return 6:00 pm but for the day before.
EDIT: I corrected my code.