I'm using two text views in a dialog, one is for from date and another is for to date. Now when i click on from date text view the date picker dialog opens and when i select the date it is not updated in the text view, if i open the date picker again and select the date for the second time the date is updated in the text view. can any one figure out why it is not updated the first time.
public static void datePickerDialog(final Context context) {
dialog = new Dialog(context);
dialog.setContentView(R.layout.date_picker_dialog);
fromDateText = dialog.findViewById(R.id.from_date);
toDateText = dialog.findViewById(R.id.to_date);
fromDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datePicker(context);
}
});
toDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datePicker(context);
}
});
dialog.show();
fromDateText.setText(fromDate);
toDateText.setText(toDate);
}
public static void datePicker(Context context){
fromDatePicker = new DatePickerDialog(context, android.R.style.Theme_Holo_Light_Dialog_MinWidth
,fromDateListner, fromDay, fromMonth, fromYear);
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
fromDatePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
fromDatePicker.show();
fromDateListner = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month+=1;
fromDate = dayOfMonth+"/"+month+"/"+year;
setDate();
}
};
}
private static void setDate() {
try {
dateFrom = simpleDateFormat.parse(fromDate);
dateTo = simpleDateFormat.parse(toDate);
} catch (ParseException e) {
e.printStackTrace();
}
fromDateText.setText(dateFrom.toString());
toDateText.setText(dateTo.toString());
}
fromDateListner is initialized after the dialog creation, so the first time the DatePickerDialog is created without listener.
Move the fromDateListner = new DatePickerDialog.OnDateSetListener() ... part before fromDatePicker = new DatePickerDialog(context ...
Can you try like this?
private static void setDate() {
try {
dateFrom = simpleDateFormat.parse(fromDate);
dateTo = simpleDateFormat.parse(toDate);
fromDateText.setText(dateFrom.toString());
toDateText.setText(dateTo.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
// Edit:
Check my code:
private void showDatePicker() {
final Calendar myCalendar = Calendar.getInstance();
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
setDate(myCalendar.getTime());
}
};
if (getActivity() != null) {
new DatePickerDialog(getActivity(), date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
}
private void setDate(Date time) {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.US);
editText.setText(sdf.format(time));
}
Try this code ..
take boolean variable for selected textview ...
change method like this way..
public class DialogActiivty extends AppCompatActivity {
private TextView fromDateText,toDateText;
private String fromDate,toDate;
private Dialog dialog;
private DatePickerDialog fromDatePicker;
private SimpleDateFormat simpleDateFormat;
private Calendar calendar;
private int year, month, day;
private boolean fromSelected=false,toSelected=true;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datePickerDialog(DialogActiivty.this);
}
public void datePickerDialog(final Context context) {
calendar=Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
dialog = new Dialog(context);
dialog.setContentView(R.layout.date_picker_dialog);
fromDateText = dialog.findViewById(R.id.from_date);
toDateText = dialog.findViewById(R.id.to_date);
fromDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toSelected=false;
fromSelected=true;
datePicker(context);
}
});
toDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fromSelected=false;
toSelected=true;
datePicker(context);
}
});
dialog.show();
// fromDateText.setText(fromDate);
// toDateText.setText(toDate);
}
public void datePicker(Context context){
fromDatePicker = new DatePickerDialog(context, android.R.style.Theme_Holo_Light_Dialog_MinWidth
,fromDateListner, year, month, day);
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
fromDatePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
fromDatePicker.show();
}
DatePickerDialog.OnDateSetListener fromDateListner = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month+=1;
fromDate = dayOfMonth+"/"+month+"/"+year;
setDate(fromDate);
}
};
private void setDate(String fromDate) {
if (fromSelected) {
fromDateText.setText(fromDate);
}
if (toSelected) {
toDateText.setText(fromDate);
}
}
}
Related
This is the Java code that Datepicker and Timepicker work. Those two are working properly so I want to send that selected date and time to the next activity(Doctor_Time_Picking_data_page.java)
Doctor_Time_Picking_page.java
public class Doctor_Time_Picking_page extends AppCompatActivity {
public static final String TEXT_TO_SEND ="com.example.dogapp.TEXT_TO_SEND";
private DatePickerDialog datePickerDialog;
private Button dateButton;
private Button timeButton;
private Bundle savedInstanceState;
private Button saveButton;
private String DATE;
//On Create method-------------------------------------------------------------------------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_time_picking_page);
initDatePicker();
dateButton = findViewById(R.id.datePickerButton);
timeButton = findViewById(R.id.timeButton);
saveButton = findViewById(R.id.date_time_save_button);
Intent intent = new Intent(getApplicationContext(),Doctor_Time_Picking_data_page.class);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent);
}
});
}
//-----------------------------------------------------------------------------------------------------------------------------------
private Bundle initDatePicker()
{
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker datePicker, 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 = AlertDialog.THEME_HOLO_LIGHT;
datePickerDialog = new DatePickerDialog(this, style, dateSetListener, year, month, day);
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
return null;
}
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";
//default should never happen
return "JAN";
}
public void openDatePicker(View view)
{
datePickerDialog.setTitle("Select Date");
datePickerDialog.show();
}
//Time Button
int hour, minute;
public void popTimePicker(View view)
{
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute)
{
hour = selectedHour;
minute = selectedMinute;
timeButton.setText(String.format(Locale.getDefault(), "%02d:%02d",hour, minute));
}
};
TimePickerDialog timePickerDialog = new TimePickerDialog(this, /*style,*/ onTimeSetListener, hour, minute, true);
timePickerDialog.setTitle("Select Time");
timePickerDialog.show();
}
}
This is the page where I want to show the date and Time selected form my previous activity(Doctor_Time_Picking_page.java)
Doctor_Time_Picking_data_page.java:
public class Doctor_Time_Picking_data_page extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_time_picking_data_page);
Button Button1a = findViewById(R.id.doc_page4_btn1);
Button Button2a = findViewById(R.id.doc_page4_btn2);
Button Button3a = findViewById(R.id.doc_page4_btn3);
Dialog nDialog = new Dialog(this);
Button1a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Doctor_Time_Picking_data_page.this,Doctor_Appoinment_payment.class);
startActivity(intent);
}
});
Button2a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Doctor_Time_Picking_data_page.this,Doctor_Time_Picking_page.class);
startActivity(intent);
}
});
Button3a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
nDialog.setContentView(R.layout.activity_doctor_delete_popup_msg);
nDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Intent intent = new Intent(Doctor_Time_Picking_data_page.this,Doctor_delete_popup_msg.class);
startActivity(intent);
}
});
}
}
In my project there are three buttons those are Select Time, Select Date and save button when I select each button Datepicker and Timepicker dialogues appear when I select Date or time those Data is appearing on the Buttons I want to pass those data to my next activity which is Doctor_Time_Picking_data_page.java and display them to user. What I now want is I want to pass That data selected from those Pickers to next activity
You need to pass an intent extra to the other activity to get your result. Follow the steps:
Create a filed name date in your class:
private String date = "JAN 1 2022"; // I have given a sample date
You need to store the date inside the DateSetListener like this:
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day)
{
month = month + 1;
date = makeDateString(day, month, year);
dateButton.setText(date);
}
};
You need to pass that date on the click of the save button:
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent.putExtra("date", date);
startActivity(intent);
}
});
Then you need to get that date on the other activity like this:
public class Doctor_Time_Picking_data_page extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_time_picking_data_page);
String date = getIntent().getStringExtra("date", "");
// 👆 that is the date from the previous activity
...
});
...
}
Below is my code of Datepicker allowing user to select dates and updates the textview with the selected date. How do I update the textview with an error message when user selects the date before today?
public void startCalender() {
txtTrigger = (TextView) findViewById(R.id.calTrigger);
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
myCalendar.set(Calendar.DAY_OF_MONTH, day);
myCalendar.set(Calendar.MONTH, month);
myCalendar.set(Calendar.YEAR, year);
updateLabel();
}
};
txtTrigger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DatePickerDialog(DisplayCeeAct.this, date,
myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
private void updateLabel() {
String no = "<font color='red'>NO</font>.";
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());
if (myCalendar.after(myCalendar.getTime())){
txtTrigger.setText(sdf.format(myCalendar.getTime()));
}
else {
txtTrigger.setText(Html.fromHtml(no), TextView.BufferType.SPANNABLE);
}
}
Seems this line is crashing:
txtTrigger.setText(Html.fromHtml(no), TextView.BufferType.SPANNABLE);
A better approach would be:
txtTrigger.setText("NO");
txtTrigger.setTextColor(Color.RED);
I am working on how to put Date value into my PHP/MySQL using android's date picker.
I want to make a Sharing Parking lot application that owner can register one's parking place with its information like operating time. Then user can use it with choosing the beginning and ending points.
I searched a lot but need more specific information.
How can I save operating time slot into PHP/MySQL?
The following is my android java code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.avtivity_date_time);
mText1 = (TextView) findViewById(R.id.text1);
mPickDate1 = (Button) findViewById(R.id.pickDate1);
mPickTime1 = (Button) findViewById(R.id.pickTime1);
mText2 = (TextView) findViewById(R.id.text2);
mPickDate2 = (Button) findViewById(R.id.pickDate2);
mPickTime2 = (Button) findViewById(R.id.pickTime2);
mPickDate1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID_1);
}
});
mPickDate2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID_2);
}
});
mPickTime1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID_1);
}
});
mPickTime2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID_2);
}
});
final Calendar c = Calendar.getInstance();
mYear1 = c.get(Calendar.YEAR);
mMonth1 = c.get(Calendar.MONTH);
mDay1 = c.get(Calendar.DAY_OF_MONTH);
mHour1 = c.get(Calendar.HOUR_OF_DAY);
mMinute1 = c.get(Calendar.MINUTE);
mYear2 = c.get(Calendar.YEAR);
mMonth2 = c.get(Calendar.MONTH);
mDay2 = c.get(Calendar.DAY_OF_MONTH);
mHour2 = c.get(Calendar.HOUR_OF_DAY);
mMinute2 = c.get(Calendar.MINUTE);
updateDisplay();
}
private void updateDisplay() {
mText1.setText(String.format("시작 : %d년 %d월 %d일 %d시 %d분", mYear1, mMonth1 + 1, mDay1, mHour1, mMinute1));
mText2.setText(String.format("종료 : %d년 %d월 %d일 %d시 %d분", mYear2, mMonth2 + 1, mDay2, mHour2, mMinute2));
}
private DatePickerDialog.OnDateSetListener mDateSetListener1 =
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear1 = year;
mMonth1 = monthOfYear;
mDay1 = dayOfMonth;
updateDisplay();
}
};
private DatePickerDialog.OnDateSetListener mDateSetListener2 =
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear2 = year;
mMonth2 = monthOfYear;
mDay2 = dayOfMonth;
updateDisplay();
}
};
private TimePickerDialog.OnTimeSetListener mTimeSetListener1 =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour1 = hourOfDay;
mMinute1 = minute;
updateDisplay();
}
};
private TimePickerDialog.OnTimeSetListener mTimeSetListener2 =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour2 = hourOfDay;
mMinute2 = minute;
updateDisplay();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID_1:
return new DatePickerDialog(this, mDateSetListener1, mYear1, mMonth1, mDay1);
case TIME_DIALOG_ID_1:
return new TimePickerDialog(this, mTimeSetListener1, mHour1, mMinute1, false);
case DATE_DIALOG_ID_2:
return new DatePickerDialog(this, mDateSetListener2, mYear2, mMonth2, mDay2);
case TIME_DIALOG_ID_2:
return new TimePickerDialog(this, mTimeSetListener2, mHour2, mMinute2, false);
}
return null;
}
private Long getDateInMS(String stringDateTime) throws ParseException {
SimpleDateFormat simpledateformat1 = new SimpleDateFormat("yyyy MM dd hh mm");
SimpleDateFormat simpledateformat2 = new SimpleDateFormat("yyyy MM dd hh mm");
String formatdate1 = simpledateformat1.format("mYear1, mMonth1, mDay1, mHour1, mMinute1");
String formatdate2 = simpledateformat2.format("mYear12, mMonth2, mDay2, mHour2, mMinute2");
Date startdate = simpledateformat1.parse(formatdate1);
Date enddate = simpledateformat2.parse(formatdate2);
return null;
}
I met a interest issue about getting the String from another activity to main activity.
The procedures:
1. User click the editText to trigger the calendar shows with DatePickerDialog
Once the date that user picked is valid, it return to be a String and set on editText, then click submit button will send to activity_confirm.
When users clicked "Edit" button, the activity_confirm will return all values and go through with dataHolder to send those data to Main activity's fragment and setText on those editText.
I can get all the values correctly except DOB, I wonder why it will return null on activity_confirm while setText() on the TextView of it, is the error existed on fragment's method? But I was confused.
Thanks for any assistance or suggestion.
Main activity:
btn_Click.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
......
//Get from fragment and intent to activity_confirm
extras.putString("confirmDOB", strDOB);
......
}
}
Fragment:
......
TextInputLayout DOBpicker;
EditText DOB;
Calendar myCalendar = Calendar.getInstance();
......
final DatePickerDialog.OnDateSetListener date = (new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar checkValid = new GregorianCalendar(year, monthOfYear, dayOfMonth);
Calendar minAdultAge = new GregorianCalendar();
minAdultAge.add(Calendar.YEAR, -18);
if (minAdultAge.before(checkValid)) {
//Snackbar.make(correspondence, "Applicant's Date of birth cannot be 18 or below.", Snackbar.LENGTH_LONG).show();
DOBpicker.setErrorEnabled(true);
DOBpicker.setError("Applicant's Date of birth cannot be 18 or below.");
strDOB = "";
DOB.setText(strDOB);
insureApplicant2.put(1, strDOB);
DOBpicker.clearFocus();
} else {
DOBpicker.setErrorEnabled(false);
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
}
});
DOB.setOnFocusChangeListener(new View.OnFocusChangeListener(){
#Override
public void onFocusChange(View view, boolean isFocus){
if(isFocus){
new DatePickerDialog(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
}
});
private void updateLabel(){
String myFormat = "dd/MM/yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
DOB.setText(sdf.format(myCalendar.getTime()));
strDOB = DOB.getText().toString().trim();
insureApplicant2.put(1, strDOB);
passToActivity2("DOB", DOB.getText().toString().trim());
}
activity_confirm:
//onCreate()
......
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras != null) {
......
strDOB = extras.getString("ConfirmDOB");
//Log.e("getStringDate", String.valueOf(extras.getString("confirmDOB"))); //can get value
......
DOB.setText(strDOB);
//DOB.setText(String.valueOf(extras.getString("ConfirmDOB")));
//DOB.setText(strDOB);
//All return null ?!
......
} else {
......
DOB = null;
}
}
......
//End of onCreate()
......
btn_editInfo.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
......
dataHolder.setDob(strDOB);
......
//intent to main activity
}
});
......
dataHolder (store those editText value for get/set):
public class fragment_data_holder {
private static data_holder mInstance;
......
private String dob;
......
public static data_holder getmInstance(){
if (mInstance == null) {
return mInstance = new data_holder();
} else {
return mInstance;
}
}
//Getter and Setter
......
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
}
Your spelling is different. On MainActivity it is "confirmDOB" while on activity_confirm it is "ConfirmDOB"
I am using a DatePicker so that the user can select a date and find out the sunrise and sunset times for that particular date.
The webservice I am using requires the date to be snet in the following format dd/MM but I would like the button to show the date in the format DDth MMMM YYYY e.g 21st March 2013
Any advice on how I should I go about doing this?
Code below as requested:
public class SunriseSunset extends Activity implements OnClickListener {
public Button getLocation;
public Button setLocationJapan;
public TextView LongCoord;
public TextView LatCoord;
public double longitude;
public double latitude;
public LocationManager lm;
public Spinner Locationspinner;
public DateDialogFragment frag;
public Button date;
public Calendar now;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sunrisesunset);
//Date stuff
now = Calendar.getInstance();
date = (Button)findViewById(R.id.date_button);
date.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)+1)+"-"+String.valueOf(now.get(Calendar.MONTH))+"-"+String.valueOf(now.get(Calendar.YEAR)));
date.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog();
}
});
}
// More date stuff
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
date.setText(String.valueOf(day)+"-"+String.valueOf(month+1)+"-"+String.valueOf(year));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment");
}
public interface DateDialogFragmentListener{
//this interface is a listener between the Date Dialog fragment and the activity to update the buttons date
public void updateChangedDate(int year, int month, int day);
}
public void addListenerOnSpinnerItemSelection() {
Locationspinner = (Spinner) findViewById(R.id.Locationspinner);
Locationspinner
.setOnItemSelectedListener(new CustomOnItemSelectedListener(
this));
}
private class LongRunningGetIO extends AsyncTask<Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// Finds todays date and adds that into the URL
SimpleDateFormat df = new SimpleDateFormat("dd/MM");
String formattedDate = df.format(now.getTime());
String finalURL = "http://www.earthtools.org/sun/"
+ LatCoord.getText().toString().trim() + "/"
+ LongCoord.getText().toString().trim() + "/"
+ formattedDate + "/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results != null) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(results));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
TextView tvSunset = (TextView) findViewById(R.id.Sunset);
tvSunrise.setText(doc.getElementsByTagName("sunrise").item(0).getTextContent());
tvSunset.setText(doc.getElementsByTagName("sunset").item(0).getTextContent());
} catch (Exception e) {
e.printStackTrace();
}
}
Button b = (Button) findViewById(R.id.CalculateSunriseSunset);
b.setClickable(true);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
DateDialogFragment:
import java.util.Calendar;
import richgrundy.learnphotography.SunriseSunset.DateDialogFragmentListener;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.widget.DatePicker;
public class DateDialogFragment extends DialogFragment {
public static String TAG = "DateDialogFragment";
static Context mContext; //I guess hold the context that called it. Needed when making a DatePickerDialog. I guess its needed when conncting the fragment with the context
static int mYear;
static int mMonth;
static int mDay;
static DateDialogFragmentListener mListener;
public static DateDialogFragment newInstance(Context context, DateDialogFragmentListener listener, Calendar now) {
DateDialogFragment dialog = new DateDialogFragment();
mContext = context;
mListener = listener;
mYear = now.get(Calendar.YEAR);
mMonth = now.get(Calendar.MONTH);
mDay = now.get(Calendar.DAY_OF_MONTH);
return dialog;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(mContext, mDateSetListener, mYear, mMonth, mDay);
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
mListener.updateChangedDate(year, monthOfYear, dayOfMonth);
}
};
}
Your help would be greatly appreciated.
Please ask questions for clarification if need =)
----------------UPDATE-------------------------
I'm getting there, updated code now looks like this:
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
DateFormat format = new SimpleDateFormat("DD MM yyyy"); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime()));
date.setText(String.valueOf(day)+"-"+String.valueOf(month+1)+"-"+String.valueOf(year));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment"); }
Just use another SimpleDateFormat to format it.
public void updateChangedDate(int year, int month, int day) {
DateFormat format = new SimpleDateFormat("DD MM YYYY"); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime());
}
Unfortunately there is nothing provided by Java to automatically get the proper suffix for ordinal dates (2nd, 13*th*, 21st, etc.)
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
now.set(year, month, day);
date.setText(DateFormat.format("dd MMMM yyyy", now));
}
}, now);
frag.show(ft, "DateDialogFragment"); }
Change
date.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)+1)+"-"+String.valueOf(now.get(Calendar.MONTH))+"-"+String.valueOf(now.get(Calendar.YEAR)));
to
date.setText(DateFormat.format("dd MMMM yyyy", Calendar.getInstance()));
public void showDialog()
{
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener()
{
public void updateChangedDate(int year, int month, int day)
{
String dateFormate = "dd'" + getDayOfMonthSuffix(day) +"' MM yyyy";
DateFormat format = new SimpleDateFormat(dateFormate); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime()));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment");
}
String getDayOfMonthSuffix(final int n) {
checkArgument(n >= 1 && n <= 31), "illegal day of month: " + n);
if (n >= 11 && n <= 13) {
return "th";
}
switch (n % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
I copy above getDayOfMonthSuffix function from the below link
getDayOfMonthSuffix