Date retrieval in android - android

In my application i have 3 text view arranged horizontally,1st previmage,2nd date,3rd nextimage.Now,when i click the 1st textview i should should display the previous month,(its printing) when once again i click means it should go to 2nd previous month of current month and this should go on..But when i click 2nd time it is coming the 1st previous month only its doesn't going backwards..Please help me.Thanks in advance..
This is my code:
prvmon.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
System.out.println("Inside left");
TextView date=(TextView)findViewById(R.id.date);
Calendar cal= Calendar.getInstance();
cal.add(cal.MONTH,-1);
Date date1=cal.getTime();
System.out.println("sssssss="+date1);
cal.setTime(date1);
SimpleDateFormat month_date = new SimpleDateFormat("MMMMM yyyy");
String month_name = month_date.format(cal.getTime());
date.setText(month_name);
}
});

The reason is that you are initializing your Calender instance everytime. So, its taking the current date/time instance. So, better would be initialize in once and use it again. Declare it globally and initialize it in onCreate().
Calendar calendar = null;
protected void onCreate(Bundle savedInstanceState){
calendar = Calendar.getInstance();
...
}
now, use this calender instance in your onClick() event.

Date date1=cal.getTime();
you're always setting it to the same time and 'going back exactly one month into the past'. So, define your Date date1=cal.getTime() outside of the onClick OR keep track of how many months you need to substract, by e.g. incrementing some value at the end of the onClick().
EDIT:
ok so let's take a look at your code again
final int clicks = 0; //we'll use this to track clicks
prvmon.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
int monthsToGo = --clicks;
// TODO Auto-generated method stub
System.out.println("Inside left");
TextView date=(TextView)findViewById(R.id.date);
Calendar cal= Calendar.getInstance();
cal.add(cal.MONTH, monthsToGo); //now it'll deduce -1 then -2 etc...
Date date1=cal.getTime();
System.out.println("sssssss="+date1);
cal.setTime(date1);
SimpleDateFormat month_date = new SimpleDateFormat("MMMMM yyyy");
String month_name = month_date.format(cal.getTime());
date.setText(month_name);
}
});

may be a full example will help:
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MonthActivity extends Activity {
private Calendar calendar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
calendar = Calendar.getInstance();
calendar.setTime(new Date());
final TextView textView = (TextView) findViewById(R.id.dateTextView);
updateTextView(textView);
Button prev = (Button) findViewById(R.id.prevCmd);
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calendar.add(Calendar.MONTH, -1);
updateTextView(textView);
}
});
Button next = (Button) findViewById(R.id.nextCmd);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calendar.add(Calendar.MONTH, 1);
updateTextView(textView);
}
});
}
private void updateTextView(TextView textView) {
textView.setText(""
+ calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT,
Locale.getDefault()));
}
}
and the Layout XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/prevCmd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text=" < " />
<TextView
android:id="#+id/dateTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/nextCmd"
android:layout_toRightOf="#+id/prevCmd"
android:gravity="center_vertical|center_horizontal"
android:paddingTop="8dp"
android:text="Jul"
android:textColor="#ffffff"
android:textSize="20dp"
android:textStyle="bold" />
<Button
android:id="#+id/nextCmd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text=" > " />
</RelativeLayout>

Related

Single button multiple action in sequence

I am using a single button to do two task.
1.Date Selection
2.Difference between two dates
As-is:
I am using 'onclick' method for two button.
btnDate2 using to select the date and onclick is(setDate2)
button9 using to calculate the difference between two dates and onclick is(diff)
To-be:
One button for selecting the date and calculate the difference between two dates.And it should be in sequence.ex:
1: Select date
2. Calculate the difference between dates
Current code:
MainActivity.java
package com.bar.example.myapplication;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.threeten.bp.LocalDate;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.format.DateTimeParseException;
import org.threeten.bp.temporal.ChronoUnit;
import java.text.SimpleDateFormat;
public class MainActivity extends AppCompatActivity {
public TextView txtResult, tv, textDivNumber, textAVG, txtZaMisiac;
public static TextView tvresult;
public Button reset, button, button1, button2, button9, editTextDate3, editTextDate5, btnok;
public EditText barcodeResult;
public static EditText courseTitleEditText;
private ListView offeringsListView;
private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d.M.uuuu");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextDate5 = (Button) findViewById(R.id.editText5);
button2 = (Button) findViewById(R.id.btnDate2);
txtResult = (TextView) findViewById(R.id.editText2);
editTextDate5.setText(DateFormat.format("dd.MM.yyyy", new java.util.Date()).toString());
}
public void diff(View view) {
SimpleDateFormat myFormat = new SimpleDateFormat("dd.MM.yyyy");
CharSequence inputString1 = editTextDate5.getText();
try {
LocalDate date1 = LocalDate.parse(inputString1, dateFormatter);
CharSequence inputString2 = button2.getText();
try {
LocalDate date2 = LocalDate.parse(inputString2, dateFormatter);
long diffDate = ChronoUnit.DAYS.between(date1, date2);
txtResult.setText(String.valueOf(diffDate));
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date2 is not a valid date: " + inputString2, Toast.LENGTH_SHORT).show();
}
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date1 is not a valid date: " + inputString1, Toast.LENGTH_SHORT).show();
}
}
public void setDate1(View view) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "Date Picker");
}
public void setDate2(View view) {
DialogFragment newFragment = new DatePickerFragment2();
newFragment.show(getFragmentManager(), "Date Picker");
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
Datepickerformat2.java
package com.bar.example.myapplication;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.Button;
import android.widget.DatePicker;
import java.util.Calendar;
public class DatePickerFragment2 extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Button btnDate2 = (Button) getActivity().findViewById(R.id.btnDate2);
String stringOfDate = day + "." + (month + 1) + "." + year;
btnDate2.setText(stringOfDate);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="1">
<TextView android:id="#+id/editText1" android:layout_width="47dp" android:layout_height="wrap_content" android:ems="10" android:inputType="textNoSuggestions" android:text="Date:" />
<Button android:id="#+id/editText5" android:layout_width="47dp" android:layout_height="wrap_content" android:layout_weight="0.50" android:ems="10" android:inputType="textNoSuggestions" android:text="" />
<TextView android:id="#+id/editText2" android:layout_width="49dp" android:layout_height="wrap_content" android:ems="10" android:inputType="textNoSuggestions" android:text="Expiry:" />
<Button android:id="#+id/btnDate2" android:layout_width="59dp" android:layout_height="wrap_content" android:layout_weight="0.41" android:ems="10" android:onClick="setDate2" android:text="" />
<Button android:id="#+id/button9" android:layout_width="59dp" android:layout_height="wrap_content" android:layout_weight="0.41" android:ems="10" android:inputType="textNoSuggestions" android:onClick="diff" android:text="calc" />
</LinearLayout>
with amended code.
With 1st Click ,
After selecting ok.
Now again i should click the calc button to know the days difference.
What i need is 1st click the date and select "ok" upon choosing the date.i should be able to see the days difference upon clicking "ok" as per screen instead of pressing again the button.
Requirement 3:
When edittext2 number is exceeds vs spinner2 number then edittext2 color should change it to red color and some doast message
When edittext2 number is reaching to very near vs spinner2 number then edittext2 color should change it to yellow color and some doast message
1.Add below method into MainActivity.java:
public void dualFunctions(View view) {
if(view.getTag() == null) view.setTag("0");
if(view.getTag().equals("0")){
view.setTag("1");
view.setBackgroundColor(Color.GREEN);
setDate2(view);
}else{
view.setTag("0"); // Remove this line for one shoot.
view.setBackgroundColor(Color.YELLOW);
diff(view);
}
}
2.Change the button in layout to use this method.
The method toggles between date selection and calculation. If date selection is allowed for only once, then remove the line with comment.
Hope that helps!
Updated:
public void onDateSet(DatePicker view, int year, int month, int day) {
Button btnDate2 = (Button) getActivity().findViewById(R.id.btnDate2);
String stringOfDate = day + "." + (month + 1) + "." + year;
btnDate2.setText(stringOfDate);
MainActivity activity = (MainActivity)getActivity();
activity.diff(btnDate2);
}
For Requirement3:
Added if-else to check conditions.
private final static int VERY_NEAR_DATE = 30;
public void diff(View view) {
SimpleDateFormat myFormat = new SimpleDateFormat("dd.MM.yyyy");
CharSequence inputString1 = editTextDate5.getText();
try {
LocalDate date1 = LocalDate.parse(inputString1, dateFormatter);
CharSequence inputString2 = button2.getText();
try {
LocalDate date2 = LocalDate.parse(inputString2, dateFormatter);
long diffDate = ChronoUnit.DAYS.between(date1, date2);
txtResult.setText(String.valueOf(diffDate));
diffDate = (Long)ok2.getSelectedItem() - diffDate;
if(diffDate < 0){
txtResult.setTextColor(Color.RED);
Toast.makeText(this, "Date not allowed!!", Toast.LENGTH_SHORT).show();
}else if(diffDate < VERY_NEAR_DATE) {
txtResult.setTextColor(Color.YELLOW);
Toast.makeText(this, "Date too near!", Toast.LENGTH_SHORT).show();
}
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date2 is not a valid date: " + inputString2, Toast.LENGTH_SHORT).show();
}
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date1 is not a valid date: " + inputString1, Toast.LENGTH_SHORT).show();
}
}
If need to update views after selection changed in spinner, then add below code inside onCreate():
ok2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
diff(null);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
});

I cant be able to set datepicker starts from tomorrows date(Material Design Datepicker)

Iam using Material Design Datepicker i can be able to set from tomorrows date but todays date is also showing in calendar i set for 29/11/2016 but it also showing 28/11/2016
How to disable that so that user cant select it
Iam using Material Design DatePicker
https://github.com/wdullaer/MaterialDateTimePicker
GregorianCalendar g1=new GregorianCalendar();
g1.add(Calendar.DATE, 1);
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.DAY_OF_MONTH, 30);
dateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatePickerDialog datePickerDialog ;
datePickerDialog = DatePickerDialog.newInstance(LoginSuccess.this, g1.get(Calendar.YEAR),
g1.get(Calendar.MONTH),
g1.get(Calendar.DAY_OF_MONTH));
datePickerDialog.setTitle("Select Date");
//datePickerDialog.setMinDate(g);
GregorianCalendar c2=new GregorianCalendar();
c2.setTimeInMillis(g1.getTimeInMillis()+(27*7*24*60*60*1000));
//c2.add(Calendar.DAY_OF_MONTH, 30);
List<Calendar> dayslist= new LinkedList<Calendar>();
Calendar[] daysArray;
Calendar cAux = Calendar.getInstance();
while ( cAux.getTimeInMillis() <= gc.getTimeInMillis())
{
if (cAux.get(Calendar.DAY_OF_WEEK)!=1)
{
Calendar c = Calendar.getInstance();
c.setTimeInMillis(cAux.getTimeInMillis());
dayslist.add(c);
}
cAux.setTimeInMillis(cAux.getTimeInMillis()+(24*60*60*1000));
}
daysArray = new Calendar[dayslist.size()];
for (int i = 0; i<daysArray.length;i++)
{
daysArray[i]=dayslist.get(i);
}
//g1.setTimeInMillis(g.getTimeInMillis()+(7*24*60*60*1000));
datePickerDialog.setMinDate(g1);
datePickerDialog.setMaxDate(c2);
datePickerDialog.show(getFragmentManager(), "DatePickerDialog");
datePickerDialog.setSelectableDays(daysArray);
}
Try this out!
dateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DAY_OF_YEAR, 1);
DatePickerDialog dpd = DatePickerDialog.newInstance(
MainActivity.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.setMinDate(now);
dpd.setThemeDark(modeDarkDate.isChecked());
dpd.vibrate(vibrateDate.isChecked());
dpd.dismissOnPause(dismissDate.isChecked());
dpd.showYearPickerFirst(showYearFirst.isChecked());
if (modeCustomAccentDate.isChecked()) {
dpd.setAccentColor(Color.parseColor("#9C27B0"));
}
if(titleDate.isChecked()) {
dpd.setTitle("DatePicker Title");
}
dpd.show(getFragmentManager(), "Datepickerdialog");
}
});
}
Hey i have done sample regarding the issue and able to get the date picker as you expect once check it and let me know
Java:
package yourpackage;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dateView = (TextView) findViewById(R.id.textView3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month + 1, day);
}
#SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(1);
Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT)
.show();
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 1) {
return new DatePickerDialog(this, myDateListener, year, month,
day + 1);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2 + 1, arg3);
}
};
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:onClick="setDate"
android:text="#string/date_button_set" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text="#string/date_label_set"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_marginTop="66dp"
android:layout_toLeftOf="#+id/button1"
android:text="#string/date_view_set"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/textView2"
android:layout_marginTop="72dp"
android:text="#string/date_selected"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
Values
<resources>
<string name="app_name">Androidr</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="text_label_1">Rate</string>
<string name="button_label">Submit</string>
<string name="text_label_2">Result: </string>
<string name="action_settings">Settings</string>
<string name="date_label_set">Press the button to set the date</string>
<string name="date_button_set">Set Date</string>
<string name="date_view_set">The Date is: </string>
<string name="date_selected"></string>
</resources>
g1.add(Calendar.DATE, +1);
check it like this
You should do this,
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, day + 1);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.YEAR, year);
datePickerDialog.getDatePicker().setMaxDate(maxDate.getTimeInMillis());
this will restrict you to select current date and let you select the
date starts from tomorrow.
From what I recall from the documentation for this library, I believe that if you set the selectable days for MaterialDateTimePicker then it overrides anything you have done set for min and max date. So if you pass an array of dates it will need to include your min and max dates, plus everything you want to see in between.

date picker dialog show on edit text double click

I have a search activity with two edit text fields. I like on edit text click date picker dialog to be show. However when I click on edit text, first the keyboard is shown, then after second click the date picker dialog is shown. Could somebody help me?
Here is activity code
package com.example.firstdemoapp.activities;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import com.example.firstdemoapp.R;
import com.example.firstdemoapp.model.StatusDK;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
public class SearchingTaxActivity extends Activity implements OnClickListener,
DatePickerDialog.OnDateSetListener, OnItemSelectedListener {
private Calendar calendarFrom;
private Calendar calendarTo;
private String myFormat;
private SimpleDateFormat sdf;
private EditText dateFrom;
private EditText dateTo;
private EditText activeEditText;
private Calendar activeCalendar;
private Spinner spinnerStatusDK;
private ArrayAdapter spinnerArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_tax);
calendarFrom = Calendar.getInstance();
calendarTo = Calendar.getInstance();
myFormat="dd/MM/yyyy";
sdf = new SimpleDateFormat(myFormat, Locale.US);
dateFrom = (EditText) findViewById(R.id.dateFrom);
dateTo = (EditText) findViewById(R.id.dateTo);
spinnerStatusDK=(Spinner)findViewById(R.id.spinnerStatusDK);
spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, new StatusDK[] {
new StatusDK( 0, "0" ),
new StatusDK( 1, "1" ),
new StatusDK( 2, "2" ),
});
spinnerStatusDK.setAdapter(spinnerArrayAdapter);
spinnerStatusDK.setOnItemSelectedListener(this);
dateFrom.setOnClickListener(this);
dateTo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == dateFrom) {
activeCalendar = calendarFrom;
activeEditText = dateFrom;
} else if (v == dateTo) {
activeCalendar = calendarTo;
activeEditText = dateTo;
}
new DatePickerDialog(SearchingTaxActivity.this, this,
activeCalendar.get(Calendar.YEAR),
activeCalendar.get(Calendar.MONTH),
activeCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
activeCalendar.set(Calendar.YEAR, year);
activeCalendar.set(Calendar.MONTH, monthOfYear);
activeCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
if (activeEditText != null) {
activeEditText.setText(sdf.format(activeCalendar.getTime()));
}
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
and the layout for the activity is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/dateFromTextView"
/>
<EditText
android:id="#+id/dateFrom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/edit_datefrom"
/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/dateToTextView"
/>
<EditText
android:id="#+id/dateTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/edit_dateto"
/>
<Spinner
android:id="#+id/spinnerStatusDK"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
I added android:focusableInTouchMode="false" for edit text in the xml file and this helped me. Because first focus event is fired, and then click event is fired.
you can try to hide a keyboard using InputMethodManager class
private void hideKeyboard(EditText et) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
}
This is best solution which is very useful for open any DatePicker & TimePicker Dialog from EditText,
editdate.setFocusable(false);
editdate.setKeyListener(null);

Why does setText() cause TextView to be re-printed at the top of the screen?

[edit] I have three sections: Title, Status, Priority, Time and Date, that are vertically aligned in that order. My problem is that when I setText() 'time' or 'date', the 'Priority' section and 'Time and Date' section get hoisted up. That is to say, the title of the 'Priority' section is completely align with the top bar and the 'Time and Date' title is right alongside it overlapping the content (instead of being below it).
The other two sections remain in their spot (at the top) but they are overlapped.
At the bottom are pictures.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- Title -->
<TextView
android:id="#+id/TitleLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/title_string"
android:textAppearance="?android:attr/textAppearanceLarge" >
</TextView>
<EditText
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/TitleLabel"
android:layout_marginTop="0dp"
android:ems="10"
android:hint="#string/enter_title_string"
android:inputType="textShortMessage">
<requestFocus />
</EditText>
<!-- Status -->
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/title"
android:layout_marginTop="25dp"
android:text="#string/status_string"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="#+id/statusGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/status"
android:orientation="horizontal"
android:layout_marginTop="12dp" >
<RadioButton
android:id="#+id/statusDone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/done_string" />
<RadioButton
android:id="#+id/statusNotDone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/not_done_string" />
</RadioGroup>
<!-- Priority -->
<TextView
android:id="#+id/priority"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/statusGroup"
android:layout_marginTop="0dp"
android:text="#string/priority_string"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="#+id/priorityGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/priority"
android:orientation="horizontal"
android:layout_marginTop="0dp"
android:text="#string/priority_string" >
<RadioButton
android:id="#+id/lowPriority"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/priority_low_string" />
<RadioButton
android:id="#+id/medPriority"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/priority_medium_string" />
<RadioButton
android:id="#+id/highPriority"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/priority_high_string" />
</RadioGroup>
<!-- Time and Date -->
<TextView
android:id="#+id/time_and_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/priorityGroup"
android:layout_marginTop="0dp"
android:text="#string/time_and_date_string"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/time_and_date"
android:layout_marginTop="0dp"
android:text="#string/no_date_set_string" />
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/time_and_date"
android:text="#string/no_time_set_string" />
<Button
android:id="#+id/date_picker_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/date"
android:text="#string/choose_date_string" />
<Button
android:id="#+id/time_picker_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#id/date_picker_button"
android:layout_below="#id/time"
android:text="#string/choose_time_string" />
<!-- Buttons -->
<Button
android:id="#+id/cancelButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginTop="0dp"
android:text="#string/cancel_string" />
<Button
android:id="#+id/resetButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="#string/reset_string" />
<Button
android:id="#+id/submitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="#string/submit_string" />
</RelativeLayout>
Here is the method I use to set it. I played around by commenting stuff and with an inclusive OR, if I set the date text or the time text, it all gets hoisted up.
Here is the full code of the activity:
See setDefaultDateTime for where the setText occurs.
package course.labs.todomanager;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import course.labs.todomanager.ToDoItem.Priority;
import course.labs.todomanager.ToDoItem.Status;
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()");
//TODO - Implement onClick().
setResult(RESULT_CANCELED);
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()");
//TODO - Reset data fields to default values
mTitleText.setText("");
setDefaultDateTime();
mStatusRadioGroup.setId(R.id.statusDone);
mPriorityRadioGroup.setId(R.id.medPriority);
}
});
// 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
//TODO - Get Priority
Priority priority = getPriority();
//TODO - Get Status
Status status = getStatus();
//TODO - Title
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);
//TODO - return data Intent and finish
setResult(RESULT_OK, data);
finish();
}
});
}
// 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.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
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 year, int monthOfYear, int dayOfMonth) {
// 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 year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
setDateString(year, monthOfYear, dayOfMonth);
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);
}
}
Any ideas? I appreciate your help!
Pics:
The problems in your code in this code
mStatusRadioGroup.setId(R.id.statusDone);
mPriorityRadioGroup.setId(R.id.medPriority);

How to pass data from date picker and spinner to another activity

I'm a beginning android developer.
I need to pass data from two date pickers and a spinner to another activity.
Can some one help me with this code:
package qi.com;
import java.text.DateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
//multi date input
public class CoaActivity extends Activity implements AdapterView.OnItemSelectedListener {
TextView selection;
TextView mDateStart;
TextView mDateEnd;
Button mPickStart;
Button mPickEnd;
Calendar startDate;
Calendar EndDate;
int mYear;
int mMonth;
int mDay;
//list menu
String[] items = {"Pendapatan","Biaya"};
static final int DATE_DIALOG_ID = 0;
private TextView activeDateDisplay;
private Calendar activeDate;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//display to text view from list View
selection = (TextView) findViewById(R.id.selection);
Spinner spin= (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa= new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
//capture view elements
mDateStart = (TextView) findViewById(R.id.DateStar);
mPickStart = (Button) findViewById(R.id.btn_PickDateStart);
//current date
startDate = Calendar.getInstance();
//listener click button
mPickStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDateDialog(mDateStart, startDate);
}
});
//END Date
mDateEnd = (TextView) findViewById(R.id.DateEnd);
mPickEnd = (Button) findViewById(R.id.btn_PickDateEnd);
EndDate = Calendar.getInstance();
//listener click button
mPickEnd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDateDialog(mDateEnd, EndDate);
}
});
//display current date
updateDisplay(mDateStart, startDate);
updateDisplay(mDateEnd, EndDate);
//Detail("tes");
}
private void updateDisplay(TextView dateDisplay, Calendar date) {
dateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
//.append(date.get(Calendar.DAY_OF_MONTH)).append("-")
.append(date.get(Calendar.DATE)).append("-")
.append(date.get(Calendar.MONTH) + 1).append("-")
.append(date.get(Calendar.YEAR)).append(" "));
//.append(DateFormat.getDateInstance(Calendar.MONTH)));
}
public void showDateDialog(TextView dateDisplay, Calendar date) {
activeDateDisplay = dateDisplay;
activeDate = date;
showDialog(DATE_DIALOG_ID);
}
private OnDateSetListener dateSetListener = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
activeDate.set(Calendar.YEAR, year);
activeDate.set(Calendar.MONTH, monthOfYear);
//activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
activeDate.set(Calendar.DATE, dayOfMonth);
updateDisplay(activeDateDisplay, activeDate);
unregisterDateDisplay();
}
};
private void unregisterDateDisplay() {
activeDateDisplay = null;
activeDate = null;
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, dateSetListener, activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), activeDate.get(Calendar.DATE));
}
return null;
}
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), activeDate.get(Calendar.DATE));
break;
}
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
selection.setText(items[position]);
Intent grid=new Intent(this, Grid.class);
this.startActivity(grid);
//send to another activity
//Detail(items[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}
//another activity
public void Detail(String id)
//public void Detail()
{
//Intent detail=new Intent(con, Detail.class);
Intent grid=new Intent(this, Grid.class);
grid.putExtra("IDP", id);
this.startActivity(grid);
//Toast.makeText(this, "list : " , Toast.LENGTH_SHORT).show();
}
}
This is the xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Mulai dari :" />
<TextView
android:id="#+id/DateStar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/btn_PickDateStart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Tanggal Awal" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sampai dengan :" />
<TextView
android:id="#+id/DateEnd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/btn_PickDateEnd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Tanggal Akhir" />
<TextView
android:id="#+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false" />
</LinearLayout>
Use the long value that Date gives you, and put it in the extras, along with everything else you are sending to the activity.

Categories

Resources