I wrote a custom datepicker for android for adding date of birth. Code is as given below:
layout.xml:
<!--Date of Birth Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/dob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Date of Birth"
android:onClick="showDatePicker"/>
</android.support.design.widget.TextInputLayout>
MainActivity.java:
package com.emc.kulkaa.dellcsrmate;
import android.app.DialogFragment;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import org.w3c.dom.Text;
public class RegistrationActivity extends AppCompatActivity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
textView = (TextView) findViewById(R.id.link_login);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(RegistrationActivity.this, LoginActivity.class);
startActivity(intent);
}
});
}
public void showDatePicker(View v) {
DialogFragment newFragment = new MyDatePickerFragment();
newFragment.show(getFragmentManager(), "Date Picker");
}
}
Here is date fragment:
package com.emc.kulkaa.dellcsrmate;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.Toast;
import java.util.Calendar;
/**
* Created by kulkaa on 1/18/2018.
*/
public class MyDatePickerFragment extends DialogFragment {
#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(), dateSetListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener dateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int month, int day) {
Toast.makeText(getActivity(), "selected date is " + view.getYear() +
" / " + (view.getMonth() + 1) +
" / " + view.getDayOfMonth(), Toast.LENGTH_SHORT).show();
}
};
}
Above code works successfully. Value selected in custom datepicker appears in Toast successfully.
Now I want selected value to appear in EditText instead of appearing in toast. How can I do it by modifying fragment code?
For simple write this code onDate selected
((TextView) getActivity().findViewById(R.id.link_login)).setText("date");
so your code looks
public void onDateSet(DatePicker view, int year, int month, int day) {
Toast.makeText(getActivity(), "selected date is " + view.getYear() +
" / " + (view.getMonth() + 1) +
" / " + view.getDayOfMonth(), Toast.LENGTH_SHORT).show();
String date ="selected date is " + view.getYear() +
" / " + (view.getMonth() + 1) +
" / " + view.getDayOfMonth();
((TextView) getActivity().findViewById(R.id.link_login)).setText(date);
}
Related
I tried to modify this time picker I found here on stackoverflow and placed it in a dialog in my application. When I try to pick the time the result is not what I setted but it is the time of the device, so the time isn't set well. The function TimeSetting is used to call the time picker. I tryed to make it start from zero and take the right time but with no result. Can someone help me find out where the error is?
here is the ExampleDialog.java file:
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDialogFragment;
import com.ikovac.timepickerwithseconds.MyTimePickerDialog;
import com.ikovac.timepickerwithseconds.TimePicker;
import java.util.Calendar;
public class ExampleDialog extends AppCompatDialogFragment {
private EditText textInputNome;
private ExampleDialogListener listener;
private Button positiveButton;
private TextView text_view_timesec;
private Button SetTimeBTN;
private String nome = null;
private int timeInSeconds=-1;
private int hourOfDay;
private int minute;
private int seconds;
/*for MainActivity*/
public interface ExampleDialogListener {
boolean applyProgram(String nome);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
textInputNome = view.findViewById(R.id.tiCrea);
SetTimeBTN=view.findViewById(R.id.btn_SetTime);
text_view_timesec=view.findViewById(R.id.textView3);
textInputNome.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
TimeSetting();
}
#SuppressLint("SetTextI18n")
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
nome =textInputNome.getText().toString().trim();
TimeSetting();
}
#Override
public void afterTextChanged(Editable s) {
TimeSetting();
}
});
builder.setView(view);
builder.setTitle("Nome programma");
builder.setNegativeButton("delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setPositiveButton("create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nome = textInputNome.getText().toString().trim();
listener.applyProgram(nome);
}
});
Dialog dialog = builder.create();
return dialog;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
listener = (ExampleDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
"must implement ExampleDialogListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public void onStart() {
super.onStart();
AlertDialog d = (AlertDialog) getDialog();
if (d != null ) {
positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setEnabled(false);
}
}
private void TimeSetting(){
SetTimeBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Btn clicked", Toast.LENGTH_SHORT).show();
Calendar c = Calendar.getInstance();
MyTimePickerDialog mTimePicker = new MyTimePickerDialog(getContext(), new MyTimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute, int seconds) {
SetTimeBTN.setText(getString(R.string.time) + String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute) + ":" + String.format("%02d", seconds));
}
}, hourOfDay=c.get(Calendar.HOUR_OF_DAY), minute=c.get(Calendar.MINUTE), seconds=c.get(Calendar.SECOND), true);
timeInSeconds = ((hourOfDay * 60 * 60) + (minute * 60) + seconds);
text_view_timesec.setText("hh=" + hourOfDay + " mm=" + minute + " ss=" + seconds + " time tot=" + timeInSeconds);
positiveButton.setEnabled(!nome.isEmpty() && timeInSeconds > 0);
mTimePicker.show();
}
});
}
}
Here is the xml of the dialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/time_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/tiCrea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/name"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/btn_SetTime"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:text="#string/clickToSetTime"
android:textAlignment="viewStart"
android:gravity="start" />
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="here is the time setted from the timepkr" />
</LinearLayout>
in onCreate method change this two lines
final LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
to
final LinearLayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, (ViewGroup)R.id.time_view");//here the id of the root LinearLayout in the XMl File layout_dialog.
I have created two activity one for registration details and another one for showing the value user has entered. But when I tried to get the value of radiobutton from the radiogroup selected. It doesn't show any error but when I debug and run in my phone.
And clicked the signup button
It show app stopped working start again message
My MainActivity.java :
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
Button signUpButton,signInButton;
TextView userTimeJoining, dateOfBirth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = findViewById(R.id.signinbutton);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
signUpButton = findViewById(R.id.signupbutton);
signUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoRegAct = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(gotoRegAct);
}
});
}
}
My RegistrationActivity.java :
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
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.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class RegistrationActivity extends AppCompatActivity {
String courseList[] = {"Java","Python", "Android", "Kotlin"};
Button submitButton;
EditText nameOfUser, userGmail, userName, userPassword;
TextView userDateOfBirth, userTimeOfJoining;
Spinner mySpinnerForCourse;
RadioGroup genderSelected;
RadioButton selectedRadiobutton;
String setTime;
String setDate;
String setGender=" ";
int itemNoSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
submitButton = findViewById(R.id.submitButton);
nameOfUser = findViewById(R.id.nameofuser);
userGmail = findViewById(R.id.usergmail);
userName = findViewById(R.id.username);
userPassword = findViewById(R.id.userpassword);
userDateOfBirth = findViewById(R.id.userdateofbirth);
userTimeOfJoining = findViewById(R.id.usertimeofjoining);
mySpinnerForCourse = findViewById(R.id.usercourse);
genderSelected = findViewById(R.id.usergender);
//This is the code which is not working
int selectedRadioButtonId = genderSelected.getCheckedRadioButtonId();
selectedRadiobutton = (RadioButton) findViewById(selectedRadioButtonId);
setGender = selectedRadiobutton.getText().toString();
ArrayAdapter<String> arrayAdapterForCourse = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item,courseList);
mySpinnerForCourse.setAdapter(arrayAdapterForCourse);
mySpinnerForCourse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
itemNoSelected = i;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
userTimeOfJoining.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
int hh = calendar.get(Calendar.HOUR);
int mm = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(RegistrationActivity.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
setTime = i+" : "+i1;
userTimeOfJoining.setText(setTime);
}
},
hh, mm, false);
timePickerDialog.show();
}
});
userDateOfBirth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
int dd = calendar.get(Calendar.DAY_OF_MONTH);
int mm = calendar.get(Calendar.MONTH);
int yy = calendar.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(RegistrationActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
setDate = i2+" / "+i1+" / "+i;
userDateOfBirth.setText(setDate);
}
}, yy, mm, dd);
datePickerDialog.show();
}
});
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoShowInfo = new Intent(RegistrationActivity.this, ShowInfo.class);
Bundle bundleforenteredvalue = new Bundle();
bundleforenteredvalue.putString("enteredname",nameOfUser.getText().toString());
bundleforenteredvalue.putString("enteredgmail",userGmail.getText().toString());
bundleforenteredvalue.putString("enteredusername",userName.getText().toString());
bundleforenteredvalue.putString("enteredpassword",userPassword.getText().toString());
bundleforenteredvalue.putString("dateselected",setDate);
bundleforenteredvalue.putString("timeselected",setTime);
bundleforenteredvalue.putString("genderselected",setGender);
bundleforenteredvalue.putString("courseselected",courseList[itemNoSelected]);
gotoShowInfo.putExtras(bundleforenteredvalue);
startActivity(gotoShowInfo);
}
});
}
}
My ShowInfo.java :
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ShowInfo extends AppCompatActivity {
TextView nameOfUserEntered, usernameEntered, passwordEntered,gmailEntered, genderSelected, courseSelected, dateOFJoinSelected, timeOfJoinSelected;
Button signInButtonAgain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_info);
Bundle getValue = getIntent().getExtras();
String getnameentered = getValue.getString("enteredname");
String getenteredGmail = getValue.getString("enteredgmail");
String getenteredUsername = getValue.getString("enteredusername");
String getenteredPassword = getValue.getString("enteredpassword");
String getdateSelected = getValue.getString("dateselected");
String gettimeSelected = getValue.getString("timeselected");
String getgenderSelected = getValue.getString("genderselected");
String getcourseSelected = getValue.getString("courseselected");
nameOfUserEntered = findViewById(R.id.nameofuserentered);
usernameEntered = findViewById(R.id.usernameentered);
passwordEntered = findViewById(R.id.passwordentered);
gmailEntered = findViewById(R.id.gmailentered);
genderSelected = findViewById(R.id.genderselected);
courseSelected = findViewById(R.id.courseselected);
dateOFJoinSelected = findViewById(R.id.dateofjoinselected);
timeOfJoinSelected = findViewById(R.id.timeofjoinselected);
signInButtonAgain = findViewById(R.id.signinbuttonagain);
nameOfUserEntered.setText("Welcome "+ getnameentered);
usernameEntered.setText("Your username is "+getenteredUsername);
passwordEntered.setText("Your password is "+getenteredPassword);
gmailEntered.setText("Your gmail is "+getenteredGmail);
genderSelected.setText("Your gender is the "+getgenderSelected);
courseSelected.setText("You selected for the "+getcourseSelected+" Course");
dateOFJoinSelected.setText("your joinig date is "+getdateSelected);
timeOfJoinSelected.setText("Time of your duty is starts from "+gettimeSelected);
signInButtonAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoMainmenu = new Intent(ShowInfo.this, MainActivity.class);
startActivity(gotoMainmenu);
}
});
}
}
In registration activity I've added a comment by only that code my app show the error message. If I remove the radiobutton code and the getString String. It works properly and then it doesn't show app stopped working message.
So why I'm not able to pass the value of the radiobutton string from one activity to another.
Try this may be your radiobutton id returns -1 if no values are selected in radio group.
int chk_gender = rg_gender.getCheckedRadioButtonId();
if (chk_gender != -1) {
Gender = ((RadioButton)findViewById(chk_gender)).getText().toString();
}
else
{
Gender = "";
}
EDITED
rg_gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId != -1) {
Gender = ((RadioButton)findViewById(checkedId)).getText().toString();
}
else
{
Gender = "";
}
}
});
In your xml layout ,did you checked TRUE any radio button ?
You should get the selected radio button value on click of submit button.It will update your setGender string with most recent value.
for your app crash , Please post your logcat error while app crash.
I used this question to get the timepicker when clicking on editext.
Please note that I am putting the code in a fragment.
What i've changed is the following:
Added : Context ctx; to the settime.java
On the line:
SetTime fromTime = new SetTime(chostime,this);
It is telling me : the constructor SetTime(editText, AppointFragment) is not defined.
I’ve tried to change it into :
SetTime fromTime = new SetTime(chostime,getActivity());
When trying to run the application gice me the following error
12-30 18:03:55.120: E/AndroidRuntime(1376): java.lang.NullPointerException
Here is the code :
AppointFragment.java
package com.example.appointapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
public class AppointFragment extends Fragment{
private static final String TAG = "AppoinFragment";
EditText chosdate, chostime;
private Appointment mappointment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mappointment= new Appointment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_appoint, parent, false);
chosdate = (EditText)v.findViewById(R.id.datea_text);
chostime = (EditText)v.findViewById(R.id.timea_text);
SetTime fromTime = new SetTime(chostime,this);
chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DialogFragment datePickerFragment = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Log.d(TAG, "onDateSet");
Calendar c = Calendar.getInstance();
c.set(year, month, day);
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
chosdate.setText(sdf.format(c.getTime()));
chosdate.requestFocus();
}
};
datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
}
});
return v;
}
}
SetTime.java
package com.example.appointapp;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;
class SetTime implements OnFocusChangeListener, OnTimeSetListener {
private EditText editText;
private Calendar myCalendar;
Context ctx;
public SetTime(EditText editText, Context ctx){
this.editText = editText;
this.editText.setOnFocusChangeListener(this);
this.myCalendar = Calendar.getInstance();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
int minute = myCalendar.get(Calendar.MINUTE);
new TimePickerDialog(ctx, this, hour, minute, true).show();
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
this.editText.setText( hourOfDay + ":" + minute);
}
}
First override onActivityCreated() in AppointFragment and then use the getActivity() to create SetTime object.
private SetTime fromTime;
private EditText chosdate, chostime;
...
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
fromTime = new SetTime(chostime,getActivity());
}
The complete code for setting the time using Fragments is below. You can use the same approach for setting the date too.
MainActivity.java
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a new Fragment to be placed in the activity layout
ChildFragment firstFragment = new ChildFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
//firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.frameLayout, firstFragment).commit();
}
ChildFragment.java (For displaying EditTexts)
public class ChildFragment extends Fragment implements View.OnClickListener, TimePickerFragment.Callback
{
private EditText editText;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.child_fragment, null, false);
editText = (EditText) view.findViewById(R.id.time_edit_text);
editText.setOnClickListener(this);
return view;
}
#Override
public void onClick(View view)
{
if(view == editText)
{
TimePickerFragment dialog = new TimePickerFragment();
dialog.setTargetFragment(this, 1); //request code
dialog.show(getFragmentManager(),"dialog");
}
}
#Override
public void onTimeSelected(String time)
{
editText.setText(time);
}
}
TimePickerFragment.java
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
public interface Callback
{
public void onTimeSelected(String time);
}
private Callback timeCallback;
#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);
timeCallback = (Callback) getTargetFragment();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
timeCallback.onTimeSelected(hourOfDay + ":" + minute + ":00");
}
}
activity_main.xml
<?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">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frameLayout"/>
</RelativeLayout>
child_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/time_edit_text"/>
</LinearLayout>
Here is the code :
AppointFragment.java
package com.example.appointapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
public class AppointFragment extends Fragment{
private static final String TAG = "AppoinFragment";
EditText chosdate, chostime;
private Appointment mappointment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mappointment= new Appointment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_appoint, parent, false);
chosdate = (EditText)v.findViewById(R.id.datea_text);
chostime = (EditText)v.findViewById(R.id.timea_text);
SetTime fromTime = new SetTime(chostime,this);
chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DialogFragment datePickerFragment = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Log.d(TAG, "onDateSet");
Calendar c = Calendar.getInstance();
c.set(year, month, day);
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
chosdate.setText(sdf.format(c.getTime()));
chosdate.requestFocus();
}
};
datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
SetTime fromTime = new SetTime(chostime,getActivity());
}
}
SetTime.java
package com.example.appointapp;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;
class SetTime implements OnFocusChangeListener, OnTimeSetListener {
private EditText editText;
private Calendar myCalendar;
Context ctx;
public SetTime(EditText editText, Context ctx){
this.editText = editText;
this.editText.setOnFocusChangeListener(this);
this.myCalendar = Calendar.getInstance();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
int minute = myCalendar.get(Calendar.MINUTE);
new TimePickerDialog(ctx, this, hour, minute, true).show();
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
this.editText.setText( hourOfDay + ":" + minute);
}
}
SingleFragmentAcitivity.java
public abstract class SingleFragmentActivity extends FragmentActivity {
protected abstract Fragment createFragment();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
Appointactivity.java
package com.example.appointapp;
import android.support.v4.app.Fragment;
public class AppointActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
return new AppointFragment();
}
}
Fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/new_patient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_patient" />
<Button
android:id="#+id/new_appoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_appoint"/>
</LinearLayout>
Fragment_appoint.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/Patients_list"
android:layout_width="117dp"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/datea_text"
android:layout_width="143dp"
android:layout_height="wrap_content"
android:hint="#string/datea_text_hint" />
<EditText
android:id="#+id/timea_text"
android:layout_width="141dp"
android:layout_height="wrap_content"
android:hint="#string/timea_text_hint" />
<Button
android:id="#+id/savea_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/savea_button" />
</LinearLayout>
Thank you for ur help
i solved the issue using the following code in my fragment:
chostime.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
chostime.setText( selectedHour + ":" + selectedMinute);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
});
Thank you
I am using this method to read the date from the calendar and display it on the TextView but it only show me 25:10:2015 and it doesn't change when I choose another date. I wrote event to change the date but i don't know what is wrong:
package com.example.user.calendar;
import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
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 AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView datee=(TextView)findViewById(R.id.textView2);
final Calendar c=Calendar.getInstance();
final int year =c.get(Calendar.YEAR);
final int month =c.get(Calendar.MONTH);
final int day =c.get(Calendar.DAY_OF_MONTH);
datee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datepicker = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
datee.setText(" ");
datee.setText(year + ":" + month + ":" + day);
// dayyy=datee.getText().toString();
}
}, year, month, day);
datepicker.setTitle("select date");
datepicker.show();
}
});
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageButton ib;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ib = (ImageButton) findViewById(R.id.imageButton1);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
et = (EditText) findViewById(R.id.editText);
ib.setOnClickListener((View.OnClickListener) this);
}
#Override
public void onClick(View v) {
showDialog(0);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
}
};
}
try this I hope its work.
private DatePickerDialog.OnDateSetListener datePickerListener
= new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into textview
tvDisplayDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
// set selected date into datepicker also
dpResult.init(year, month, day, null);
}
};
When you 'setText' you are using the variables from 'Calendar.getInstance();' which set those variables according to the current day, month, and year. Instead you should be using the variables that are set by the datePicker.
Instead of:
datee.setText(year + ":" + month + ":" + day);
use this:
datee.setText(year + ":" + monthOfYear + ":" + dayOfMonth);
Also, the month returned by Calendar.Month is off by one (10 instead of 11) because the Java Calendar goes from 0 to 11. So you have to add 1 to the month to get the correct number for the current month. But the month value (dayOfMonth) returned by the datePicker should be correct by default.
How do I make this time picker set the edittext box with the time that the TimePickerDialog set?
package com.example.d;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
int hour,min;
//static final int TIME_DIALOG_ID=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etOne = (EditText) findViewById(R.id.editText1);
etOne.setOnClickListener(new EditText.OnClickListener() {
public void onClick(View v) {
//Do stuff here
Calendar c=Calendar.getInstance();
int hour=c.get(Calendar.HOUR);
int min=c.get(Calendar.MINUTE);
showTimeDialog(v, hour, min);
}
});
}
OnTimeSetListener timeSetListener;
public void showTimeDialog(View v, int hour, int min)
{
(new TimePickerDialog(this, timeSetListener, hour, min, true)).show();
//how do I make this time picker set the edittext box with the time that the TimePickerDialog set
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:width="320px">
<requestFocus />
</EditText>
</RelativeLayout>
public class MainActivity extends Activity {
int hour = -1, min = -1;
static final int TIME_DIALOG_ID = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etOne = (EditText) findViewById(R.id.editText1);
etOne.setOnClickListener(new EditText.OnClickListener() {
public void onClick(View v) {
// Do stuff here
if (hour == -1 || min == -1) {
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR);
min = c.get(Calendar.MINUTE);
}
showTimeDialog(v, hour, min);
}
});
}
public void showTimeDialog(View v, int hour, int min) {
(new TimePickerDialog(MainActivity.this, timeSetListener, hour, min,
true)).show();
}
public TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour = hourOfDay;
min = minute;
EditText et = (EditText) findViewById(R.id.editText1);
et.setText(hour + " : " + min);
}
};
}
You can do it in onTimeSetListener like this
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
setTimeEditText.setText(hour + ":" + minute);
}
};
You have to creat an instance of OnTimeSetListener and in it's onTimeSet method you have the selected hour and minute.