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
Related
I am new in this app development and I am making an APP that takes input from user like name, date and time and by clicking on submit button the data is sent to firebase database but I got stuck on datePickerDialog I am having issues on getting data from datePickerDialog. I am getting value of name by get and set method by making other java file with name member.java and it was done, my name value is showing on firebase database tree but from datePicker side I got confused idk what value should I get and set that value so that firebase database can have that value, having difficulty in getting data from datePickerDialog,
here is the code with two java files ;
MAIN-ACTIVITY-JAVA:
Public class MainActivity extends AppCompatActivity {
EditText firstname ,todays_date;
float start_time;
Button btnsave;
DatabaseReference reff;
Member member;
long maxid = 0;
private DatePickerDialog datePickerDialog;
private Button dateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initDatePicker();
dateButton = findViewById(R.id.datepickerbutton);
dateButton.setText(getTodaysDate());
firstname = (EditText)findViewById(R.id.firstname);
todays_date = (EditText) findViewById(R.id.todays_date);
btnsave = (Button) findViewById(R.id.btnsave);
member = new Member();
reff= FirebaseDatabase.getInstance().getReference().child("Member");
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
maxid = (dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int date = Integer.parseInt(todays_date.getText().toString().trim());
member.setToday_date(date);
member.setName(firstname.getText().toString().trim());
reff.child(String.valueOf(maxid+1)).setValue(member);
firstname.getText().clear();
todays_date.getText().clear();
}
});
}
private String getTodaysDate() {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
month = month + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
return makeDateString(day,month,year);
}
private void initDatePicker() {
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month + 1;
String date = makeDateString (day, month, year);
dateButton.setText(date);
}
} ;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int style = THEME_HOLO_LIGHT;
datePickerDialog = new DatePickerDialog(this,style,dateSetListener , year , month,day);
}
private String makeDateString(int day , int month ,int year){
return getMonthFormat(month) + " " + day + " " + year;
}
private String getMonthFormat(int month) {
if (month == 1)
return "JAN";
if (month == 2)
return "FEB";
if (month == 3)
return "MAR";
if (month == 4)
return "APR";
if (month == 5)
return "MAY";
if (month == 6)
return "JUN";
if (month == 7)
return "JUL";
if (month == 8)
return "AUG";
if (month == 9)
return "SEP";
if (month == 10)
return "OCT";
if (month == 11)
return "NOV";
if (month == 12)
return "DEc";
return "JAN";
}
public void openDatePicker(View view) {
datePickerDialog.show();
}
}
MEMBER.JAVA:
public class Member {
private String name;
private int today_date;
public Member() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getToday_date() {
return today_date;
}
public void setToday_date(int today_date) {
this.today_date = today_date;
}
}
You already got the choosen date inside the DatePickerDialog.OnDateSetListener. Just declare a global variable and set it inside the listener and then use it when you send your data to firebase.
String myDate; // a global variable
...
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month + 1;
String date = makeDateString (day, month, year);
dateButton.setText(date);
myDate = date; // this is where you initialize yor variable
}
};
...
// sending to Firebase:
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// you also need to make sure that myDate has a value...
int date = Integer.parseInt(myDate.trim()); // change here
member.setToday_date(date);
member.setName(firstname.getText().toString().trim());
reff.child(String.valueOf(maxid+1)).setValue(member);
firstname.getText().clear();
todays_date.getText().clear();
}
});
I have a Simple Date Picker App in Android and it's working fine when I click on First TextView.
How Can I activate the same Calendar with a second TextView. One TextView shows the Long Date and other shows the Short Date
public class MainActivity extends AppCompatActivity {
private TextView mDisplayLongDate;
TextView mDisplayShortDate;
CheckBox checkBoxVisibility;
private DatePickerDialog.OnDateSetListener mDateSetListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDisplayLongDate = findViewById(R.id.tvLDate);
mDisplayShortDate = findViewById(R.id.tvSDate);
//View checkBox = findViewById(R.id.checkBox);
checkBoxVisibility = findViewById(R.id.checkBox_visibility);
//boolean isChecked = checkBoxVisibility.isClickable();
boolean isChecked = checkBoxVisibility.isChecked();
updateTextVisibility(isChecked);
checkBoxVisibility.setOnCheckedChangeListener((buttonView, isChecked1) -> {
//Step 05 - Updating UI according to the currently changed state
updateTextVisibility(isChecked1);
});
mDisplayLongDate.setOnClickListener(view -> {
Calendar cal = Calendar.getInstance();
With a CheckBox, the TextView Shows Long Date and Short Date.
I cannot click on the short date to edit the Calendar. How to activate the Calendar in both situation.
String dateLong = monthStr + "/" + day + "/" + year;
String dateShort = monthStr + "/" + day;
mDisplayLongDate.setText(dateLong);
mDisplayShortDate.setText(dateShort);
};
}
private void updateTextVisibility(boolean isChecked) // When checking the trigger (checkbox)
{
if (isChecked)
{
mDisplayShortDate.setVisibility(View.VISIBLE);
mDisplayLongDate.setVisibility(View.GONE);
}
else
{
mDisplayShortDate.setVisibility(View.GONE);
mDisplayLongDate.setVisibility(View.VISIBLE);
}
You can use this type of method and call it where you need .
private void getCal() {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int monthStr = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dPDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog,
new DatePickerDialog.OnDateSetListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
public void onDateSet(DatePicker datepicker, int selectedY, int selectedM, int selectedD) {
String[] months = new DateFormatSymbols(Locale.ENGLISH).getMonths();
String dateLong = months[selectedM] + "/" + selectedD + "/" + selectedY;
String dateShort = months[selectedM] + "/" + selectedD;
// String dateLong = (selectedM + 1) + "/" + selectedD + "/" + selectedY;
//String dateShort = (selectedM + 1) + "/" + selectedD;
mDisplayLongDate.setText(dateLong);
mDisplayShortDate.setText(dateShort);
}
}, year, monthStr, day);
dPDialog.show();
}
Example class-
public class MainActivity extends AppCompatActivity {
private TextView mDisplayLongDate;
TextView mDisplayShortDate;
CheckBox checkBoxVisibility;
private DatePickerDialog.OnDateSetListener mDateSetListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDisplayLongDate = findViewById(R.id.tvLDate);
mDisplayShortDate = findViewById(R.id.tvSDate);
mDisplayLongDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCal();
}
});
mDisplayShortDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCal();
}
});
}
private void getCal() {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int monthStr = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dPDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog,
new DatePickerDialog.OnDateSetListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
public void onDateSet(DatePicker datepicker, int selectedY, int selectedM, int selectedD) {
String[] months = new DateFormatSymbols(Locale.ENGLISH).getMonths();
String dateLong = months[selectedM] + "/" + selectedD + "/" + selectedY;
String dateShort = months[selectedM] + "/" + selectedD;
// String dateLong = (selectedM + 1) + "/" + selectedD + "/" + selectedY;
//String dateShort = (selectedM + 1) + "/" + selectedD;
mDisplayLongDate.setText(dateLong);
mDisplayShortDate.setText(dateShort);
}
}, year, monthStr, day);
dPDialog.show();
}
}
I am working on a simple app in which i have taken two date pickers they subtract two dates and display the result. But i want that if the two dates are same like 06/04/2017 then two radio button should pop up for selecting full day and half day as soon as it calculates that the two dates are same.
how to do that?
public class Leave extends AppCompatActivity {
TextView date;
private DatePickerDialog datePickerDialog;
TextView date2;
//TextView setDay;
private DatePickerDialog datePickerDialog2;
TextView no_of_days;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leave);
date = (TextView) findViewById(R.id.date);
date2 = (TextView) findViewById(R.id.date2);
//setDay = (TextView) findViewById(R.id.setDay);
no_of_days = (TextView) findViewById(R.id.no_of_days);
// initiate the date picker and a button
date = (TextView) findViewById(R.id.date);
// perform click event on edit text
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
date.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
// initiate the date picker and a button
date2 = (TextView) findViewById(R.id.date2);
// perform click event on edit text
date2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog2 = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
date2.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog2.show();
}
});
no_of_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy");
String date01 = date.getText().toString();
String date02 = date2.getText().toString();
try {
Date d = format.parse(date01);
Date d1 = format.parse(date02);
getDifferenceDays(d, d1);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.leave_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
}
public class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener {
SpinnerActivity() throws ParseException {
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
}
}
private void setupRadios() {
RadioButton radio_full = (RadioButton) findViewById(R.id.radio_full);
RadioButton radio_Half = (RadioButton) findViewById(R.id.radio_Half);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioleave);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
int buttonId = radioGroup.getCheckedRadioButtonId();
switch (buttonId) {
case R.id.radio_full:
Toast.makeText(getApplicationContext(), "You have selected Full Day Leave", Toast.LENGTH_SHORT).show();
break;
case R.id.radio_Half:
Toast.makeText(getApplicationContext(), "You have selected Half Day Leave", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
public void getDifferenceDays(Date d1, Date d2) {
int daysdiff = 0;
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000) + 1;
daysdiff = (int) diffDays;
no_of_days.setText(Integer.toString(daysdiff));
System.out.println("day count=>" + daysdiff);
}
}
Compare the dates whenever any date is selected from any one of the date picker's as follows :
public class Leave extends AppCompatActivity {
TextView date;
private DatePickerDialog datePickerDialog;
TextView date2;
//TextView setDay;
private DatePickerDialog datePickerDialog2;
TextView no_of_days;
String date1 = "", date2 = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leave);
date = (TextView) findViewById(R.id.date);
date2 = (TextView) findViewById(R.id.date2);
//setDay = (TextView) findViewById(R.id.setDay);
no_of_days = (TextView) findViewById(R.id.no_of_days);
RadioButton radio_full = (RadioButton) findViewById(R.id.radio_full);
RadioButton radio_Half = (RadioButton) findViewById(R.id.radio_Half);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioleave);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
int buttonId = radioGroup.getCheckedRadioButtonId();
switch (buttonId) {
case R.id.radio_full:
Toast.makeText(getApplicationContext(), "You have selected Full Day Leave", Toast.LENGTH_SHORT).show();
break;
case R.id.radio_Half:
Toast.makeText(getApplicationContext(), "You have selected Half Day Leave", Toast.LENGTH_SHORT).show();
break;
}
}
});
// initially hide the radio buttons
radio_full.setVisibility(View.GONE);
radio_Half.setVisibility(View.GONE);
// initiate the date picker and a button
date = (TextView) findViewById(R.id.date);
// perform click event on edit text
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
// assign the value to date1
date1 = dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year;
date.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
// check if date2 has been set and compare it with date1
if(!TextUtils.isEmpty(date2)) {
// get difference
getDifferenceDays(date, date2);
if(date1.equals(date2)) {
// pop up radio button
radio_full.setVisibility(View.VISIBLE);
radio_Half.setVisibility(View.VISIBLE);
} else {
// hide radio buttons
radio_full.setVisibility(View.GONE);
radio_Half.setVisibility(View.GONE);
}
}
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
// initiate the date picker and a button
date2 = (TextView) findViewById(R.id.date2);
// perform click event on edit text
date2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog2 = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
// assign the value to date2
date2 = dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year;
date2.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
// check if date2 has been set and compare it with date1
if(!TextUtils.isEmpty(date1)) {
// get difference
getDifferenceDays(date, date2);
if(date1.equals(date2)) {
// pop up radio button
radio_full.setVisibility(View.VISIBLE);
radio_Half.setVisibility(View.VISIBLE);
} else {
// hide radio buttons
radio_full.setVisibility(View.GONE);
radio_Half.setVisibility(View.GONE);
}
}
}
}, mYear, mMonth, mDay);
datePickerDialog2.show();
}
});
no_of_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy");
String date01 = date.getText().toString();
String date02 = date2.getText().toString();
try {
Date d = format.parse(date01);
Date d1 = format.parse(date02);
getDifferenceDays(d, d1);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.leave_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
}
What I have is a calendar widget which opens up when pressed and the user can select their dates from the calendar. I have variables to save the dates entered in inside the DateSetup class and I followed the code on using putExtra() to send the data from one class to another, but the values are not showing up.
The process of the application is when the dates have been selected, the user will then be able to select the times with the time picker widget which works.
After the dates and times have been selected, the values are sent to a MySQL database which the dates/times values should be shown. Only the selected times are showing but not the dates from the calendar selected.
DateSetup class
public class DateSetup extends MainActivity implements View.OnClickListener
{
//UI References
private EditText fromDateEtxt;
private EditText toDateEtxt;
// Dates Strings setup
String startDate;
String endDate;
DatePickerDialog fromDatePickerDialog;
DatePickerDialog toDatePickerDialog;
private SimpleDateFormat dateFormatter;
private DataDBAdapter2 Database;
Button btnHistory;
Button btnTime;
Button btnFuture;
Button btnManual;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.date_setup);
fromDateEtxt = (EditText) findViewById(R.id.etxt_fromdate);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
toDateEtxt = (EditText) findViewById(R.id.etxt_todate);
toDateEtxt.setInputType(InputType.TYPE_NULL);
toDateEtxt.requestFocus();
btnTime = (Button)findViewById(R.id.btnSetDates);
btnFuture = (Button)findViewById(R.id.btnFutureSetups);
btnManual = (Button)findViewById(R.id.btnManualControl);
fromDateEtxt.setOnClickListener(this);
toDateEtxt.setOnClickListener(this);
// Open the database
Database = new DataDBAdapter2(this);
Database.open();
// Set the date format to English (Australia)
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
btnHistory = (Button)findViewById(R.id.btnHistoryView);
btnHistory.setOnClickListener(this);
//-------------------------------------------
// Start Date (From date)
//-------------------------------------------
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener()
{
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
//startDate = fromDateEtxt.getText().toString();
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
//-------------------------------------------
// End Date (End date)
//-------------------------------------------
toDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener()
{
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
toDateEtxt.setText(dateFormatter.format(newDate.getTime()));
//endDate = toDateEtxt.getText().toString();
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
// Set dates and continue to set times
btnTime.setOnClickListener(new View.OnClickListener()//OnClickListener()
{
#Override
public void onClick(View view)
{
// Start next activity
Intent i = new Intent(DateSetup.this, TimeSetup.class);
// Send data start data and End Date
//i.putExtra("START", startDate);
//i.putExtra("END", endDate);
i.putExtra("START", fromDateEtxt.getText().toString());
i.putExtra("END", toDateEtxt.getText().toString());
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(i);
}
});
// History view
btnHistory.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v2)
{
Intent myIntent2 = new Intent(DateSetup.this, HistoryView.class);
myIntent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(myIntent2);
}
});
// Future Settings View
btnFuture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent myIntent3 = new Intent(DateSetup.this, CurrentView.class);
myIntent3.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(myIntent3);
}
});
// Manual Control
btnManual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent myIntent4 = new Intent(DateSetup.this, IrrigationControl.class);
myIntent4.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(myIntent4);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.date_setup, menu);
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onClick(View view)
{
if(view == fromDateEtxt)
{
fromDatePickerDialog.show();
}
else if(view == toDateEtxt)
{
toDatePickerDialog.show();
}
}
}
TimeSetup2 class
public class TimeSetup2 extends TimeSetup
{
Button btnBck;
Button btnSetDatesandTime;
String minutedisplay2;
String hourdisplay2;
private DataDBAdapter2 Database;
private TimePicker timePicker2;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.time_setup2);
btnBck = (Button) findViewById(R.id.btnBack);
btnSetDatesandTime = (Button) findViewById(R.id.btnSet);
timePicker2 = (TimePicker)findViewById(R.id.timePicker2);
Database = new DataDBAdapter2(this);
Database.open();
// Back to previous activity
// http://stackoverflow.com/questions/4038479/android-go-back-to-previous-activity
btnBck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(TimeSetup2.this, TimeSetup.class);
TimeSetup2.this.startActivity(myIntent);
}
});
// Set time and dates
btnSetDatesandTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
// Generate random number for ID
Random r = new Random();
int i2 = r.nextInt(100-1) + 100;
// Convert from integer to string
String random2 = Integer.toString(i2);
//------------------------------------------------------
// Data from other classes to be sent to the database
//------------------------------------------------------
Intent intent = getIntent();
// Start Date and End date data
String StartD = intent.getStringExtra("START");
String EndD = intent.getStringExtra("END");
// Time Picker 1 Data (Working)
String StartTime1 = intent.getStringExtra("TIMEHOUR1");
String EndTime1 = intent.getStringExtra("TIMEMIN1");
// Time Picker 2 Data
//String StartTime2 = intent.getStringExtra("TIMEHOUR2");
//String EndTime2 = intent.getStringExtra("TIMEMIN2");
hourdisplay2 = timePicker2.getCurrentHour().toString();
minutedisplay2 = timePicker2.getCurrentMinute().toString();
// Send data to the Database
Database.insertData2(random2, StartD, EndD, StartTime1 + ":" + EndTime1, hourdisplay2 + ":" + minutedisplay2);
// Send data to the arduino board
// Show Message that the data has been sent
Toast.makeText(getApplicationContext(), "Irrigation Setups have been sent", Toast.LENGTH_LONG).show();
}
});
}
}
I've been stuck on trying to solve this problem for days. It's probably something really simple I'm missing out but I can't figure it out.
The only data types that are OS-friendly are primitive types (int, long, float, boolean, etc...), so that means that putExtra() allows you to store primitives only. That's why you cant send a Calendar object.
Try to send a String of your period to your next activity.
In my Android application i have a tracker activity in which i retrieve the exercises information(name , period , burned calories) from the sqlite data base based on the selected date and display these information in a linear layout , and my problem that as the user select new date the retrieved data are displayed in another "new " layout appear above the old one but what actually i want to do is to display the new retrieved data on the same layout " change the layout content with the new retrieved data ", i have tried the remove all views method but it didn't work since the data appear for few minutes then dis appear
How i can do this: when the user select a new date the new retrieved data displayed on the same layout " refresh the old data by the new one " not to display them in anew layout . how i can do that ? please help me...
java code
public class Tracker extends BaseActivity
{
private Button date_btn;
private ImageButton left_btn;
private ImageButton right_btn;
private ImageView nodata;
private TextView ex_name;
private TextView ex_BCals;
private LinearLayout excercises_LL;
private LinearLayout content_LL ;
private LinearLayout notes;
private LinearLayout details;
private int year,month,day;
private double tot_excals_burned;
private Calendar localCalendar;
private static final int DATE_DIALOG_ID=0;
private boolean has_ex_details;
private boolean has_meal_details=false;
private Cursor exercises_cursor;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tracker);
date_btn=(Button)findViewById(R.id.btn_date);
date_btn.setText(FormatDate());
date_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar = Calendar.getInstance();
year = localCalendar.get(1);
month= localCalendar.get(2);
day = localCalendar.get(5);
showDialog(DATE_DIALOG_ID);
}
});
left_btn=(ImageButton)findViewById(R.id.btn_left);
left_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar.add(5, -1);
date_btn.setText(FormatDate(localCalendar,"EEEE, d/MMM/yyyy"));
RefreshExercisesData();
RefreshNoDataImage();
}
});
right_btn=(ImageButton)findViewById(R.id.btn_right) ;
right_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar.add(5, 1);
date_btn.setText(FormatDate(localCalendar,"EEEE, d/MMM/yyyy"));
RefreshExercisesData();
RefreshNoDataImage();
}
});
details=(LinearLayout)findViewById(R.id.ll_details);
notes=(LinearLayout)findViewById(R.id.ll_notes);
excercises_LL=(LinearLayout)findViewById(R.id.ll_exercises);
nodata=(ImageView)findViewById(R.id.nodata_imgV);
RefreshExercisesData();
RefreshNoDataImage();
}
private String FormatDate()
{
localCalendar = Calendar.getInstance();
return new SimpleDateFormat("EEEE, d/MMM/yyyy").format(localCalendar.getTime());
}
private String FormatDate(int year, int month, int day)
{
localCalendar = Calendar.getInstance();
localCalendar.set(year, month, day);
return new SimpleDateFormat("EEEE, d/MMM/yyyy").format(localCalendar.getTime());
}
private String FormatDate(Calendar calendar , String format)
{
return new SimpleDateFormat(format).format(calendar.getTime());
}
private void RefreshExercisesData()
{
tot_excals_burned=0;
DBAdapter db = new DBAdapter(this);
db.open();
String selected_date= date_btn.getText().toString();
Log.e("date", selected_date);
exercises_cursor = db.getExerciseInfo(selected_date);
if(exercises_cursor.getCount() !=0 )
{
has_ex_details=true;
details.setVisibility(0);
nodata.setVisibility(8);
notes.setVisibility(0);
//excercises_LL.removeAllViews();
excercises_LL.setWeightSum(1.0F);
excercises_LL.setVisibility(0);
excercises_LL.setOrientation(LinearLayout.VERTICAL);
LayoutInflater exc_LayoutInflater = (LayoutInflater)getApplicationContext().getSystemService("layout_inflater");
LinearLayout layout = (LinearLayout)exc_LayoutInflater.inflate(R.layout.tracker_header_item,null);
TextView tot_ex_cals_value=((TextView)(layout).findViewById(R.id.tv_tot_cals_value));
TextView exs_title=((TextView)(layout).findViewById(R.id.tv_item_title)) ;
exs_title.setText("Exercises ");
(layout).setPadding(0, 36, 0, 0);
excercises_LL.addView((View)layout, 0);
int i = 1;
if (exercises_cursor.moveToFirst())
{
do
{
content_LL=new LinearLayout(this);
ex_name=new TextView(this);
ex_name.setText( exercises_cursor.getFloat(1)+"," +exercises_cursor.getString(0) + "min ");
ex_name.setTextColor(R.color.black);
content_LL.addView(ex_name,0);
ex_BCals=new TextView(this);
ex_BCals.setText(Round(exercises_cursor.getFloat(2)) +" ");
ex_BCals.setTextColor(R.color.color_black);
content_LL.addView(ex_BCals,1);
tot_excals_burned = tot_excals_burned+exercises_cursor.getFloat(2);
excercises_LL.addView(content_LL, i);
i++;
}
while (exercises_cursor.moveToNext());
}
tot_ex_cals_value.setText(Round(tot_excals_burned) );
}
else if(exercises_cursor.getCount()==0 ||tot_excals_burned==0)
{
has_ex_details=false;
RefreshNoDataImage();
}
exercises_cursor.close();
exercises_cursor.deactivate();
db.close();
}
private void RefreshNoDataImage()
{
if(has_ex_details==false && has_meal_details==false)
{
notes.setVisibility(8);
excercises_LL.setVisibility(8);
nodata.setImageResource(R.drawable.bg_nodata);
nodata.setVisibility(View.VISIBLE);
}
else
nodata.setVisibility(8);
}
protected Dialog onCreateDialog(int id)
{
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, this.year, this.month, this.day);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
{
public void onDateSet(DatePicker paramDatePicker, int year, int monthofYear, int dayofMonth)
{
Tracker.this.year=year;
month=monthofYear;
day=dayofMonth;
date_btn.setText(FormatDate(year,month,day));
RefreshExercisesData();
RefreshNoDataImage();
}
};
private String Round(double num) {
return String.format("%.1f%n", num);
}}
Its because you defined these variables as static:
public static int icon;
public static String data_text;
public static String text;
As a result only one instance of those variables are created for all instances of that class. So when you create a new Profile each time, they are overwritten with new values. You need to remove the static keyword from variable declarations:
public int icon;
public String data_text;
public String text;
Then you cannot access them as static so you need to access like this:
Profile pli = data[position];
holder.imgIcon.setImageResource(pli.icon);
holder.Datatxt.setText(pli.data_text);
holder.txt.setText(pli.text);
Check out this if you want to learn more about static: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html