Android DatePicker and Button issues - android

I'm trying to have a DatePicker dialog display when a user clicks on a button that says "Set your birthday", and what I need then is for the button to then display the user's selection back in the button. I have tried some of the solutions listed on this site with a TextView, but all to no avail. The DatePicker is displaying just fine, but I can't get the data to show up on the Button. I've tried these solutions: DatePicker not updating Textview in Android Display datepickers value in a textview Android: DatePicker and DatePicker Dialog How to transfer the formatted date string from my DatePickerFragment?
Here's my code:
First the DatePickerFragment:
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
TheListener listener;
public interface TheListener {
public void returnDate(String date);
}
#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);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(c.getTime());
if (listener != null) {
listener.returnDate(formattedDate);
}
}
}
Now, the Fragment that is calling it:
public class SignUpFragment extends Fragment implements MyBirthday.TheListener {
private Button btnBirthday;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_signup, container, false);
return view;
}
#Override
public void onResume() {
super.onResume();
btnBirthday = (Button) getActivity().findViewById(R.id.signup_birthday_button);
btnBirthday.setText("Set your birthday");
btnBirthday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
picker.show(getFragmentManager(), "datePicker");
}
});
}
#Override
public void returnDate(String date) {
btnBirthday.setText(date);
}
}
Any and all help will be greatly appreciated. If this is a duplicate question, I'm sorry for that, but I couldn't find a way to get my program to behave in the way I would like for it to. I couldn't find a solution on here.
Thanks in advance.

Try this. This will show you how to render the information in a textview, but you can transfer that to a button as well. You can find the full source code on http://www.ahotbrew.com/android-datepicker-example/
package com.ahotbrew.datepicker;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends ActionBarActivity {
public static TextView SelectedDateView;
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);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
SelectedDateView.setText("Selected Date: " + (month + 1) + "-" + day + "-" + year);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SelectedDateView = (TextView) findViewById(R.id.selected_date);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}

Related

DatePickerDialog result back to Fragment?

I want to get the selected Date from the DatePickerDialog back to my Fragment.
Whe i test it, i only get in the Build Log this Error:
E/ViewRootImpl: sendUserActionEvent() mView == null
Testing my code on an Samsung Galaxy S6 Edge (7.0)
The Dialog appears, i can choose a date, click on ok but dont get the result to my TextView... Did i forget a little detail??
My Fragment where i call the DatePickerDialog:
package at.marcelklein.drautaxi;
import android.app.DatePickerDialog;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Calendar;
/**
* Created by Marcel on 10.09.2017.
*/
public class FourthFragment extends Fragment implements DatePickerDialog.OnDateSetListener {
View myView;
TextView textView;
Button btnDayStart, btnDayEnd;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fourth_layout, container, false);
btnDayStart = (Button) myView.findViewById(R.id.button_daystart);
btnDayEnd = (Button) myView.findViewById(R.id.button_dayend);
textView = (TextView) myView.findViewById(R.id.textView12);
btnDayStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
FragmentTransaction ft = ((FragmentActivity)getActivity()).getSupportFragmentManager().beginTransaction();
datePicker.show(ft, "datepicker");
}
});
btnDayEnd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//showDialog();
}
});
return myView;
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
textView.setText(currentDateString);
}
}
DatePickerDialog Fragment:
package at.marcelklein.drautaxi;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment {
DatePickerDialog.OnDateSetListener onDateSet;
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
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(), onDateSet, year, month, day);
}
}
Thanks in advance!
You forgot to assign your fragment as a listener. Add it as listener like this
btnDayStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.onDateSet = FourthFragment.this
FragmentTransaction ft = ((FragmentActivity)getActivity()).getSupportFragmentManager().beginTransaction();
datePicker.show(ft, "datepicker");
}
});
I changed my code to this: DatePickerDialog
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
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);
}
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
TextView tv = (TextView) getActivity().findViewById(R.id.textView12);
DecimalFormat df = new DecimalFormat("00");
tv.setText("Gewähltes Datum:");
tv.setText(tv.getText() + "\nJahr: " + year);
tv.setText(tv.getText() + "\nMonat: " + df.format(month));
tv.setText(tv.getText() + "\nTag: " + df.format(day));
}
----------- And my Fragment where i call the DatePickerDialog:
public class FourthFragment extends Fragment {
View myView;
public TextView textView;
Button btnDayStart, btnDayEnd;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fourth_layout, container, false);
btnDayStart = (Button) myView.findViewById(R.id.button_daystart);
btnDayEnd = (Button) myView.findViewById(R.id.button_dayend);
textView = (TextView) myView.findViewById(R.id.textView12);
btnDayStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getFragmentManager(), "date Picker");
}
});
return myView;
}
Now i change the TextView directly from the DatePickerDialog.
I think thats not the best Solution...
The think i want is a Range Date Picker like "TimeSquare DatePicker".
But i cant choose days from the past in "TimeSquare DatePicker".
Any suggestions?

How to set a minimum date for an EditText field?

I'm trying to set a minimum date (which is supposed to be the current date) so that the user won't be able to select a date older than today. I'm working in a fragment as you can see. I already searched for help but either it wasn't clear to me since i'm just starting with coding or i just failed to use it. Here is what i coded until now but i can't go further.
public 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 datePicker, int year, int month, int day) {
Calendar cal = new GregorianCalendar(year, month, day);
setDate(cal);
}
protected void setDate(final Calendar calendar) {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
((TextView) getActivity().findViewById(R.id.datenaissance)).setText(dateFormat.format(calendar.getTime()));
}
}
Here is the second fragment i'm working with:
package cm.opep.opep.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import cm.opep.opep.R;
public class RegistrationFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_registration, container, false);
initUI(v);
return v;
}
private void initUI(View v){
//Lancement de la date de naissance
EditText datenaissance = (EditText) v.findViewById(R.id.datenaissance);
datenaissance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatePickerFragment fragment = new DatePickerFragment();
fragment.show(getFragmentManager(), "datePicker");
}
});
}
}
Here's the XML code:
<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"
android:background="#color/white"
tools:context="cm.opep.opep.Tiroir$PlaceholderFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="UselessParent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/datenaissance"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:hint="#string/date_de_naissance"
android:inputType="date"
android:textColor="#color/colorPrimaryDark"
android:textSize="12sp"
android:onClick="datePicker"
android:focusable="False"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Any help will be appreciated. Thanks
All you need to do is create an instance of DatePickerDialog and using the 'set min date()' function.
public 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
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
// Here you can set the minimum date on date picker ********
dialog.getDatePicker().setMinDate(new Date().getTime());
return dialog;
}
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
Calendar cal = new GregorianCalendar(year, month, day);
setDate(cal);
}
protected void setDate(final Calendar calendar) {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
((TextView) getActivity().findViewById(R.id.datenaissance)).setText(dateFormat.format(calendar.getTime()));
}
}
or you can use this class:
public class StartDatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener {
Calendar c = Calendar.getInstance();
int startYear = c.get(Calendar.YEAR);
int startMonth = c.get(Calendar.MONTH);
int startDay = c.get(Calendar.DAY_OF_MONTH);
SharedPreferences objSharedPreferences;
SharedPreferences.Editor objEditor;
private Activity activity;
private View component;
public StartDatePicker(Activity activity, View component) {
this.activity = activity;
this.component = component;
createSharedPreferences();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
// Use the current date as the default date in the picker
DatePickerDialog dialog = new DatePickerDialog(activity, this, startYear, startMonth, startDay);
// dialog.getDatePicker().setMaxDate(new Date().getTime());
// dialog.getDatePicker().setMinDate(new Date().getTime());
return dialog;
}
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
try {
startDay = dayOfMonth;
startMonth = monthOfYear + 1;
startYear = year;
String dateToBeSet = startDay + "-" + getMonth(startMonth) + "-" + startYear;
if (component instanceof EditText) {
((EditText) component).setText(dateToBeSet);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month - 1].substring(0, 3);
}
}
On editText click use this code :
DialogFragment dialogFragment = new StartDatePicker(this, fromDateEditText);
dialogFragment.show(getFragmentManager(), "start_date_picker");

Android DatePicker fails on android 2.3.3

As I am new to Android development I am trying to display DatePicker dialog on Android 2.3.3 emulator,but while it is crashing. I am followed what am I missing to include in my code? But this code is working in Android 4.0.
DatePickerFragment class
public class DatePickerFragment extends DialogFragment implements 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);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
The activity class that starts the DatePicker Dialog:
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
public class FormAnalysis extends FragmentActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fanalysis);
//getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.fanalysis, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//switch (item.getItemId()) {
// case android.R.id.home:
// NavUtils.navigateUpFromSameTask(this);
return true;
//}
//return super.onOptionsItemSelected(item);
}
public void generate(View view){
}
public void startDialog(View view){
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");} }
Update
Here is the Stack Trace
[2012-11-16 00:31:55 - Food Security] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=kz.bimash.food.security/.Starter }
[2012-11-16 00:31:55 - Food Security] ActivityManager: Warning: Activity not started, its current task has been brought to the front
Your DialogFragment import is for the incorrect version of the class. It needs to be android.support.v4.app.DialogFragment instead of android.app.DialogFragment, otherwise it will not work correctly on 2.3.

How to set the date from DatePicker dialog for multiple calls

Good day, can't seem to find a solution for this. i have 2 buttons that when pressed, opens a datepickerdialog, but my problem now is , how can i set them to the appropriate button on OnDateSet method. I am using a DialogFragment for the date and then implementing the DateListener in my activity. I have tried using getTag() but no success in getting the tag. here is what i tried:
public void showfromDatePickerDialog(View v) {
DialogFragment dateFragment = new DateDialogFragment();
dateFragment.show(getSupportFragmentManager(), "fromdatePicker");
}
public void showtoDatePickerDialog(View v) {
DialogFragment dateFragment = new DateDialogFragment();
dateFragment.show(getSupportFragmentManager(), "todatePicker");
}
public void onDateSet(DatePicker view, int year, int month, int day) {
StringBuilder builder = new StringBuilder();
builder.append(day).append("-")
.append(month).append("-")
.append(year);
String text= builder.toString();
if(view.getTag().toString().equals("fromdatePicker")) { // error here
Log.d(TAG, "got here" + text);
fromdate.setText(text);
}
if(view.getTag() == "todatePicker") {
todate.setText(text);
}
any ideas how to implement this? i keep seeing solutions about using 2 different DialogFragment class but am guessing there should be another way. or am i wrong? Thank you
ok, i have a work around for these. which can be helpful for anyone with this problem. if its slightly incorrect please let me know and i can change it. but this is what i did to solve this issue.
in on DateSet:
public void onDateSet(DatePicker view, int year, int month, int day) {
StringBuilder builder = new StringBuilder();
builder.append(day).append("-")
.append(month).append("-")
.append(year);
String text= builder.toString();
FragmentManager fragmanager = getSupportFragmentManager();
if(fragmanager.findFragmentByTag("fromdatePicker") != null) {
Log.d(TAG, "got here" + text);
fromdate.setText(text);
}
// if(view.getTag() == "todatePicker") {
if(fragmanager.findFragmentByTag("todatePicker") != null) {
todate.setText(text);
}
that way you can use the same dateListener for multiple calls and set the date appropriately based on the tag that was passed when calling show on the dialog.
Use below code of DatePicker Dialog.
private int mYear;
private int mMonth;
private int mDay;
Calendar cal4DatePicker = Calendar.getInstance();
Button btnDOB=findviewbyId(R.id.btndob);
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
cal4DatePicker.set(Calendar.YEAR, mYear);
cal4DatePicker.set(Calendar.MONTH, mMonth);
cal4DatePicker.set(Calendar.DAY_OF_MONTH, mDay);
btnDOB.setText(new StringBuilder()
.append(mDay).append("-").append(mMonth).append("-").append(mYear).append(" "));
}
};
on btnDOB you need to set click listner to show this DatePicker Dialog.
I have try same thing with Time Picker only. You can try out and set same for date picker also.
package com.example.toolboxtest;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
public class MainActivity extends FragmentActivity implements OnClickListener {
Button testBtn;
EditText testET;
static final int TIME_DIALOG_ID = 0;
int mHour = 0;
int mMinute = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testBtn = (Button) findViewById(R.id.testBTn);
testET = (EditText) findViewById(R.id.testET);
testBtn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.testBTn:
showDialog(TIME_DIALOG_ID);
break;
}
}
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour=hourOfDay;
mMinute = minute;
// myPrefs = ImportantDateReminderActivity.this.getSharedPreferences("myPrefs",MODE_WORLD_WRITEABLE);
// prefsEditor = myPrefs.edit();
// prefsEditor.putInt("hour", mHour);
// prefsEditor.putInt("minute", mMinute);
// prefsEditor.putString("a", a);
// prefsEditor.commit();
if(mHour==12){
//reminderSetTime.setText(new StringBuilder().append("12").append(":").append((minute)+" PM"));
testET.setText(mHour+":"+mMinute+" "+"PM");
}
else
updateTimeDisplay();
}
};
private void updateTimeDisplay() {
try {
Format formatter;
SimpleDateFormat df = new SimpleDateFormat("hh:mm");
Date d = df.parse(mHour + ":" + mMinute);
Calendar gc = new GregorianCalendar();
gc.setTime(d);
//gc.add(Calendar.HOUR, 0);
Date d2 = gc.getTime();
formatter = new SimpleDateFormat("hh:mm a");
String time = formatter.format(d2);
System.out.println("The TIME is: "+time);
testET.setText(time);
String hour = new SimpleDateFormat("hh").format(d2);
String minute = new SimpleDateFormat("mm").format(d2);
String a = new SimpleDateFormat("a").format(d2);
System.out.println("The Hour is: "+hour+ " "+minute+ " " +a);
/*myPrefs = this.getSharedPreferences("myPrefs",MODE_WORLD_WRITEABLE);
prefsEditor = myPrefs.edit();
prefsEditor.putInt("hour", Integer.parseInt(hour));
prefsEditor.putInt("minute", Integer.parseInt(minute));
prefsEditor.putString("a", a);
prefsEditor.putString("complateTime", time);
prefsEditor.commit();*/
//addTwoMonthNotification();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,mTimeSetListener, mHour, mMinute, false);
}
return null;
}
}
Hope it will help you.
Please let me know if there is any issue.

android-Intent and OnClickListener

Brand new to android and facing a weird problem.Check out the code below
FirstActivity.java:
package experiment.on.it;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FirstActivity extends Activity implements Button.OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button timeDatePicker = (Button) findViewById(R.id.timeDatePickerBtn);
Button customSpinner = (Button) findViewById(R.id.spinnerBtn);
timeDatePicker.setOnClickListener(this);
customSpinner.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.timeDatePickerBtn:
startActivity(new Intent(this, TimeDatePicker.class));
case R.id.spinnerBtn:
startActivity(new Intent(this, CustomSpinner.class));
}
}
}
As I/you expected that by clicking on the two buttons i.e.
timeDatePicker
customSpinner
a new Activity will starts (TimeDatePicker and CustomSpinner respectively).
Our expectation is correct. But the problem i'm facing that when i click on the timeDatePicker the second activity (CustomSpinner) starts. But if i press the emulator's back button (i.e. the device back button) the first activity(TimeDatePicker) appears. I cant find any keyword to describe this kind of problem. So writing this boring question. Any help will be greatly appreciated from a beginner.(...And i think the answer will be pretty easy and small, which i couldnt get. :-P) The Activities code are given below.
TimeDatePicker.java:
package experiment.on.it;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class TimeDatePicker extends Activity {
private TextView mDateDisplay;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
private TextView mTimeDisplay;
private Button mPickTime;
private int mhour;
private int mminute;
static final int TIME_DIALOG_ID = 3;
static final int DATE_DIALOG_ID = 2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timedatepicker);
mDateDisplay = (TextView) findViewById(R.id.date);
mPickDate = (Button) findViewById(R.id.datepicker);
mTimeDisplay = (TextView) findViewById(R.id.time);
mPickTime = (Button) findViewById(R.id.timepicker);
// Pick time's click event listener
mPickTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(TIME_DIALOG_ID);
}
});
// PickDate's click event listener
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
mhour = c.get(Calendar.HOUR_OF_DAY);
mminute = c.get(Calendar.MINUTE);
}
// -------------------------------------------update
// date----------------------------------------//
private void updateDate() {
mDateDisplay.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mDay).append("/").append(mMonth + 1).append("/")
.append(mYear).append(" "));
showDialog(TIME_DIALOG_ID);
}
// -------------------------------------------update
// time----------------------------------------//
public void updatetime() {
mTimeDisplay.setText(new StringBuilder().append(pad(mhour)).append(":")
.append(pad(mminute)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
// Datepicker dialog generation
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
};
// Timepicker dialog generation
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mhour = hourOfDay;
mminute = minute;
updatetime();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
mDay);
case TIME_DIALOG_ID:
return new TimePickerDialog(this, mTimeSetListener, mhour, mminute,
true);
}
return null;
}
}
CustomSpinner.java:
package experiment.on.it;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class CustomSpinner extends Activity {
String[] items = { "this", "is", "a", "really", "really2", "really3",
"really4", "really5", "silly", "list" };
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.spinnerlayout);
Spinner spin =(Spinner)findViewById(R.id.sPinner);
ArrayAdapter adapter = new ArrayAdapter(this,R.layout.radio,R.id.txt,items);
spin.setAdapter(adapter);
}
}
The problem can be solved putting break in every case of the switch
public void onClick(View v) {
switch (v.getId()) {
case R.id.timeDatePickerBtn:
startActivity(new Intent(this, TimeDatePicker.class));
break;
case R.id.spinnerBtn:
startActivity(new Intent(this, CustomSpinner.class));
break;
}
}
try this.
You are missing break; statement in your switch case block.
So, thought the first activity starts and is in your backstack, it is immediately pushed down by the second one due to the missing break and the back button behaves as it should and return you to the the first one.
I think, you missed 'break' in switch~case.
You're missing break in your switch case, along with default. Since your switch case is taking the value of the spinner class, when you end the spinner class by pressing back button, the time-date picker class pops up.

Categories

Resources