How to disable CustomValidator for a specific scenario - java

I have a form which uses CustomValidator to check for non empty field whenever we try to Add a record (PARAMETER, VALUE)
I'm looking for a way to disable form validation when I'm trying to Delete (the user can delete an empty listGridRecord if he changes his mind and needs no more to add).
I'm using this custom validator:
CustomValidator validatorParameter = new CustomValidator() {
#Override
protected boolean condition(Object value) {
parameterName = (String) value;
if ((value == null || ((String) value).trim().isEmpty())) {
rowIsValidate = false;
return false;
} else {
rowIsValidate = true;
return true;
}
}
};
which I'm setting in an init() method this way:
parametersListGrid.getField(PARAMETER).setValidators(validatorParameter);
I tried setting a flag "noValidation" on true whenever I detect a click on Delete button and used it this way:
CustomValidator validatorParameter = new CustomValidator() {
#Override
protected boolean condition(Object value) {
parameterName = (String) value;
if (((value == null || ((String) value).trim().isEmpty())) && !noValidation){
rowIsValidate = false;
return false;
} else {
rowIsValidate = true;
return true;
}
}
};
but I figured out that this flag is set later on after the validation happened so
rowIsValidate stays false and we can't delete the empty record given the errors shown after validation;
Any idea on how to pass this validation step just in deletion scenario?

Call discardEdits(rowNum) before deleting a record.
Same question is asked on SmartClient Forums.

Related

How to optimalize if else statemants with many specifications

I am trying to create dynamic search based on fields send in request body.
I prepared many Specifications and in "summary specification" (which is called in method) I want to call them if field is different than null.
It works but the problem is I will never know which parameter will start creating condition so I had to add boolean parameter which resulted in the creation of many if else statements.
Code:
public Specification<ShapeEntity> conditionalSearch(ShapeParams shapeParams) {
Specification spec = null;
boolean isFirstParam = true;
if (shapeParams.getType() != null) {
if (isFirstParam) {
spec = Specification.where(isTypeEqual(shapeParams.getType()));
isFirstParam = false;
} else {
spec = spec.and(isTypeEqual(shapeParams.getType()));
}
}
if (shapeParams.getWidthTo() != null) {
if (isFirstParam) {
spec = Specification.where(isWidthLessThan(shapeParams.getWidthTo()));
isFirstParam = false;
} else {
spec = spec.and(isWidthLessThan(shapeParams.getWidthTo()));
}
}
if (shapeParams.getWidthFrom() != null) {
if (isFirstParam) {
spec = Specification.where(isWidthGreaterThan(shapeParams.getWidthTo()));
isFirstParam = false;
} else {
spec = spec.and(isWidthGreaterThan(shapeParams.getWidthTo()));
}
}
return spec;
}
Is there any way to optimalize it? Specification has to always start with ".where" as first, and next I can add other conditions and I would like to have even 10+ params
You can write some methods that receive some values to validate and return boolean.
boolean checkType(CustomObject type){
return type == null;
}
You can check the use of Optional, it maybe helps with some if blocks.
Optional.ofNullable(type).ifPresent(t -> /*some operations*/);
You can check if you can merge some conditions.
if (shapeParams.getType() != null && isFirstParam) {
//do something....
} else {
//do other....
}

How can i conditionally prevent a user from navigating to a different view/part in eclipse E4 RCP application?

I am trying to prevent a user from going to a different view/part in a perspective of eclipse E4 application.When i am trying to navigate to the same perspective and view,I am facing a stackOverflow exception due to recursively calling the showPart method by the framework.
NavigationHelper.showPerspective(CommonConstants.PERSPECTIVE1, getEclipseContext());
NavigationHelper.showPart(CommonConstants.VIEW1, getEclipseContext());
NavigationHelper.showPart(CommonConstants.VIEW2, getEclipseContext());
My showPart method lokks like this,
public static boolean showPart(String partId, IEclipseContext eclipseContext) {
logger.debug("showPart::STARTED::" + partId);
if (null == eclipseContext) {
eclipseContext = getEclipseContext();
}
if (Model.getInstance().hasDataChanged()) {
if (partId.equalsIgnoreCase(CommonConstants.VIEW1)
|| partId.equalsIgnoreCase(CommonConstants.VIEW2)) {
isNavigationSuccessful = true;
} else {
isNavigationSuccessful = false;
Navigation.showWarning();
}
}
if (isNavigationSuccessful) {
findPartAndActivate(partId, eclipseContext, true);
}
logger.debug("isNavigationSuccessful = " + isNavigationSuccessful);
logger.debug("showPart::END::" + partId);
return isNavigationSuccessful;
}
The findPartAndActivate looks like this
private static boolean findPartAndActivate(String partId, IEclipseContext eclipseContext, boolean giveFocus) {
MTrimmedWindow applicationWindow = ((MTrimmedWindow) ((MApplication) eclipseContext.get(MApplication.class))
.getChildren().get(0));
IEclipseContext currentContext = applicationWindow.getContext();
EPartService partService = currentContext.get(EPartService.class);
EModelService modelService = currentContext.get(EModelService.class);
MPart part = (MPart) modelService.find(partId, eclipseContext.get(MApplication.class).getChildren().get(0));
partService.activate(part, giveFocus);
return true;
}
The partDeactivated is invoked,once a user leaves from a part/View
public void partDeactivated(#Active MPart part) {
if (partInstance.getElementId() != part.getElementId()) {
return;
}
if (transactionButton != null && !transactionButton.isDisposed() && transactionButton.isEnabled()
&& isTransactionCompleted && NavigationHelper.getEditableViewInstance() != null && !partDeactivateFlag) {
doTransaction();
partDeactivateFlag = true;
}
if (Navigation.isPerspective()) {
if (EModel.getInstance().hasDataChanged()/*&& !Model.getInstance().isSwitchFlag()*/) {
System.out.println("Changes");
//Model.getInstance().setSwitchFlag(true);
//partDeactivateFlag = true;
NavigationHelper.showPerspective(CommonConstants.PERSPECTIVE1, getEclipseContext());
NavigationHelper.showPart(CommonConstants.VIEW1, getEclipseContext());
NavigationHelper.showPart(CommonConstants.VIEW2, getEclipseContext());
}
}
viewDeactivated();
}
};
java.lang.StackOverflowError : null
org.eclipse.e4.ui.workbench.modeling.ElementMatcher.select(ElementMatcher.java:71)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:182)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:317)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:271)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:271)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:271)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:251)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:271)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElements(ModelServiceImpl.java:428)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElements(ModelServiceImpl.java:409)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElements(ModelServiceImpl.java:414)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.find(ModelServiceImpl.java:448)
This is the StackOverflow trace..
How can I solve this..?
Well the stack trace shows this is an error in your code. You are running NavigationHelper.showPart in a part deactivated listener, but your code is causing another part deactivate event which calls the deactivate listener again which calls showPart again and so on.
You can't try to show a different part in the the part deactivate listener directly.
One possibility is to use Display.asyncExec in the part deactivate listener to run the showPart after the deactivate event has completed.

Android Data Binding: Missing return statement in generated code when calling custom binding adapter more than once

I am using the android data binding library and MVVM architecture. In the xml layout I define a variable named viewModel of type myViewModel. The layout has several TextInputEditText for which I used the following custom binding adapter:
//makes the drawable_right of the TextView clickable
#SuppressLint("ClickableViewAccessibility")
#BindingAdapter("onDrawableRightClick")
inline fun TextView.setOnDrawableRightClick(crossinline f: () -> Unit) {
this.setOnTouchListener(View.OnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_UP) {
if (event.rawX >= this.right - this.paddingRight - this.compoundDrawables[DRAWABLE_RIGHT].bounds.width()) {
f()
return#OnTouchListener true
}
}
false
})
}
In the layout I add app:onDrawableRightClick="#{() -> viewModel.doThing()}" to just one of the TextInputEditText and click run. Everything works, no problem.
Now I go back and add app:onDrawableRightClick="#{() -> viewModel.doOtherThing()}" to the second TextInputEditText. This time compilation fails with error: missing return statement.
The error is in MyFragmentBindingImpl (generated), in this block of code:
public final kotlin.Unit _internalCallbackInvoke(int sourceId ) {
switch(sourceId) {
case 1: {
// localize variables for thread safety
// viewModel
com.example.MyViewModel viewModel = mViewModel;
// viewModel != null
boolean viewModelJavaLangObjectNull = false;
viewModelJavaLangObjectNull = (viewModel) != (null);
if (viewModelJavaLangObjectNull) {
viewModel.doOtherThing();
}
return null;
}
case 2: {
// localize variables for thread safety
// viewModel
com.example.MyViewModel viewModel = mViewModel;
// viewModel != null
boolean viewModelJavaLangObjectNull = false;
viewModelJavaLangObjectNull = (viewModel) != (null);
if (viewModelJavaLangObjectNull) {
viewModel.doThing();
}
return null;
}
}
}
There is neither a default case nor a return statement outside of the switch. This causes the error but I was pretty sure that the default case isn't necessary when every case is handled... Anyways, when I go back to xml and remove one of the listener bindings, MyFragmentBindingImpl changes to this:
public final kotlin.Unit _internalCallbackInvoke(int sourceId ) {
// localize variables for thread safety
// viewModel
com.example.MyViewModel viewModel = mViewModel;
// viewModel != null
boolean viewModelJavaLangObjectNull = false;
viewModelJavaLangObjectNull = (viewModel) != (null);
if (viewModelJavaLangObjectNull) {
viewModel.doThing();
}
return null;
}
The compiler is happy again, but I need to use the binding adapter more than once. How can I make the library add a return statement? Is there a workaround?
I'm using Android Studio 3.4 Preview. Thanks all
#SuppressLint("ClickableViewAccessibility")
#BindingAdapter("onDrawableEndClick")
fun setOnDrawableEndClick(view: TextView, listener: OnCompoundDrawableClickListener?) {
val padding = 10
if (listener != null) {
view.setOnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_DOWN) {
if (view.compoundDrawables[DRAWABLE_RIGHT] == null) return#setOnTouchListener false
else if (event.rawX >= (view.right - view.compoundDrawables[DRAWABLE_RIGHT].bounds.width() - padding)) {
listener.onDrawableEnd()
return#setOnTouchListener true
}
}
return#setOnTouchListener false
}
}
}
try something like this i am using a custom interface for the listener(OnCompoundDrawableClickListener)

boolean value not update in Call Receiver

I have call receiver which I want to display dialog on incoming call only. For that I have created a global Boolean variable and trying to changes its value to true in ringing state. But when call disconnects, code always picks default value of Boolean not the updated value given in ringing state. The variable is num. Why it always give false value though its value getting true in ringing state only. Here is the code:
public class phonerece extends BroadcastReceiver{
private Boolean num = false;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
//some task here
}
} else if (extraState != null) {
if (extraState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
//task
} else if (extraState
.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
if (num) {
phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
//call dialog }
}
} else if (extraState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
if (checknumber() != null) {
Log.e("Nummber", "found");
} else {
Log.e("Number", "Not Found");
num = true;
}
}
}
}
public String checknumber() {
String res = null;
try {
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor c = resolver.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (c != null) { // cursor not null means number is found contactsTable
if (c.moveToFirst()) { // so now find the contact Name
res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}
c.close();
}
} catch (Exception ex) {
/* Ignore */
}
return res;
}
}
You should use static variables (private static num = false) or save your variable in SharedPreferences (it's better), because BroadcastReceivers are not saved between broadcasts. Every broadcast will create a new instance of the BroadcastReceiver, at least if registered automatically via the manifest.
(Your code snippet looks broken, the num variable is missing its type? This answer assumes its type is boolean.)
This sounds like a multithreading problem. Threads in java may cache values of variables, because synchronizing through the main memory is more expensive. You can force the synchronization by flagging the field in question as volatile. This keyword is explained here.
When a field is flagged as volatile, Threads may not cache its value, and all modifications to the variable become visible to all other Threads.
private volatile boolean num = false;

ChangeHandler not recognising a blank date

I am checking for a change in value of a date. The ValueChangeHandler is recognising a date (e.g. 1/5/2014 is updated to the DB when entered). However, when I delete a date it is not recognised (i.e., the DB is not updated to null - I have tried Backspace, highlight and Del, overtyping with spaces). I then entered a new date (2/5/2014) and this was updated to the DB. Any ideas as to why this code does not recognise that I have removed the date please.
Regards,
Glyn
I have updated this with the code suggested by Braj. Unfortunately this did not work.
final DateBox awardedDate = new DateBox();
awardedDate.setFormat(new DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
awardedDate.setValue(ymAwards.getCaAwardedDate());
awardedDate.setWidth("75px");
//Add change handler for the awarded date.
//Only a Leader or Administrator can update the date
if (accountLevel.equals("Leader") || accountLevel.equals("Administrator")) {
awardedDate.addValueChangeHandler(new ValueChangeHandler<java.util.Date>() {
int pog = 0;
public void onValueChange(ValueChangeEvent<java.util.Date> event) {
if (pog == 0) {
pog++;
Window.alert("First change hadler.");
//Check for a null date and handle it for dateBoxArchived and dateBoxPackOut
java.sql.Date sqlDateAwarded = awardedDate.getValue() == null ? null : new java.sql.Date(awardedDate.getValue().getTime());
AsyncCallback<YMAwards> callback = new YMAwardedDateHandler<YMAwards>();
rpc.updateYMAwarded(youthMemberID, returnAwID, sqlDateAwarded, callback);
}else{
pog = 0;
}
}
});
awardedDate.getTextBox().addValueChangeHandler(new ValueChangeHandler<String>() {
#Override
public void onValueChange(ValueChangeEvent<String> event) {
if (event.getValue() == null) {
Window.alert("Second change hadler.");
//Check for a null date and handle it for dateBoxArchived and dateBoxPackOut
java.sql.Date sqlDateAwarded = awardedDate.getValue() == null ? null : new java.sql.Date(awardedDate.getValue().getTime());
AsyncCallback<YMAwards> callback = new YMAwardedDateHandler<YMAwards>();
rpc.updateYMAwarded(youthMemberID, returnAwID, sqlDateAwarded, callback);
}
}
});
}
Add this line:
awardDate.setFireNullValues(true);
This was added in GWT 2.5.
Try this one also
final DateBox dateBox = new DateBox();
dateBox.getTextBox().addValueChangeHandler(new ValueChangeHandler<String>() {
#Override
public void onValueChange(ValueChangeEvent<String> event) {
if (dateBox.getValue() == null) {
System.out.println("date value is empty");
// your code here
}
}
});
output:
date value is empty
DateBox#addValueChangeHandler() fires when there is any change in date via date picker.
You can check the value in text box using TextBox#addValueChangeHandler().

Categories

Resources