android datepickerfragment transfer information to main activity - android

I'm new in programming and android. I'm having problem with a datePickerfragment. Error when implementing DatePickerFragment.OnFragmentInteractionListener on mainActivity, it says that "Class MainActivity must either be declared abstract or implement abstract method 'returnDate(String)' in 'OnFragmentInteractionListener'."
I used the datePicker as shown in http://developer.android.com/guide/topics/ui/controls/pickers.html.
The datePicker works but I want to transfer the value selected to mainActivity and I took some tips in this other post: How to transfer the formatted date string from my DatePickerFragment?.
I don't really know what I'm missing. I would also like to know if its possible to transfer de Date value instead of a String value. I wanted to manipulate the Date in mainActivity. Hope someone can help me. Here is my code:
package com.example.android.datepickertest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends FragmentActivity
implements DatePickerFragment.OnFragmentInteractionListener
{
private TextView dataSelecionada;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataSelecionada = (TextView)findViewById(R.id.data_selecionada);
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
#Override
public void setTextDate (int year, int month, int day) {
TextView displayDataSelecionada = (TextView) findViewById(R.id.data_selecionada);
dataSelecionada.setText(day + "/" + month +"/" + year);
}
#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);
}
}
and datePickerFragment:n
package com.example.android.datepickertest;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link DatePickerFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link DatePickerFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
OnFragmentInteractionListener listener;
public interface OnFragmentInteractionListener {
public void returnDate(String date);
};
#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);
listener=(OnFragmentInteractionListener)getActivity();
// 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
Calendar c= Calendar.getInstance();
c.set(year,month,day);
SimpleDateFormat date = new SimpleDateFormat();
String dateSet = date.format(c.getTime());
if (listener !=null){
listener.returnDate(dateSet);
}
}
}

The error has the answer, when you implement an interface, you should implement all the methods in the interface.
In your case there is no method returndate in your mainactivity.
1.Create the method returnDate or if you use Android studio, just go to file MainActivity and put your cursor over 'public class MainActivity' then press Alt+Enter, the method ll be automatically created, and you ll the date in your mainactivity through this method.
If you need date instead of string change the argument of returndate method to Date, and remove that Simpledateformat instead use
new Date (c.getTime())

Related

How do I call my Date Picker from a button press?

I am trying to create an app that allows me to pick a date and a table is populated with appointments on that day. I am having troubles with getting the date picker to show.
I have taken a look at this https://developer.android.com/guide/topics/ui/controls/pickers and created a date picker from this code. I want to call that date picker from a button press found in the AddAppointmentActivity class.
Here is my Appointment class:
package com.example.dentdevils.ui.HomeLinks;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import com.example.dentdevils.R;
import com.example.dentdevils.ui.HomeActivity;
import java.util.Calendar;
public class AddAppointmentActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_appointment);
// Date label
TextView dateLabel = (TextView) findViewById(R.id.txtDateLabel);
// Date Picker Button Functionality
Button datePicker = (Button) findViewById(R.id.btnDatePicker);
datePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// Back Button Functionality
Button btnBack = (Button) findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchHomepage = new Intent(AddAppointmentActivity.this, HomeActivity.class);
startActivity(launchHomepage);
}
});
}
}
class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// Get date set by user and display appointments in table for the date chosen.
}
public void showDatePickerDialog() {
DialogFragment newFragment = new com.example.dentdevils.ui.HomeLinks.DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
}
I did have the classes in separate files but was testing different things hence why they are in the same file (I will move them back out again to separate files after I have managed to call the date picker).
My question is, how would I call the date picker dialog from the button press?
datePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
});
You don't need create an extra dialog fragment for date picker. Just create DatePickerDialog object and call show().
Example:
val calendar = Calendar.getInstance()
val dialog = DatePickerDialog(context,
DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
// TODO
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH))
dialog.show()

Android DatePicker and Button issues

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");
}
}

how can i check a time more than one time

I have a class that takes a time from a user by time picker ,the time picker action should be compared with current phone time ,when current phone time is same with which user set ,the app should trigger a media player called mediaplayer like an alarm .now the problem is I cant check the timepicker time with the current phone time more than one time .
import java.util.Calendar;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
public class Sabah2 extends Activity {
Button btn;
Intent i;
int hour,min;
static TimePicker picker;
private Handler hh;
private Runnable rr;
Calendar c = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sabah2);
final MediaPlayer mp = MediaPlayer.create(Sabah2.this, R.raw.salam);
picker = (TimePicker) findViewById(R.id.timePicker1);
btn = (Button) findViewById(R.id.sabah_save);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
hour=picker.getCurrentHour();
min=picker.getCurrentMinute();
Toast.makeText(getApplicationContext(), "The Alarm has been
Activated At "+hour+":"+min, Toast.LENGTH_SHORT).show();
}
});
if(hour==c.get(Calendar.HOUR)&&min==c.get(Calendar.MINUTE))
{
mp.start();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sabah2, menu);
return true;
}
}
You have to set the alarmanager for the time in the timepicker.If the time matches with current time it will trigger the alarm and play the mediaplayer .something like this
AlarmManager alarmanager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
TimePicker ti = (TimePicker) findViewById(R.id.time_alarm);
ti.setOnTimeChangedListener(new OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
selectedhour = hourOfDay;
selectedminute = minute;
count = 2;
}
});
now convert the selectedhour and selectedminute into millisecond and set it to alarmanager
alarmanager.set(AlarmManager.RTC_WAKEUP, time in millisec,pndingIntent) ;
You have to use a service to check for the time.In this service check your time with current time.This will be in background and thus will try to check the instance of time even when your ap is not running.

What would I use to grab a TextView from the MainActivity within a DialogFragment?

I'm writing a simple app that opens up a time picker dialog, asks for input, checks it against the system time, and tells you whether or not it is correct. However, I need to grab the TextView that displays whether it is true or false, and change it within the TimePickerFragment which is a DialogFragment. What should I do?
TimePickerFragment.java
package com.example.timechecker;
import java.util.Calendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
int hour;
int minutes;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minutes = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, 12, 00,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//Grab the Text View from the Main Activity
// MainActivity m = new MainActivity();
// m.grabText text = new m.grabText();
//Check if given Picker value is == to the system time, display whether or not it is so
if (hourOfDay == hour && minutes == minute) {
text.setText("You are correct!");
} else {
text.setText("You are incorrect!");
}
}
}
MainActivity.java
package com.example.timechecker;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Creates the dialog with the Time Picker
public void checkTime(View view) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
//Class to grab the Text View for the Dialog Fragment
public class grabText {
TextView text = (TextView) findViewById(R.id.whatTime);
//Uses a method to set the Text View text
public void setText(String string) {
text.setText(string);
}
}
}
When you call findViewById in any activity then i searches in activity layout only. therefore to get the TextView from a dialog you need a reference to that dialog and then you call dialog.findViewById(id_of_field) and this will give you desired TextView.
Hope this Helps
I recently did this, I was able to do this by making MainActivity.java the parent of my DialogFragment.
MainActivity.Java
Add this to MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
mActivity = this;
After, make it global here:
public class MainActivity extends Activity {
MainActivity mActivity;
DialogFragment
Add this to DialogFragment:
public void setParent(MainActivity parent) {
mParent = parent;
}
After, make it global here:
public class ClearDialogModern extends DialogFragment {
MainActivity mParent;
EDIT: Here's where you setParent. Put this in your MainActivity.java onCreate:
newDialogFragment = new DialogFragment();
newDialogFragment.setParent(mActivity);
How to use:
You can now use mParent to reference the MainActivity.java.

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.

Categories

Resources