LWUIT List works terribly slow - list

I've faced with the well-known problem in LWUIT. My list component with the checkbox renderer scrolls very slow. If to test my application on emulator it runs quite smoothly (nevertheless I see CPU utilization splashes up to 60% during scroll action), but if to run it on mobile phone it takes a couple of seconds between focus movements.
There's a code of renderer:
public class CheckBoxMultiselectRenderer extends CheckBox implements ListCellRenderer {
public CheckBoxMultiselectRenderer() {
super("");
}
//override
public void repaint() {
}
public Component getListCellRendererComponent(List list, Object value,
int index,boolean isSelected) {
Location loc = (Location)value;
setText(loc.getLocationName());
setFocus(isSelected);
setSelected(loc.isSelected());
return this;
}
public Component getListFocusComponent(List list) {
setText("");
setFocus(true);
getStyle().setBgTransparency(Consts.BG_TRANSPARENCY);
return this;
}
}
that's the code of my form containing the list:
protected void createMarkup() {
Form form = getForm();
form.setLayout(new BorderLayout());
form.setScrollable(false);
Label title = new Label("Choose location zone:");
title.getStyle().setMargin(5, 5, 0, 0);
title.getStyle().setBgTransparency(Consts.BG_TRANSPARENCY);
title.setAlignment(Component.CENTER);
form.addComponent(BorderLayout.NORTH, title);
list = new List(StateKeeper.getLocationsAsList());
list.setFixedSelection(List.FIXED_NONE_CYCLIC);
// list.setSmoothScrolling(true);
list.getStyle().setBgTransparency(0);
list.setListCellRenderer(new CheckBoxMultiselectRenderer());
list.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
// List l = (List)ae.getSource();
// l.requestFocus();
// l.setHandlesInput(true);
Location selItem = (Location)list.getSelectedItem();
selItem.setSelected(!selItem.isSelected());
}
});
form.addComponent(BorderLayout.CENTER, list);
}
I would be very thankful for any help!

We must be so carefull building lwuit List. If we have made something wrong they can work worse than expected. I recommend you to take a look on this
LWUIT Blog ListRender
You can also rewrite your paint method. You list's speed will be increased.

Related

JavaFX - using toggle isSelected() in conditional statements

I'm building a simple sketch program using JavaFX. I want the user to be able to switch between drawing a rectangle, circle or line and I've put toggle radio buttons in the menu for these options.
Is it possible to write an if/else statement so I can write code for three different functions depending on which is selected? At the moment it will only draw lines. This is part of my code so far (sorry it's messy):
package Sketchbook;
public class Sketchbook extends Application {
final static int CANVAS_WIDTH = 800;
final static int CANVAS_HEIGHT = 600;
ColorPicker colorPicker1;
ColorPicker colorPicker2;
#Override
public void start(final Stage primaryStage) {
final Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
final GraphicsContext graphicsContext = canvas.getGraphicsContext2D();
initDraw(graphicsContext);
canvas.addEventHandler(MouseEvent.MOUSE_PRESSED,
new EventHandler<MouseEvent>(){
#Override
public void handle(MouseEvent event) {
graphicsContext.beginPath();
graphicsContext.moveTo(event.getX(), event.getY());
graphicsContext.setStroke(colorPicker1.getValue());
graphicsContext.stroke();
}
});
canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED,
new EventHandler<MouseEvent>(){
#Override
public void handle(MouseEvent event) {
graphicsContext.lineTo(event.getX(), event.getY());
graphicsContext.setStroke(colorPicker1.getValue());
graphicsContext.stroke();
}
});
canvas.addEventHandler(MouseEvent.MOUSE_RELEASED,
new EventHandler<MouseEvent>(){
#Override
public void handle(MouseEvent event) {
}
});
Group root = new Group();
ToggleGroup toggleGroup = new ToggleGroup();
RadioButton rectangle = new RadioButton("Rectangle");
RadioButton circle = new RadioButton("Circle");
RadioButton line = new RadioButton("Line");
rectangle.setSelected(true);
rectangle.setToggleGroup(toggleGroup);
circle.setToggleGroup(toggleGroup);
line.setToggleGroup(toggleGroup);
You've pretty much already described what you need to do:
canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED,
new EventHandler<MouseEvent>(){
#Override
public void handle(MouseEvent event) {
if (toggleGroup.getSelectedToggle() == line) {
graphicsContext.lineTo(event.getX(), event.getY());
graphicsContext.setStroke(colorPicker1.getValue());
graphicsContext.stroke();
} else if (toggleGroup.getSelectedToggle() == rectangle) {
// etc...
} // etc...
}
}
});
Obviously you may need to reorder the code a little to make sure variables are declared and initialized before you use them.

Hiding / showing markers: OSMDroid / OpenMaps

I have an app which uses or googlemaps or openMaps (offline) depending of connection state.
In each case there are markers, for places or point of interest or… I want that the user can display or hide some category of markers.
When using google maps I have a menu and in the action bar when some item is selected it toggles between showing or hiding the markers from the correpondent category; As for google maps that works easily & perfectly using isVisible();
As for osmdroid i have not found in the doc any equivalent to isVisible(), neither any show() or hide() method. So I have tried to use as a workaround somemarkers.getAlpha() & somemarkers.setAlpha(), toggling between 0 & 1 alpha values.
No error occurs but the visibility of markers remains the same, not toggling, or only randomly when i tap 10 or 20 times on the action icon.
In the log i get "InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed" which seems to me to be the cause.
But what to do to avoid this?
KitKat, SonyXperia Z
In osmdroid, the method to hide/show overlays (markers) is:
Overlay.setEnabled(boolean enabled)
I have done this bit differently.
Extend ItemizedIconOverlay
Add as an overlay to mapView
Hide markers by using removeAllItems or removeItem
Show marker by adding it to the itemized overlay list
Create a new Overlay class by extending ItemizedIconOverlay.
Note: WaypointOverlayItem extends OverlayItem. {It's your custom overlay model class}
public class NavigatorItemizedOverlay extends ItemizedIconOverlay<WaypointOverlayItem> {
private Context mContext;
public NavigatorItemizedOverlay(final Context context, final List<WaypointOverlayItem> aList) {
super(context, aList, new OnItemGestureListener<WaypointOverlayItem>() {
#Override
public boolean onItemSingleTapUp(int index, WaypointOverlayItem item) {
return false;
}
#Override
public boolean onItemLongPress(int index, WaypointOverlayItem item) {
return false;
}
});
// TODO Auto-generated constructor stub
mContext = context;
}
}
Add this Overlay to your map
//Add Itemized overlay
navigatorItemizedOverlay = new NavigatorItemizedOverlay(getActivity(), waypointOverlayItemList);
mapView.getOverlays().add(navigatorItemizedOverlay);
To Add marker:
navigatorItemizedOverlay.addItem(waypointOverlayItem);
To hide all markers:
navigatorItemizedOverlay.removeAllItems();
There are other methods:
removeItem(position) and removeItem(waypointOverlayItem)

JComboBox list based model

In my program I use couple JComboBoxes with a simple list combo box model:
public class ListComboBoxModel<T> extends AbstractListModel implements ComboBoxModel {
protected List<T> list;
private T selection;
public ListComboBoxModel(List<T> list) {
this.list = list;
this.selection = getDefaultSelection();
}
protected T getDefaultSelection() {
if (list.size() > 0) {
return list.get(0);
} else {
return null;
}
}
#Override
public Object getSelectedItem() {
return selection;
}
#Override
public void setSelectedItem(Object anItem) {
selection = (T) anItem;
}
#Override
public int getSize() {
return list.size();
}
#Override
public T getElementAt(int index) {
return list.get(index);
}
}
And the problem is that when I add elements to the list that combobox is using it doesn't work as intended anymore. If I click on combo box, the list has correct length but all elements in there are empty so the list is all white. When I roll over an element it doesn't highlight. When I click anywhere in the list it always works as if I selected the recently added element. If I reduce list size back to original or even decrease it, combo box works as it should have.
To edit the lists that combo boxes use, I use JTables and the add method I implemented in their models.
public void add(T element) {
list.add(element);
fireTableDataChanged();
}
Any ideas how can I fix that?
Well if anyone were interested I solved problem by adding
fireContentsChanged(this, 0, getSize());
in a method that gets called when by table/list gets changed anywhere in the program using observer pattern.

Built-in ScrollView that scrolls with head motion

Speaking "ok glass" brings up a command list that automatically scrolls based on the user's head motion.
Is there a built-in UI element in the GDK that implements this? Or will I have to write my own code that uses sensors?
I tried reimplementing parts of this. It's not as shiny as the google one, but those could serve as a starting point:
https://github.com/pscholl/glass_snippets/blob/master/lib/src/main/java/de/tud/ess/HeadListView.java
https://github.com/pscholl/glass_snippets/blob/master/lib/src/main/java/de/tud/ess/HeadScrollView.java
I went through the GDK's Developer Guides at https://developers.google.com/glass/develop/gdk/dev-guides and Reference at https://developers.google.com/glass/develop/gdk/reference/index and there's definitely no such built-in UI elements in GDK, as of XE 12 released in December 2013.
So the answer for now is yes you have to use sensors to implement that.
There is currently no native GDK UI element for scrolling a list using sensors (in fact, according to this issue, use of ListView at all appears to be discouraged).
However, I was able to get the following to work reasonably well in my app. My list is fixed at 4 elements (which helps determine how much scrolling happens), so you can tweak this accordingly (see comments).
import com.google.android.glass.media.Sounds;
import com.google.android.glass.touchpad.Gesture;
import com.google.android.glass.touchpad.GestureDetector;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.view.MotionEvent;
import android.widget.ListView;
/**
* Implements sensor-based scrolling of a ListView
*/
public class SensorListController implements SensorEventListener, GestureDetector.BaseListener {
static final String TAG = "SensorListController";
Context mContext;
ListView mList;
SensorManager mSensorManager;
private float[] mRotationMatrix = new float[16];
private float[] mOrientation = new float[9];
private float[] history = new float[2];
private float mHeading;
private float mPitch;
boolean mActive = true;
GestureDetector mGestureDetector;
public SensorListController(Context context, ListView list) {
this.mContext = context;
this.mList = list;
history[0] = 10;
history[1] = 10;
mGestureDetector = new GestureDetector(mContext);
mGestureDetector.setBaseListener(this);
}
/**
* Receive pass-through of event from View
*/
public boolean onMotionEvent(MotionEvent event) {
return mGestureDetector.onMotionEvent(event);
}
#Override
public boolean onGesture(Gesture gesture) {
switch (gesture) {
case TWO_LONG_PRESS:
// Toggle on and off accelerometer control of the list by long press
playSuccessSound();
toggleActive();
return true;
case TWO_TAP:
// Go to top of the list
playSuccessSound();
scrollToTop();
return true;
}
return false;
}
/**
* Should be called from the onResume() of Activity
*/
public void onResume() {
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
SensorManager.SENSOR_DELAY_UI);
}
/**
* Should be called from the onPause() of Activity
*/
public void onPause() {
mSensorManager.unregisterListener(this);
}
/**
* Toggles whether the controller modifies the view
*/
public void toggleActive() {
mActive = !mActive;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (mList == null || !mActive) {
return;
}
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values);
SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X,
SensorManager.AXIS_Z, mRotationMatrix);
SensorManager.getOrientation(mRotationMatrix, mOrientation);
mHeading = (float) Math.toDegrees(mOrientation[0]);
mPitch = (float) Math.toDegrees(mOrientation[1]);
float xDelta = history[0] - mHeading; // Currently unused
float yDelta = history[1] - mPitch;
history[0] = mHeading;
history[1] = mPitch;
float Y_DELTA_THRESHOLD = 0.13f;
// Log.d(TAG, "Y Delta = " + yDelta);
int scrollHeight = mList.getHeight()
/ 19; // 4 items per page, scroll almost 1/5 an item
// Log.d(TAG, "ScrollHeight = " + scrollHeight);
if (yDelta > Y_DELTA_THRESHOLD) {
// Log.d(TAG, "Detected change in pitch up...");
mList.smoothScrollBy(-scrollHeight, 0);
} else if (yDelta < -Y_DELTA_THRESHOLD) {
// Log.d(TAG, "Detected change in pitch down...");
mList.smoothScrollBy(scrollHeight, 0);
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private void scrollToTop() {
mList.smoothScrollToPosition(0);
}
private void playSuccessSound() {
// Play sound to acknowledge action
AudioManager audio = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
audio.playSoundEffect(Sounds.SUCCESS);
}
}
I used the above in a ListActivity. I initialize it in onCreate(), and here is the method that initializes it:
private void initListController() {
mListView = getListView();
mListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
mListView.setSelector(android.R.color.transparent);
mListView.setClickable(true);
mListController = new SensorListController(this, mListView);
}
This also removes the selection indicator from view by making it transparent.
The above controller also uses two finger press to pause/resume scrolling, and a two finger tap to scroll to the top of the list (and acknowledges both these actions with a sound). Note that for these gestures to work, you will need to override onGenericMotionEvent() in your Activity and pass through the event, like:
#Override
public boolean onGenericMotionEvent(MotionEvent event) {
// We need to pass events through to the list controller
if (mListController != null) {
return mListController.onMotionEvent(event);
}
return false;
}
Full source code for this solution can be seen on Github, and the APK can be downloaded here.

WICKET: Updating a self-made Panel

ive got the following Problem:
my self-made video-class (extending Panel) doesnt get updated, if its model changes.
Thats the current state:
I got a Class "A" with a ListChoice. This Class creates the Panel "descrPanel", which gets a Model, containing the current selected Item of the ListChoice. It is updated, when the User selects something in the ListChoice (The ListChoice got an AjaxBehaviour, updating the descrPanel via target.add(descrPanel)):
Class A:
PropertyModel<Exercise> currExerciseModel = new PropertyModel<Exercise>(this,"selectedExercise");
final ExerciseDescriptionPanel descrPanel = new ExerciseDescriptionPanel("descrPanelTag", currExerciseModel);
descrPanel.setOutputMarkupId(true);
In Class ExerciseDescriptionPanel, i inserted my self-made Video-Class (extending Panel). Also i inserted a MultiLineLabel:
Class ExerciseDescriptionPanel
public class ExerciseDescriptionPanel extends Panel {
private IModel<Exercise> model;
private Exercise exercise;
public ExerciseDescriptionPanel(String id, IModel<Exercise> model) {
super(id, model);
this.model = model;
MultiLineLabel mll = new MultiLineLabel("mll", new Model() {
#Override
public String getObject() {
if (ExerciseDescriptionPanel.this.getModel().getObject() != null){
return ExerciseDescriptionPanel.this.getModel().getObject().getDescription();
}
else return "";
}
});
add(mll);
Video video = new Video("myVideo", new Model<Exercise>(){
#Override
public Exercise getObject() {
if (ExerciseDescriptionPanel.this.getModel().getObject() != null){
return ExerciseDescriptionPanel.this.getModel().getObject();
}
else return new Exercise();
}
});
add(video);
}
Well, what i dont understand is: While the Description is updated based on the current selection of the ListChoice, the Video-Class just ignores it and keeps returning the "new Exercise()", which schould only be returned at the first load of the ListChoice, when no selection is made.
I also provide you the Video-Class:
Class Video
public class Video extends Panel{
private IModel<Exercise> model;
public Video(String id, IModel<Exercise> model) {
super(id, model);
String src = ((Exercise)model.getObject()).getVideo();
String startPicDest = ((Exercise)model.getObject()).getPicture();
WebMarkupContainer flashSrc = new WebMarkupContainer("flashSrcTag");
flashSrc.add(new AttributeModifier("value", "config={'playlist':['" +
startPicDest +"',{'url':'"+ src +"','autoPlay':false}]}"));
this.add(flashSrc);
setOutputMarkupId(true);
}
}
Ive been searching through the internet for hours now, without finding anything helpful.
Hope you guys are able to give me some solution to this problem. Thanks in regard.
Greetings
You're pulling the exercise out of the model once only:
public Video(String id, IModel<Exercise> model) {
super(id, model);
String src = ((Exercise)model.getObject()).getVideo();
...
}
How is this supposed to be up-to-date when the exercise changes later on?
You have to get the actual value for each render:
WebMarkupContainer flashSrc = new WebMarkupContainer("flashSrcTag") {
public void onComponentTag(ComponentTag tag) {
Exercise temp = (Exercise)model.getObject();
String src = temp.getVideo();
String startPicDest = temp.getPicture();
tag.put("value", String.format("config={'playlist':['%s',{'url':'%s','autoPlay':false}]}", startPicDest, src));
}
};
NOTE: Please ignore this humble try to help you, svenmeier's answer is way better than mine.
I'm not 100% sure if this is true, but could it be related to the difference between your Video being a MarkupContainer and the MultiLineLabel being a WebComponent?
Both the Video and the MultiLineLabel are added to the ExerciseDescriptionPanel in its constructor. If I understand the Wicket documentation correctly, as long as the surrounding Page and thus the ExerciseDescriptionPanel stay the same instance, the markup of the Video will not be regenerated. It says:
A Page renders itself by rendering its associated markup (the html file that sits next to the Page). As MarkupContainer (the superclass for Page) iterates through the markup stream for the associated markup, it looks up components attached to the tags in the markup by id. Since the MarkupContainer (in this case a Page) is already constructed and initialized by onBeginRequest(), the child for each tag should be available in the container. Once the Component is retrieved, it's render() method is called.
Maybe you calling modelChanged() on your Video once you change the Model of your ExerciseDescriptionPanel could indicate that the markup has to be refreshed.