I have 2 datepickers and 2 timepickers on a screen and also a submit button. The user selects the start date, start time, end date, and end time. The program then takes these values and stores them into variables, however the variables only return the default values for these controls. Is there anyway to get the updated value from each of these controls?
My code looks like this for the edit screen:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.editscreen);
timepickerStart = (TimePicker)findViewById(R.id.timePicker1);
timepickerEnd = (TimePicker)findViewById(R.id.timePicker2);
datepickerStart = (DatePicker)findViewById(R.id.datePicker1);
datepickerEnd = (DatePicker)findViewById(R.id.datePicker2);
submitbutton = (Button)findViewById(R.id.submit);
locationText = (EditText)findViewById(R.id.locationText);
eventText = (EditText)findViewById(R.id.eventText);
}
public void DateStart(View v)
{
GlobalVariables.datepickerYearStart = datepickerStart.getYear();
GlobalVariables.datepickerMonthStart = datepickerStart.getMonth();
GlobalVariables.datepickerDayStart = datepickerStart.getDayOfMonth();
}
public void DateEnd(View v)
{
GlobalVariables.datepickerYearEnd = datepickerEnd.getYear();
GlobalVariables.datepickerMonthEnd = datepickerEnd.getMonth();
GlobalVariables.datepickerDayEnd = datepickerEnd.getDayOfMonth();
}
public void TimeStart(View v)
{
GlobalVariables.timepickerHourStart = timepickerStart.getCurrentHour();
GlobalVariables.timepickerMinuteStart = timepickerStart.getCurrentMinute();
}
public void TimeEnd(View v)
{
GlobalVariables.timepickerHourEnd = timepickerEnd.getCurrentHour();
GlobalVariables.timepickerMinuteEnd = timepickerEnd.getCurrentMinute();
}
public void submitClicked(View v)
{
startActivity(new Intent(this, AddToCalendar.class));
}
Rewrite
Looking at your current code, let's stick with the various get methods from DatePicker and TimePicker. However you never call DateStart() or any of the others, they look like you have them set up for an OnClickListener... Regardless, try this:
public void submitClick(View v) {
DateStart(null);
TimeStart(null);
DateEnd(null);
TimeEnd(null);
// Do what you please your GlobalVariables
}
Though I might leave out the multiple GlobalVariables and store one long value for each date/time:
public void submitClick(View v) {
Calendar calendar = Calendar.getInstance();
calendar.set(datepickerStart.getYear(), datepickerStart.getMonth(),
datepickerStart.getDayOfMonth(), timepickerStart.getCurrentHour(),
timepickerStart.getCurrentMinute(), 0);
long startTime = calendar.getTimeInMillis();
// And similar approach for the end time, then use them however you please
}
You need to set a listener to your DatePicker:
DatePicker picker = new DatePicker(this);
picker.init(<year>, <monthOfYear>, <dayOfMonth>, new DatePicker.OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//set the value of the variable here
}
});
Related
I have run into a problem where my app is properly building and buttons are working as expect, but the text field I am editing with two time picker fragments is being edited by both the start time picker and end time picker.
public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_start = (Button) findViewById(R.id.start_picker_button);
button_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker1 = new TimePickerStartFragment();
timePicker1.show(getSupportFragmentManager(),"time picker start");
}
});
Button button_end = (Button) findViewById(R.id.end_picker_button);
button_end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker2 = new TimePickerEndFragment();
timePicker2.show(getSupportFragmentManager(),"time picker end");
}
});
}
#Override
public void onTimeSet(TimePicker TimePickerStartFragment, int hourOfDay, int minute) {
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Hour: " + hourOfDay + " " + "Minute: " + minute);
My application looks like two buttons, one for a start time fragment and the other for an end time fragment. I have two seperate time picker fragment java files. However, when I set the end time fragment it still modifies the start time text. I want to have the start time picker only modify the start time text and the end time picker modify the end time text.
To further clarify when the select start time button is pressed TimePickerStratFragment is opened and a time is selected, this modifies a text field called textView. However when the time end button fragment is selected it also modifies the text view. I want the time end button to not modify the text view.
Add a String value to check which time picker is opened, because onTimeSet is fired for both fragments use something like this
String timeTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_start = (Button) findViewById(R.id.start_picker_button);
button_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeTag = "from";
DialogFragment timePicker1 = new TimePickerStartFragment();
timePicker1.show(getSupportFragmentManager(),"time picker start");
}
});
Button button_end = (Button) findViewById(R.id.end_picker_button);
button_end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeTag = "to";
DialogFragment timePicker2 = new TimePickerEndFragment();
timePicker2.show(getSupportFragmentManager(),"time picker end");
}
});
}
#Override
public void onTimeSet(TimePicker TimePickerStartFragment, int hourOfDay, int minute) {
if(Objects.equals(timeTag, "from")) {
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Hour: " + hourOfDay + " " + "Minute: " + minute);
}
if(Objects.equals(timeTag, "to")) {
}
}
I am trying to get the time when the user clicks on the EditText StartTime and EndTime. The problem is that I don't know how to distinguish the EditTexts at the TimePickerFragment. Any help, please?
public void initializeTime () {
startTimeEditText = (EditText) findViewById(R.id.startTimeEditText);
startTimeEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Initialize a new time picker dialog fragment
DialogFragment dFragment = new TimePickerFragment();
// Show the time picker dialog fragment
dFragment.show(getSupportFragmentManager(),"TimePicker");
}
});
endTimeEditText = (EditText) findViewById(R.id.endTimeEditText);
endTimeEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Initialize a new time picker dialog fragment
DialogFragment dFragment = new TimePickerFragment();
// Show the time picker dialog fragment
dFragment.show(getSupportFragmentManager(),"TimePicker");
}
});
}
TimePickerFragment.java:
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
EditText startTimeEditText = (EditText) getActivity().findViewById(R.id.startTimeEditText);
EditText endTimeEditText = (EditText) getActivity().findViewById(R.id.endTimeEditText);
flag = getArguments().getString("Flag");
Log.v(TAG,flag);
Toast.makeText(getActivity(), "Toast"+flag, Toast.LENGTH_LONG).show();
if (startTimeEditText.isActivated()){
startTimeEditText.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
}
else if (endTimeEditText.isActivated()){
endTimeEditText.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
}
}
TimePickerFragment should not mess with the layout of the rest of the Activity: the best way here is to pass a listener to the TimePickerFragment. Take a look at TimePicker.setOnTimeChangedListener(...), I know it's not a Fragment, but the idea is the same.
Another solution is to use an event bus (for example including the EventBus library) and posting a new event when the user select a date: in this way any component of your app can subscribe to this event and act accordingly.
im quite new to android programming. Im am trying to make use of google's latest datetimepicker function. I downloaded the source code from https://android.googlesource.com/platform/frameworks/opt/datetimepicker/+/e91a5dcdcc786074be1f6a9f2a4d79b99e34e18e and i imported it into my own project. So far i dont have any errors but i dont know how to make use of this function and test it into my project. I want to have a dialog box that will provide to the user the ability to select hours and minutes and a button click will save these data into my application.
Example: https://scontent-b-lhr.xx.fbcdn.net/hphotos-ash3/t1.0-9/10157365_10203642451081150_8056765662416057326_n.jpg
The Calendar app has the code to call the DatePickerDialog in the EditEventFragment (I think)
it looks about like this:
private class DateListener implements DatePickerDialog.OnDateSetListener {
View mView;
public DateListener(View view) {
mView = view;
}
#Override
public void onDateSet(DatePickerDialog view, int year, int month, int monthDay) {
// Cache the member variables locally to avoid inner class overhead.
Time startTime = mStartTime;
Time endTime = mEndTime;
// Cache the start and end millis so that we limit the number
// of calls to normalize() and toMillis(), which are fairly
// expensive.
long startMillis;
long endMillis;
if (mView == mFromDateButton) {
startTime.year = year;
startTime.month = month;
startTime.monthDay = monthDay;
startMillis = startTime.normalize(true);
setDate(mFromDateButton, startMillis);
} else {
endTime.year = year;
endTime.month = month;
endTime.monthDay = monthDay;
// Do not allow an event to have an end time before the start
// time.
if (endTime.before(mStartTime)) {
endTime.set(mStartTime);
}
endMillis = endTime.normalize(true);
setDate(mToDateButton, endMillis);
}
}
}
private DatePickerDialog mDatePickerDialog;
private class DateClickListener implements View.OnClickListener {
private Time mTime;
public DateClickListener(Time time) {
mTime = time;
}
#Override
public void onClick(View v) {
final DateListener listener = new DateListener(v);
if (mDatePickerDialog != null) {
mDatePickerDialog.dismiss();
}
mDatePickerDialog = DatePickerDialog.newInstance(listener,
mTime.year, mTime.month, mTime.monthDay);
mDatePickerDialog.setFirstDayOfWeek(PickerUtils.getFirstDayOfWeekAsCalendar( getActivity()));
mDateRangePickerDialog.setYearRange(mToday.year, mToday.year + 2);
mDateRangePickerDialog.show(getActivity().getFragmentManager(), "datePicker");
}
}
I've a Listview with two linear layouts and there is one button add new row . When i click add new row button i want to create new row of buttons dynamically. After that click on that created button i want to show an time picker dialog . When user click set time button i want to set that time in that button. My problem is All the buttons(with different id) are added fine and when click that button time picker dialog was pop up. But after click set time button the time will not set . How can i add this time to the button. How can i handle this button ?
It is my piece of code inside of listview onscroll listener
final LinearLayout l1 = LinearLayout) List_Layout.getChildAt(0);
LinearLayout l12 = (LinearLayout) List_Layout.getChildAt(1);
final Button button = new Button(getApplicationContext());
final Button button1 = new Button(getApplicationContext());
add_button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
button.setLayoutParams(lparams);
button1.setLayoutParams(lparams);
button.setId(0);
button1.setId(1);
l1.addView(button, lparams);
l12.addView(button1, lparams);
}
}
button.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("deprecation")
public void onClick(View v)
{
showDialog(TIME_DIALOG_ID);
}
}
button1.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("deprecation")
public void onClick(View v)
{
// TODO Auto-generated method stub
Log.e("tag 1", button1.getTag()+"");
showDialog(TIME_DIALOG_ID);
}
});
Rest of the codes for timepicker dialog is works fine
It's just sample code
Please anyone help me get out from this riddle.
Edit:
static final int TIME_DIALOG_ID = 998;
private int hour;
private int minute;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
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;
}
}
You need to set text of button or button1 to the time that was actually picked by the user. To do so, code some button.setText(<formatted time>) in the timePickerListener.
Here's some line of code, I use to format date and time from a java.util.Date object:
Date date = new Date();
java.text.DateFormat dateFormat = DateFormat.getMediumDateFormat(context);
java.text.DateFormat timeFormat = DateFormat.getTimeFormat(context);
button.setText(String.format("%s %s", dateFormat.format(date), timeFormat.format(date)));
In your case of the time picker you can just format the selected values into a string:
button.setText(String.format("%02d:%02d", selectedHour, selectedMinute));
The app has initial message screen that is displayed the first time it run where a date is obtained from user using datepicker then from next time it goes directly to main.xml. This is the logic i tried
in onCreate()
if(<date set>)
{
<open main.xml>
<listeners>
}
else
{
<get date from user>
<set flag>
setContentView(R.layout.initial_msg);
<make changes in main.xml according to date>
}
The problem is the first time it executes it obtains the date but the listeners are not loaded, i think this is because the code is not executed at all. when i place the listener outside the if block i get a null pointer exception. But when i close the app and start it again it works as this time it opens if() block not else().
public class pgactivity extends Activity
{
/** Called when the activity is first created. */
SharedPreferences prefs;
Calendar c=Calendar.getInstance();
Calendar tempDate;
TextView tv1,tv2;
Menu theMenu;
LayoutInflater li;
int week;
DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener()
{
//#override
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth)
{
c.set(Calendar.DATE,dayOfMonth);
c.set(Calendar.MONTH,monthOfYear);
c.set(Calendar.YEAR,year);
if(checkValidity())
{
SharedPreferences.Editor editor=prefs.edit();
//set the flag that indicates concieved_date has been added
editor.putBoolean("concieved_date", true);
int datepref;
datepref=c.get(Calendar.DATE);
datepref=datepref*1000000;
datepref+=c.get(Calendar.MONTH)*10000;
datepref+=c.get(Calendar.YEAR);
editor.putInt("date",datepref);
editor.commit();
setContentView(R.layout.main);
setData();
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//check if concieved date is set from the prefs file "app_data"
//if yes open application page else open initial message screen to set the date
prefs=getApplicationContext().getSharedPreferences("app_data",Context.MODE_APPEND);
if(prefs.getBoolean("concieved_date", false))
{
setContentView(R.layout.main);
setData();
//Listener for the temp button 'false'
//It resets the flag used to indicate if date is set or not. used for testing purpose
Button btn1=(Button)findViewById(R.id.setfalse);
btn1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("concieved_date", false);
editor.commit();
TextView tv3=(TextView)findViewById(R.id.test);
tv3.setText("entered listener");
}
});
//Listener for the weekly_tip text view
//when clicked open the layout giving the full description
TextView tv2=(TextView)findViewById(R.id.weekly_tip);
tv2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent j=new Intent(pgactivity.this,weekly.class);
Bundle b=new Bundle();
b.putInt("cur_week",week);
j.putExtras(b);
startActivity(j);
}
});
//Listener for open_remainders button to switch to Remainders page
Button btn2=(Button)findViewById(R.id.open_remainders);
btn2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i=new Intent(pgactivity.this,RemaindersPage.class);
startActivity(i);
}
});
}
else
{
setContentView(R.layout.initial_msg);
//click listener for textview 2
TextView tv1=(TextView)findViewById(R.id.init_msg);
tv1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("concieved_date", true);
editor.commit();
new DatePickerDialog(pgactivity.this,d,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
}
void setData()
{
Long sec,tempSec;
int date,day,month,year;
date=prefs.getInt("date", 10101010);
day=date/1000000;
date=date%1000000;
month=date/10000;
date=date%10000;
year=date;
c.set(year, month, day);
tempDate=c;
//insert value to concieved_date textfield
tv1=(TextView)findViewById(R.id.concieved_date);
tv1.setText(android.text.format.DateFormat.format("dd MMM yyyy", tempDate));
//insert value to delivery_date
tv1=(TextView)findViewById(R.id.delivery_date);
tempDate.add(Calendar.DATE, 280);
tv1.setText(android.text.format.DateFormat.format("dd MMM yyyy", tempDate));
//insert value to days_to_delivery
tv1=(TextView)findViewById(R.id.days_to_delivery);
c=Calendar.getInstance(); //c has current date
sec=tempDate.getTimeInMillis()-c.getTimeInMillis(); //find diff in millisecs
sec=sec/86400000;
tv1.setText(sec.toString());
//insert value for days_into_pregnancy
tv1=(TextView)findViewById(R.id.days_into_pregnancy);
tempSec=280-sec;
tv1.setText(tempSec.toString());
//insert value for current_week
tv1=(TextView)findViewById(R.id.current_week);
tempSec=tempSec/7;
week=tempSec.intValue();
tv1.setText(tempSec.toString());
}
//user method to check the date validity : check if date entered is a reasonable value
boolean checkValidity()
{
Long duration;
tempDate=Calendar.getInstance(); //get today's date in c
//check if user date is on or before today's date
if(tempDate.before(c))
{
AlertDialog.Builder ad=new AlertDialog.Builder(this);
ad.setMessage("Specified date should be on or before today's date");
ad.setNeutralButton("OK",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0,int arg1){}
}
);
ad.show();
return false;
}
//check if diff between user date and todays date is more than 280 days
duration=tempDate.getTimeInMillis()-c.getTimeInMillis();
duration/=86400000;
if(duration>280)
{
AlertDialog.Builder ad=new AlertDialog.Builder(this);
ad.setMessage("Specified date can be atmost 280 days before today's date");
ad.setNeutralButton("OK",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0,int arg1){}
}
).show();
return false;
}
return true;
}
}
If you need your listeners in the else-block, too, you can put this code before the if-block.
If the layout changes if the if or the else is executed, you can use the onClick-attribute in your XML-Layout definition.
To save your data, you can use SharedPreferences.