checkboxcell event - events

GWT 2.4
I have a CheckBoxCell in a CellTable. After checking/unchecking the checkbox, the change event fires twice. I can't figure out why.
Any help will be appreciated.
private void createTable() {
// Create a CellTable with a key provider.
final CellTable<Contact> table = new CellTable<Contact>(KEY_PROVIDER);
// Add a checkbox column
final CheckboxCell cbCell = new CheckboxCell();
Column<Contact, Boolean> cbColumn = new Column<Contact, Boolean>(cbCell) {
#Override
public Boolean getValue(Contact object) {
System.out.println("method getValue() - " + object.id + " - " + object.checked);
return object.checked;
}
};
cbColumn.setFieldUpdater(new FieldUpdater<Fieldupdater.Contact, Boolean>() {
#Override
public void update(int index, Contact object, Boolean value) {
System.out.println("method update() - " + object.id + " - " + value);
}
});
table.addColumn(cbColumn);
// Push the data into the widget.
table.setRowData(CONTACTS);
// Add it to the root panel.
RootPanel.get("table1").add(table);
}

Related

How to use RxJava / RxAndroid in Android to make slow network call and update the UI?

I have started reading about RxJava / RxAndroid, but I can't find simple tutorial that covers typical thing, like getting network data and updating UI with the result.
Many tutorials cover scenario like running one or more background tasks, that take a parameter and return nothing.
Lets say I have a slow function that may return data or throw an Exception, like this:
private String getNetworkData(Integer parameter) throws Exception {
Thread.sleep(1000); // simulated delay
switch (parameter) {
case 0: return "Bill";
case 1: return "Joe";
case 2: return "Bob";
case 3: return "Alex";
case 4: return "Mary";
default: throw new Exception("No such user");
}
}
So far, I have written something like this: in my MainActivity I have a button with onClick set like this:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Observable<Integer> observable = Observable
.just(0, 1, 3, 4, 8) // these are call parameters, right?
.subscribeOn(Schedulers.io()) // this is where I do slow work, right?
.observeOn(AndroidSchedulers.mainThread()); // this is where I get results, right?
observable.subscribe(new Observer<Integer>() {
#Override
public void onSubscribe(#NonNull Disposable d) {
Log.d(TAG,"onSubscribe on " + Thread.currentThread().getName());
}
#Override
public void onNext(#NonNull Integer i) {
// what to do with returned?
// how do I catch errors?
String returnedData = getNetworkData(i);
Log.d(TAG,"onNext on " + Thread.currentThread().getName());
}
#Override
public void onError(#NonNull Throwable e) {
// how and where to throw errors that can be processed here?
Log.d(TAG,"onSubscribe on " + Thread.currentThread().getName());
}
#Override
public void onComplete() {
Log.d(TAG,"onComplete on " + Thread.currentThread().getName());
}
});
}
});
The question is: how can I update UI and receive returned data?
I have tried to understand something from this:
How to return value in rxJava
but it does not explain anything to me, I have no idea what type is youtubeApi (is it Observable or what?).
After some discussion in comments under another question I changed my button handler to this:
Callable callable = new Callable<String>() {
#Override
public String call() throws Exception {
Log.d(TAG, "callable called on " + Thread.currentThread().getName());
Thread.sleep(1000); // simulated delay
throw new Exception("Exception!");
// return "Bill";
// this is not what I want, because I can't get any parameter from here
}
};
SingleObserver<String> observer = new SingleObserver<String>() {
#Override
public void onSubscribe(#NonNull Disposable d) {
Log.d(TAG, "onSubscribe called on " + Thread.currentThread().getName());
}
#Override
public void onSuccess(#NonNull String s) {
Log.d(TAG, "onSuccess called on " + Thread.currentThread().getName());
}
#Override
public void onError(#NonNull Throwable e) {
Log.d(TAG, "onError called on " + Thread.currentThread().getName());
}
};
Single.fromCallable(callable)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
But now I can't pass a parameter to my slow function.
OK. I got this.
So we need an observer, which will update our view.
Observer<String> observer = new Observer<String>() {
#Override
public void onSubscribe(#NonNull Disposable d) {
Log.d(TAG, "onSubscribe called on thread " + Thread.currentThread().getName());
}
#Override
public void onNext(#NonNull String s) {
Log.d(TAG, "onNext called on thread " + Thread.currentThread().getName() + " returned data " + s);
}
#Override
public void onError(#NonNull Throwable e) {
Log.d(TAG, "onError called on thread " + Thread.currentThread().getName() + " with message " + e.getMessage());
}
#Override
public void onComplete() {
Log.d(TAG, "onComplete called on thread " + Thread.currentThread().getName());
}
};
I need a function, that takes Integer as parameter (this will be my database Id) and returns String (this will be data returned from database).
Function<Integer, String> getNameByIdFunction = new Function<Integer, String>() {
#Override
public String apply(Integer integer) throws Throwable {
Thread.sleep(1000); // simulated delay
switch (integer) {
case 0:
return "Bill";
case 1:
return "Joe";
case 2:
return "Bob";
case 3:
return "Alex";
case 4:
return "Mary";
default:
throw new Exception("No such user");
}
}
};
And finally we need to connect everything together with Observable.
Observable
.just(1,3,5,0,4) // I want 5 function calls with diffrent parameters
.map(getNameByIdFunction) // this is my function
.subscribeOn(Schedulers.io()) // this is thread for a function
.observeOn(AndroidSchedulers.mainThread()) // this is thread that will update my UI
.subscribe(observer); // everything will start after we subscribe

JavaFX creating a new scene from KeyCombination correctly

I dont like menu bars so I am limiting my application to KeyCombinations to spawn events. I have the key combination working however I have a feeling I am not using controllers correctly. I need to edit the new scene within my controller but instead I find myself doing so within the try/catch of the KeyCombination event.
I would like to make all changes to the scene in class SettingsController.java
where I create a new scene/view
final KeyCombination settingsCMD = new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN);
scene.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>()
{
#Override
public void handle(KeyEvent event)
{
if (settingsCMD.match(event))
{
System.out.println("CTRL + S was pressed on " + name + " display\n" +
"Opening Settings Scene");
/*
* This is where we need to launch a scene for settings
*/
try
{
Parent root = FXMLLoader.load(getClass().getResource("/sample/view/settingsscreen.fxml"));
Stage settingsStage = new Stage();
settingsStage.setTitle("Settings");
settingsStage.setScene(new Scene(root, 500 , 400));
settingsStage.show();
// This really needs to be done in the controller. How do I do this?
JSON jsonTools = new JSON();
jsonTools.readJSONSettings();
jsonTools.writeJSONSettings();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
});
SettingsController.java
public class SettingsController
{
#FXML private TextField hostname;
public String getText()
{
String textProp = textProperty().get();
System.out.println("testProperty is " + textProp + "\n");
return textProp;
}
public void setText(String value)
{
textProperty().set(value);
}
private StringProperty textProperty()
{
return hostname.textProperty();
}
}
You can get a reference to the view controller class from the FXMLLoader:
FXMLLoader loader = new FXMLLoader(getClass().getResource(resource));
Scene scene = new Scene(loader.load());
parentStage.setScene(scene);
Controller controller = loader.getController();
On this reference you can call the appropriate method
final KeyCombination settingsCMD = new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN);
scene.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>()
{
#Override
public void handle(KeyEvent event)
{
if (settingsCMD.match(event))
{
System.out.println("CTRL + S was pressed on " + name + " display\n" +
"Opening Settings Scene");
/*
* This is where we need to launch a scene for settings
*/
try
{
FXMLLoader loader = new FXMLLoader.load(getClass().getResource("/sample/view/settingsscreen.fxml"));
Parent root = loader.load();
SettingsController controller = loader.getController();
Stage settingsStage = new Stage();
settingsStage.setTitle("Settings");
settingsStage.setScene(new Scene(root, 500 , 400));
settingsStage.show();
controller.yourMethod();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
});

Continously updating marker on running Google Map v2

I am making a tracking app that receive data(longitude and latitude) from the user via SMS and display on the googlemapv2. I want my application to work continously and the marker update on new location when a new message is received.But the marker doesn't move to new location.
I have made 2 java files. One is "IncomingSms" that receives new SMS and other is "MainActivity" that display google map and show marker.It show marker on defaultposition but don't update on new coordinates.
Please help me...here is my code..
package com.example.chck;
public class MainActivity extends Activity {
public static LatLng point;
GoogleMap gMap;
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Log.d("Activity","Got new Data again");
Toast.makeText(getApplicationContext(),"In NEW-INTENT", Toast.LENGTH_SHORT).show();
initializeMap();
drawMarker();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.MyMap)).getMap();
initializeMap();
Toast.makeText(getApplicationContext(),"In CREATE", Toast.LENGTH_SHORT).show();
// Enabling MyLocation Layer of Google Map
gMap.setMyLocationEnabled(true);
}
private void drawMarker(){
// Clears all the existing coordinates
String LON="72.99056966";
String LAT="33.64272895";
gMap.clear();
if(IncomingSms.chk==1){
Intent i1 = getIntent();
LAT = i1.getExtras().getString("NewLat");
LON = i1.getExtras().getString("NewLon");
}
Toast.makeText(getBaseContext(),LAT + LON , Toast.LENGTH_SHORT).show();
point = new LatLng(Double.parseDouble(LAT), Double.parseDouble(LON));
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
gMap.clear();
markerOptions.position(point);
// Setting title for the InfoWindow
markerOptions.title("Position");
// Setting InfoWindow contents
markerOptions.snippet("Latitude:"+point.latitude+",Longitude"+point.longitude);
// Adding marker on the Google Map
gMap.addMarker(markerOptions);
// Moving CameraPosition to the user input coordinates
gMap.moveCamera(CameraUpdateFactory.newLatLng(point));
}
private void initializeMap() {
if (gMap == null) {
gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.MyMap)).getMap();
// check if map is created successfully or not
if (gMap == null)
Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
========================
IncomingSms.java
package com.example.chck;
public class IncomingSms extends BroadcastReceiver {
public static double latitude;
public static double longitude;
public static int chk =0;
public static String la;
public static String lo;
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage
.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage
.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
String[] columns = message.split(",");
assert columns.length == 2;
longitude = Double.parseDouble(columns[0]);
latitude = Double.parseDouble(columns[1]);
la= columns[1];
lo= columns[0];
Log.i("SmsReceiver", "senderNum: " + senderNum
+ "; message: " + message);
int duration = Toast.LENGTH_LONG;
//Toast toast = Toast.makeText(context, "Latitude: "+
//longitude + ", Longitude: " + latitude, duration);
//toast.show();
} // end for loop
chk=1;
//New Location fetched
Toast.makeText(context,la + lo , Toast.LENGTH_SHORT).show();
final Intent i1 = new Intent(context, MainActivity.class);
i1.putExtra("NewLat", la);
i1.putExtra("NewLon", lo);
int duration1 = Toast.LENGTH_LONG;
//Toast toast1 = Toast.makeText(context, "Check Latitude: "+
// lo + ", Longitude: " + la, duration1);
//toast1.show();
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
}

JavaFX TreeItem string not appearing

After hours of trying i finally somewhat managed to figure out how to hook a listener to TreeItems in a TreeView, it probably isn't at all the right way to do so but hey it works so far.
Although one thing isn't, that is the "label" or better said text in the TreeItems isn't showing up anymore.
Can anyone look at my code and tell me, if i'm either doing it completely wrong or why the text isn't showing up anymore?
Thanks in advance.
Code:
TreeView<String> tree = new TreeView<>();
TreeItem<String> treeRoot = new TreeItem<>(Login.name + " - " + Login.accountType);
treeRoot.getChildren().addAll(new TreeItem<>("Branches"),
new TreeItem<>("Planning"), new TreeItem<>("Courses"),
new TreeItem<>("Add new item"));
treeRoot.getChildren().get(1).getChildren().addAll(
new TreeItem<>("2014 - Q1"), new TreeItem<>("2014 - Q2"),
new TreeItem<>("2014 - Q3"), new TreeItem<>("2014 - Q4"));
treeRoot.getChildren().get(3).getChildren().addAll(
new TreeItem<>("Branch"), new TreeItem<>("Course"));
for(String str : loadBranchData()) {
treeRoot.getChildren().get(0).getChildren().add(
new TreeItem<>(str));
}
for(String str : loadCourseData()) {
treeRoot.getChildren().get(2).getChildren().add(
new TreeItem<>(str));
}
for(int c = 0; c <= 2; c++) {
treeRoot.getChildren().get(c).setExpanded(true);
}
treeRoot.setExpanded(true);
tree.setPrefWidth(PREFWIDTH);
tree.setRoot(treeRoot);
tree.setShowRoot(true);
tree.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){
#Override
public TreeCell<String> call(TreeView<String> p) {
return new EpicTreeCell();
}
});
...
private final class EpicTreeCell extends TreeCell<String> {
#SuppressWarnings("unchecked")
super.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent evt) {
System.out.println("TEST?");
}
});
}
When the custom cell is defined, the setText() method should be called in its overridden updateItem() method.
private final class EpicTreeCell extends TreeCell<String> {
public EpicTreeCell() {
setOnMouseClicked (
new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent evt) {
System.out.println("TEST?");
}
}
);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
setText(getItem() == null ? "" : getItem().toString());
}
setGraphic(null);
}
}
See the "Custom Java-fx cellfactory messes up the setCellValueFactory" for more information.

Wicket 6 AjaxFormComponentUpdatingBehavior event working on first row of ListView but not for subsequent ones

I'm trying to handle a DropDownChoice onchange event in a listView that can display a modal window. It seems working fine for first element but not for subsequent added elements.
final ModalWindow modal = new ModalWindow("modal");
modal.setOutputMarkupId(true);
form.add(modal);
final ListView<CommandeFournisseurDetails> myView = new ListView<CommandeFournisseurDetails>(
"rowsList",
new PropertyModel<List<CommandeFournisseurDetails>>(this,
"rows")) {
#Override
protected void populateItem(
final ListItem<CommandeFournisseurDetails> item) {
final CommandeCollectionJDBC myCollection = new CommandeCollectionJDBC();
CommandeFournisseurDetails row = item.getModelObject();
item.add(new Label("index",
new AbstractReadOnlyModel<Integer>() {
#Override
public Integer getObject() {
return item.getIndex() + 1;
}
}));
final DropDownChoice<String> ID_PRODUIT = new DropDownChoice(
"ID_PRODUIT", new PropertyModel<String>(row,
"ID_PRODUIT"), myCollection.getProduit());
ID_PRODUIT.setOutputMarkupId(true);
ID_PRODUIT.setMarkupId("ID_PRODUIT");
ID_PRODUIT.setLabel(Model.of("Produit"));
ID_PRODUIT.setRequired(true);
AjaxFormComponentUpdatingBehavior behavior = new AjaxFormComponentUpdatingBehavior(
"onChange") {
protected void onUpdate(AjaxRequestTarget target) {
if (!ID_PRODUIT.getDefaultModelObjectAsString()
.isEmpty()) {
final PageParameters params = new PageParameters();
params.set("message",
ID_PRODUIT.getDefaultModelObjectAsString());
params.set("type", "Produit");
modal.setPageCreator(new ModalWindow.PageCreator() {
public Page createPage() {
// Use this constructor to pass a reference
// of this page.
return new ModalContentPage(modal, params);
}
});
modal.show(target);
target.add(modal);
target.add(ID_PRODUIT);
}
}
protected void onError(AjaxRequestTarget target,
RuntimeException e) {
System.out.println(e.toString());
}
};
ID_PRODUIT.add(behavior);
AbstractSubmitLink remove = new SubmitLink("removeRowLink") {
#Override
public void onSubmit() {
getList().remove(item.getModelObject());
getParent().getParent().removeAll();
};
}.setDefaultFormProcessing(false);
item.add(remove);
}
}.setReuseItems(true);
form.add(new SubmitLink("addRowLink") {
#Override
public void onSubmit() {
rows.add(new CommandeFournisseurDetails());
}
}.setDefaultFormProcessing(false));
myView.setOutputMarkupId(true);
form.add(myView);
Any idea why the other elements do not inherit the same event?
Thanks for your help.
All ID-PRODUIT dropdownchoices (the first, but also the rest) have the same markupId, thanks to:
ID_PRODUIT.setMarkupId("ID_PRODUIT");
Try giving them a unique MarkupId. Perhaps by adding the index of the listitem:
ID_PRODUIT.setMarkupId("ID_PRODUIT" + item.getIndex());
or remove that line of code altogether.

Resources