How to determine the type of object in blackberry application? - blackberry-jde

On my screen i have ButtonField and CustomButtonField.
Both have been added to Listner of my screen.
myScreen.add(new ButtonField("click me"));
myScreen.add(new CustomButtonField("click me Again"));
Now i want to know which button is clicked and type of object in fieldChanged function.
public void fieldChanged(Field field, int context) {
//Here- how to determine the type of object
//which object has been clicked
//ButtonField or CustomButtonField????
}
Kindly Help
Thanks
SIA

instanceof is your friend:
public void fieldChange(Field field, int context) {
if(field instanceof CustomButtonField)
;//do something
else if(field instanceof ButtonField)
;//do something
}

Related

Recognize pointer down event without delay in Flutter (iOS, Android)

T'd like to track pointer events in Flutter (pointer down/up and pointer position) but there's always a delay (about 500ms) between the moment a finger touch the screen and the PointerDown event, unless I move my finger immediately.
The standard GestureDetector doesn't handle that (there is a delay to recognize TapDown event), so I tried the code below but to no avail: the delay is still there.
Any idea how could I solve this problem?
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
typedef PositionEventHandler = void Function(Offset);
class MySimplePointerGestureRecognizer extends OneSequenceGestureRecognizer {
final PositionEventHandler onPointerDown;
final PositionEventHandler onPointerUpdate;
final PositionEventHandler onPointerUp;
MySimplePointerGestureRecognizer(
{#required this.onPointerUp,
#required this.onPointerUpdate,
#required this.onPointerDown});
#override
void addPointer(PointerEvent event) {
startTrackingPointer(event.pointer);
resolve(GestureDisposition.accepted);
}
#override
void handleEvent(PointerEvent event) {
if(event is PointerDownEvent) {
onPointerDown(event.position);
}
if (event is PointerMoveEvent) {
onPointerUpdate(event.position);
}
if (event is PointerUpEvent) {
onPointerUp(event.position);
stopTrackingPointer(event.pointer);
}
}
#override
void didStopTrackingLastPointer(int pointer) {}
#override
String get debugDescription => 'simplePointerTracker';
}

How to detect valueChange event in validator?

Mojarra 2.1
I need to write a validator for the h:inputText which performs some logic only if the value for that input is changed. I.e.
public class MyValidator implements Validator{
public void validate(FacesContext context,
UIComponent component,
Object value) throws ValidatorException;
if(valueChanged(UIComponent component)){ //The method checks if the value's changed
//do some piece of logic
}
return;
}
}
I dug into the queuing events of the UIInput and found this:
validateValue(context, newValue);
// If our value is valid, store the new value, erase the
// "submitted" value, and emit a ValueChangeEvent if appropriate
if (isValid()) {
Object previous = getValue();
setValue(newValue);
setSubmittedValue(null);
if (compareValues(previous, newValue)) {
queueEvent(new ValueChangeEvent(this, previous, newValue));
}
}
This piece of code is from the method, executed by the Validation phase callback. The first thought that popped into my head was queriyng all events fired during handling the request. The method queueEvent(FacesEvent) is implemented as follows:
public void queueEvent(FacesEvent event) {
if (event == null) {
throw new NullPointerException();
}
UIComponent parent = getParent();
if (parent == null) {
throw new IllegalStateException();
} else {
parent.queueEvent(event);
}
}
Therefore every such invokation will end up in UIViewRoot.queueEvent(FacesEvent) which is implemented as:
public void queueEvent(FacesEvent event) {
if (event == null) {
throw new NullPointerException();
}
// We are a UIViewRoot, so no need to check for the ISE
if (events == null) {
int len = PhaseId.VALUES.size();
List<List<FacesEvent>> events = new ArrayList<List<FacesEvent>>(len);
for (int i = 0; i < len; i++) {
events.add(new ArrayList<FacesEvent>(5));
}
this.events = events;
}
events.get(event.getPhaseId().getOrdinal()).add(event);
}
Which means, all events is actually stored as a List<List<FacesEvent>> for each phase. But the List<List<FacesEvent>> events is a private field, so it's impossible to get direct acces to it.
Another thing is that the actual validation is being perfromed before the quingEvent, so implemting valueChangeListener doesn't seem useful as well.
Question: Is it possible to implements such validator in JSF in a natural way?
Just do the value comparison yourself. In the validator, the old value is just readily available via UIComponent argument.
#Override
public void validate(FacesContext context, UIComponent component, Object submittedValue) {
if (component instanceof EditableValueHolder) {
Object newValue = submittedValue;
Object oldValue = ((EditableValueHolder) component).getValue();
if (newValue == null ? oldValue == null : newValue.equals(oldValue)) {
return; // Not changed, so skip validation.
}
}
// Do actual validation here.
}
If you happen to use JSF utility library OmniFaces, it has a ValueChangeValidator which does exactly this.

How to detect when MvxListView is bound and has loaded its bindings?

I've Inherted MvxListView to my CustomMvxListView where I dos something with the visualization when a child has been added or removed.
It works great but can be laggy when many items get bound.
Is there a way to detect when Mvx view controls are bound and loaded there first bound data?
Found a good solution myself;
To track Itemsource changes in Android in a ListView you can use a DataSetObserver.
like:
internal class MyObserver : DataSetObserver
{
private readonly object view;
public MvxListViewNonScrollableObserver(ViewToTrack view)
{
tView = view;
DoSomething():
}
public override void OnChanged()
{
base.OnChanged();
DoSomething():
}
}
Add it to a ListView by:
class MyMvxListView : MvxListView
{
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
itemsourceObserver = new MyObserver(this);
Adapter.RegisterDataSetObserver(itemsourceObserver);
}
protected override void OnDetachedFromWindow()
{
if (itemsourceObserver != null)
{
Adapter.UnregisterDataSetObserver(itemsourceObserver);
itemsourceObserver = null;
}
base.OnDetachedFromWindow();
}
public void DoSomething()
{
}
DoSomething() get raised after load and on every itemsource change.

GWT Celtable: two clicks needed to change checkbox state in FireFox

In my project i have CellTable with CheckBoxCell column. This is regular column to represent (change) values and doesn't use for row selection (for selection i use SingleSelectionModel). In Chrome everything works fine, on first click I get checkbox state changed and row selected. In FireFox when I try to click on check box in CheckBoxCell column GWT selects row and after second click on checkbox it change checkbox state. But I need the same behavior as in Chrome (change checkbox state on first click).
Here is how i create column:
private <C> Column<T, C> addColumn(CellTable<T> itemListTable, Cell<C> cell, String headerText, int columnWidthPct, final IValueGetter<C, T> getter, #Nullable FieldUpdater<T, C> fieldUpdater) {
Column<T, C> column = new Column<T, C>(cell) {
#Override
public C getValue(T object) {
return getter.getValue(object);
}
};
column.setFieldUpdater(fieldUpdater);
column.setSortable(false);
itemListTable.addColumn(column, headerText);
itemListTable.setColumnWidth(column, columnWidthPct, PCT);
return column;
}
private void generateExistingSettingsTable() {
addColumn(existingSettingsTable, new ParameterizedCheckboxCell<T>(), IS_PUBLIC_HEADER, 10, new IValueGetter<Boolean, T>() {
#Override
public Boolean getValue(T setting) {
return setting.isPublic();
}
},
new FieldUpdater<T, Boolean>() {
#Override
public void update(int index, T object, Boolean value) {
object.setPublic(value);
updatePublicState(object);
}
}
);
}
My ParameterizedCheckboxCell extends CheckboxCell and overrides only render method (to enable\disable checkbox input).
I already tried everything suggested here here:
stopPropagation doesn't works for me
Add column to DefaultSelectionEventManager black list, is not an option (very large area left unclickable around checkbox)
As i found out today, the same thing happen with Chrome (version 45.0.2454.101).
I investigate this more and find out the following. GWT CheckboxCell by default consume only two browser events: keydown and change. In old Chrome version when you clicked on checkbox change event fired and everything works fine. In FireFox and in the new Chrome version there is no change event after click (i cannot figure out why, explanations are welcome), so i decide to create my own checkbox class that extends AbstractEditableCell<Boolean, Boolean> and replace consumed change to click event. Here is what i got:
import java.util.Objects;
import com.google.gwt.cell.client.AbstractEditableCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import static com.google.gwt.dom.client.BrowserEvents.CLICK;
import static com.google.gwt.dom.client.BrowserEvents.KEYDOWN;
public class ParameterizedCheckboxCell extends AbstractEditableCell<Boolean, Boolean> {
public ParameterizedCheckboxCell() {
super(KEYDOWN, CLICK);
}
#Override
public void render(Context context, Boolean value, SafeHtmlBuilder sb) {
// Here i have some specific logic so i skip this part
// You can just copy/paste body of this method from original CheckboxCell
}
#Override
public void onBrowserEvent(Context context, Element parent, Boolean value, NativeEvent event, ValueUpdater<Boolean> valueUpdater) {
final String type = event.getType();
final boolean enterPressed = KEYDOWN.equals(type) && event.getKeyCode() == KeyCodes.KEY_ENTER;
if (CLICK.equals(type) || enterPressed) {
InputElement input = parent.getFirstChild().cast();
Boolean isChecked = input.isChecked();
if (enterPressed) {
isChecked = !isChecked;
input.setChecked(isChecked);
}
if (Objects.equals(value, isChecked)) {
clearViewData(context.getKey());
} else {
setViewData(context.getKey(), isChecked);
}
valueUpdater.update(isChecked);
}
}
#Override
public boolean isEditing(Context context, Element parent, Boolean value) {
return false;
}
}
I skipped dependsOnSelection and handlesSelection because i dont use this for selection column.

Slow loading of layout

I have a super class which is in a library. This library take care of initializing some basic layout components and other stuff. My problem is that it takes 1.x seconds to load the layout, and shows the default layout for a while, before setting the child-specified layout.
This is the method of my super class:
public void InitializeWindow(Activity act, int layoutResourceId, String windowTitle,
Object menuAdapter, int slideMenuMode) {
super.setContentView(layoutResourceId);
super.setBehindContentView(R.layout.menu_frame);
this.menuAdapter = menuAdapter;
this.slideMenuMode = slideMenuMode;
setWindowTitle(windowTitle);
initializeSlidingMenu();
}
This is called this way:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.InitializeWindow(this, R.layout.activity_home, "\t\tHome",
new MenuAdapter(this, R.menu.slide_menu), SlidingMenu.TOUCHMODE_FULLSCREEN);
}
The application works like a charm, but it takes, as I said around 1.x seconds to load the layout passed from the child-class. Why does this happen?
By request, this is my initializeSlideMenu() method:
public void initializeSlidingMenu() {
this.setSlidingActionBarEnabled(true);
getSlidingMenu().setBehindOffsetRes(R.dimen.actionbar_home_width);
getSlidingMenu().setShadowWidthRes(R.dimen.shadow_width);
getSlidingMenu().setShadowDrawable(R.drawable.shadow);
getSlidingMenu().setTouchModeAbove(slideMenuMode);
getSlidingMenu().setBehindScrollScale(0.25f);
ListView v = new ListView(this);
v.setBackgroundColor(Color.parseColor("#000000"));
v.setAdapter((ListAdapter) menuAdapter);
getSlidingMenu().setMenu(v);
}
To avoid such problems there are three ways in general.
Let your onCreate() finish after setContentView() call as early as possible. You can use postDelayed runnable to delay few initialization which may not be needed at early stages.
Do some task when the view is ready, it causes the Runnable to be added to the message queue of that view.
Snippet
view.post(new Runnable() {
#Override
public void run() {
}
});
If none of the above helps consider "Optimize with stubs" link : http://android-developers.blogspot.in/2009/03/android-layout-tricks-3-optimize-with.html
Hope it helps.
I suspect that the trouble spot for you is with:
v.setAdapter((ListAdapter) menuAdapter);
You should do this as part of an AsyncTask. It will often be very slow to execute the loading by the adapter.
Here is a snippet from a sample AsyncTask implementation:
//before starting the load, I pop up some indicators that I'm doing some loading
progressBar.setVisibility(View.VISIBLE);
loadingText.setVisibility(View.INVISIBLE);
AsyncTask<Void, Void, Void> loadingTask = new AsyncTask<Void, Void, Void>() {
private ArrayList<Thing> thingArray;
#Override
protected Void doInBackground(Void... params) {
//this is a slow sql fetch and calculate for me
thingArray = MyUtility.fetchThings(inputValue);
return null;
}
#Override
public void onPostExecute(Void arg0) {
EfficientAdapter myAdapter = new EfficientAdapter(MyActivity.this, thingArray);
listView.setAdapter(myAdapter);
//after setting up my adapter, I turn off my loading indicators
progressBar.setVisibility(View.INVISIBLE);
loadingText.setVisibility(View.INVISIBLE);
RelativeLayout layout = (RelativeLayout)MyActivity.this.findViewById(R.id.spacey);
if (layout != null) {
LayoutInflater inflater = LayoutInflater.from(MyActivity.this);
View view = inflater.inflate(R.layout.name_tabled_sub, layout);
NamedTableView tableView = new NamedTableView(MyActivity.this, view);
}
progressBar.setVisibility(View.INVISIBLE);
loadingText.setVisibility(View.INVISIBLE);
}
};
loadingTask.execute();
You can also do "PreExecute" items with the Async task, as well as update.

Resources