Show method for DialogFragment not working in Android Version 2.3 - datepicker

I am using DatePicker and Time Picker in my Application but I am getting an error while using it.
See the Code Below :
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
{
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);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day)
{
tv_date_value.setText(String.valueOf(day) + "/" + String.valueOf(month + 1) + "/" + String.valueOf(year));
}
}
This is the Package I have imported after googling :
import android.support.v4.app.DialogFragment;
The Problem occurs when I try to create an object of the DialogFragment and use the show() Method, it says:
The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentManager, String)
Here is the Code for that:
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(myActivity.getFragmentManager(), "datePicker");
I am getting Error on show() method.
I am using this Date and Time Picker in a Class and not an Activity, So I am giving a reference of that Main Activity Class named : "myActivity".
Can anybody Please help me here???
Thanks,
David.

try using getActivity().getSupportFragmentManager()

use the code below:
android.app.FragmentManager fragmentManager=getActivity().getFragmentManager();
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(fragmentManager,"datepicker");

Related

the date picker the date does not change in the date text field

I have an issue with the date Picker in wicket and need help please:
Here is the code when was everything okay :
private void addToDateFieldContainer() {
DateField field = new ReservationDateField("validToDate");
WebMarkupContainer container = new WebMarkupContainer("validToDateContainer");
container.add(field);
container.setVisible(configParams.isShowReservationToDate());
add(container);
}
but I had a problem that the datetext field had a different id from the parent component, so I added some code
private void addToDateFieldContainer() {
DateField field = new ReservationDateField("validToDate"){
#Override
protected DateTextField newDateTextField(String id, PropertyModel dateFieldModel) {
DateTextField dateTextField = DateTextField.forShortStyle(id, dateFieldModel);
dateTextField.setMarkupId(this.getMarkupId());
return dateTextField;
}
};
WebMarkupContainer container = new WebMarkupContainer("validToDateContainer");
container.add(field);
container.setVisible(configParams.isShowReservationToDate());
add(container);
}
now the date text id has the same id for the parent component, but it comes to a different problem :
when I press on the date picker the date does not change in the date text field
here is an image about for the date picker
Does anyone have a clue how I can overcome this issue?

Why is onChanged() not called when observing LiveData

This question is a follow up to this problem here: How to make retrofit API call using ViewModel and LiveData
The mistakes 1 and 2 highlighted in that post's response have been fixed. For mistake 3, I haven't yet moved the API call to a repository, but I will once the code start working properly.
So I'm trying to make an API call using Retrofit, using MVVM with LiveData and ViewModel. The API call (which currently is in the ViewModel), is working properly, but the changes is not being picked up by the Observer in the Activity.
I've setup my ViewModel observer as follow:
public class PopularGamesActivity extends AppCompatActivity {
private static final String igdbBaseUrl = "https://api-endpoint.igdb.com/";
private static final String FIELDS = "id,name,genres,cover,popularity";
private static final String ORDER = "popularity:desc";
private static final int LIMIT = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_popular_games);
PopularGamesViewModel popViewModel = ViewModelProviders.of(this).get(PopularGamesViewModel.class);
popViewModel.getGameList().observe(this, new Observer<List<Game>>() {
#Override
public void onChanged(#Nullable List<Game> gameList) {
String firstName = gameList.get(0).getName();
Timber.d(firstName);
}
And my ViewModel code is as follow:
public class PopularGamesViewModel extends AndroidViewModel {
private static final String igdbBaseUrl = "https://api-endpoint.igdb.com/";
private static final String FIELDS = "id,name,genres,cover,popularity";
private static final String ORDER = "popularity:desc";
private static final int LIMIT = 30;
public PopularGamesViewModel(#NonNull Application application) {
super(application);
}
public LiveData<List<Game>> getGameList() {
final MutableLiveData<List<Game>> gameList = new MutableLiveData<>();
// Create the retrofit builder
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(igdbBaseUrl)
.addConverterFactory(GsonConverterFactory.create());
// Build retrofit
Retrofit retrofit = builder.build();
// Create the retrofit client
RetrofitClient client = retrofit.create(RetrofitClient.class);
Call<List<Game>> call = client.getGame(FIELDS,
ORDER,
LIMIT);
call.enqueue(new Callback<List<Game>>() {
#Override
public void onResponse(Call<List<Game>> call, Response<List<Game>> response) {
Timber.d("api call sucesss");
if (response.body() != null) {
Timber.d("First game: " + response.body().get(0).getName());
gameList.setValue(response.body());
}
}
#Override
public void onFailure(Call<List<Game>> call, Throwable t) {
Timber.d("api call failed");
}
});
return gameList;
}
}
When I run the code, the onResponse in the ViewModel class will output the correct response from the API call, so the call is working properly. But the onChanged() in the PopularGamesActivity class will never get called. Can someone shed some light on what I'm doing wrong? Thank you!
Ok, so this turned out to be a weird android studio bug. I was initially running the code on my real nexus 4 device, and the onChange never gets called. However, after running it on an emulated device, it started working immediately. And now, it's working on my real device too.
I don't know the actual reason behind it, but if anyone in the future run into a problem where onChange won't get called, try switching device/emulators.
Cheers.
I debug the code on a device and have the same problem.
M'n solution was simply activate the device screen.
The screensaver was the problem..

why esper_ext timed does not filter out old entries

I need help with understanding of the win_ext window in Esper (CEP). I'm wondering why older (first 2) events still popup on the update-method even though they have been "expired"
public class MyCepTest {
public static void main(String...args) throws Exception{
System.out.println("starting");
MyCepTest ceptest = new MyCepTest();
ceptest.execute();
System.out.println("end");
}
public void execute() throws Exception{
Configuration config = new Configuration();
config.addEventType(MyPojo.class);
EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(config);
EPAdministrator admin = epService.getEPAdministrator();
EPStatement x1 = admin.createEPL(win);
EPStatement x2 = admin.createEPL(win2);
x1.setSubscriber(this);
x2.setSubscriber(this);
EPRuntime runtime = epService.getEPRuntime();
ArrayList<MyPojo> staffToSendToCep = new ArrayList<MyPojo>();
staffToSendToCep.add(new MyPojo(1, new Date(1490615719497L)));
staffToSendToCep.add(new MyPojo(2, new Date(1490615929497L)));
for(MyPojo pojo : staffToSendToCep){
runtime.sendEvent(pojo);
}
Thread.sleep(500);
System.out.println("round 2...");//why two first Pojos are still found? Shouldn't ext_timed(pojoTime.time, 300 seconds) rule them out?
staffToSendToCep.add(new MyPojo(3, new Date(1490616949497L)));
for(MyPojo pojo : staffToSendToCep){
runtime.sendEvent(pojo);
}
}
public void update(Map<String,Object> map){
System.out.println(map);
}
public static String win = "create window fiveMinuteStuff.win:ext_timed(pojoTime.time, 300 seconds)(pojoId int, pojoTime java.util.Date)";
public static String win2 = "insert into fiveMinuteStuff select pojoId,pojoTime from MyPojo";
}
class MyPojo{
int pojoId;
Date pojoTime;
MyPojo(int pojoId, Date date){
this.pojoId = pojoId;
this.pojoTime = date;
}
public int getPojoId(){
return pojoId;
}
public Date getPojoTime(){
return pojoTime;
}
public String toString(){
return pojoId+"#"+pojoTime;
}
}
I've been puzzled with this for a while and help would be greatly appreciated
See the processing model in docs. http://espertech.com/esper/release-6.0.1/esper-reference/html/processingmodel.html
All incoming insert-stream events are delivered to listeners and subscribers. regardless of your window. A window, if one is in the query at all, defines the subsets of events to consider and therefore defines what gets aggregated, pattern-matched or is available for iteration. Try "select * from MyPojo" for reference. My advice to read up on external time, see http://espertech.com/esper/release-6.0.1/esper-reference/html/api.html#api-controlling-time
Usually when you want "external time window" you want event time to drive engine time.

Javafx Datepicker validation

we tried to validate a javafx datepicker. So we use:
if (fromDatePicker.getValue() == null) {
sb.append("No valid from date!\n");
} else {
System.out.println(fromDatePicker.getValue().toString());
if (!DateUtil
.validEnglishDate(fromDatePicker.getValue().toString())) {
sb.append("No valid from date. Use the format yyyy-MM-dd.\n");
}
}
But at the moment it's impossible to get an invalid Date with the datepicker, because all invalid date's are changed to the start value.
So we asked us is it possible to get an invalid Date with the javafx datepicker?
***** EDIT *****
Example: we have the following datepicker:
DatePicker[2015-05-12]
now we entered "fjdfk" in the DatePicker so we have:
DatePicker[fjdfk]
on save the data's the datepicker changes automatical to DatePicker[2015-05-12]
You could use the DatePicker#setConverter(StringConverter<LocalDate>) to catch any parse exception and warn the user in consequence. Here is a sample :
public class SecureLocalDateStringConverter extends StringConverter<LocalDate> {
/**
* The date pattern that is used for conversion. Change as you wish.
*/
private static final String DATE_PATTERN = "dd/MM/yyyy";
/**
* The date formatter.
*/
public static final DateTimeFormatter DATE_FORMATTER =
DateTimeFormatter.ofPattern(DATE_PATTERN);
private boolean hasParseError = false;
public boolean hasParseError(){
return hasParseError;
}
#Override
public String toString(LocalDate localDate) {
return DATE_FORMATTER.format(localDate);
}
#Override
public LocalDate fromString(String formattedString) {
try {
LocalDate date=LocalDate.from(DATE_FORMATTER.parse(formattedString));
hasParseError=false;
return date;
} catch (DateTimeParseException parseExc){
hasParseError=true;
return null;
}
}
}
From your control, you'll just have to call converter#hasParseError(), converter being the one you set with DatePicker#setConverter(StringConverter<LocalDate>)

Junit with new Date()

What would the junit test be when i have the following method:
#Override
public void saveLastSuccesfullLogin(final User user) {
gebruiker.setLastLogin(new Date());
storeUser(user);
}
submethode storeUser:
#Override
public void storeUser(final User user) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.merge(user);
em.getTransaction().commit();
em.close();
}
The problem i have is the date, being set for the entity user and then stored. Im using junit and easymock.
Try pulling the new Date() into a method with default access specifier like below
#Override
public void saveLastSuccesfullLogin(final User user) {
gebruiker.setLastLogin(getDate());
storeUser(user);
}
Date getDate() {
return new Date();
}
In your test class override the class as below using a mock or stubbed date.
<ClassUnderTest> classUnderTest = new <ClassUnderTest> () {
#Override
Date getDate() {
return mockDate;
}
}
In this way you can assert the date value easily as it is going to be stubbed out.
What's the problem with the Date? That you don't know what it is to assert later? A few alternatives:
Pass the date into the method
Create a factory to get the current date/time so you can mock it out
Assert the date within a threshold of correctness
There is also a more "enterprise" approach that may be used where Dependency Injection is available (like in EJB, Spring etc.).
You can define an interface, for example TimeService and add e method that returns the current date.
public interface TimeService {
Date getCurrentDate();
}
You can implement this to return new Date() and use it like this:
gebruiker.setLastLogin(timeService.getCurrentTime());
This will obviously be very easy to test because you can mock the TimeService. Using EasyMock (just an example), this might be:
Date relevantDateForTest = ...
expect(timeService.getCurrentTime()).andReturn(relevantDateForTest);
replay(timeService);
Using the TimeService throughout the entire code and never using new Date() is a pretty good practice and has other advantages as well. I found it helpful in a number of occasions, including manual functional testing of features that would activate in the future. Going even further, the system time may be retrieved from an external system thus making it consistent across clusters etc.
You can also create a getDate method, and a date static var:
private static Date thisDate = null;
#Override
public void saveLastSuccesfullLogin(final User user) {
gebruiker.setLastLogin(getDate());
storeUser(user);
}
public Date getDate() {
if(thisDate != null) return thisDate;
return new Date();
}
public void setDate(Date newDate) {
thisDate = newDate;
}
Then in your test method, you can go ahead and call setDate to control what date you will get.