How to translate multiple objects with Translator - java

I need to translate the text that comes to the screen from the database with each new button click. I know that there is a method
Translator.translate(answerThree.getText().toString())
.addOnSuccessListener(
translatedText -> answerThree.setText(translatedText))
.addOnFailureListener(
e -> answerThree.setText(e.toString()));
which will put the translated text in the radio button. This is good. But what if I need to translate 4 objects?
Do I have to rewrite the above action every time but for a different object? Is it possible to make the translation of everything that I need more compactly?
I tried to create a method that would return me a string with the translated text, but I just can't return the string when it comes to checking whether the translation was successful.
I can't declare the final variable because it will change, and without that I can't assign a value to the result variable. I don't really know how best to solve the problem.
private String getTranslateText(String s) {
Stringresult;
englishRUSSIANTranslator.translate(s)
.addOnSuccessListener(
new OnSuccessListener<String>() {
#Override
public void onSuccess(#NonNull String translatedText) {
result = translatedText; // error Variable 's' is accessed from within
// inner class needs to be final or effectively final
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
result = e;
}
});
return result;

Related

Emitting 2 observables, processing the result and then emitting another one

I have the following task to perform:
I need to emit 2 observables (obs1 & obs2) process their results and then call another observable (obs3) and process its results and if possible that while processing the results of obs3 have access to the results of obs1 and obs2.
This is my draft code which doesn't do the trick, how can I alter it.
public void executeFind(String session_id, long template_id, GameModelType game_model) {
Observable<RxMessage<byte[]>> userObs = context.getUser(session_id);
Observable<Game> gameObs = context.findGame(template_id, game_model, GameStateType.WAITING);
Observable.zip(userObs, gameObs, new Func2<RxMessage<byte[]>, Game, GameObject>() {
#Override
public GameObject call(RxMessage<byte[]> userRawReply, ActiveGame game) {
..
..
return context.updateGame(game.getGameData())
.subscribe(new Action1<GameObject>() {
#Override
public void call(GameObject updateReply) {
..
..
}
});
return userReply;
}
});
}
This doesn't really work - I can write a code which uses explicit calls to .flatMap\subscribe for each Observable but results in many nested calls which is obviously poor usage of the framework.
What is the right way to solve this??
Thank you!
EDIT:
I've found this solution to work, but I'm still wondering whether there is a "cleaner" way to achieve this:
public void executeFind(ReplyMessage<JsonObject> replyObj, String session_id, long template_id, GameModelType game_model) throws CommandException {
rx.Observable<GameObject> userObs = context.getUser(session_id);
rx.Observable<Game> gameObs = context.findGame(template_id, game_model, GameStateType.WAITING);
rx.Observable.zip(userObs, gameObs, new Func2<GameObject, Game, List<Object>>() {
#Override
public List<Object> call(GameObject userReply, Game game) {
User user = ...;
final List<Object> results = new ArrayList<Object>(3);
results.add(ErrorCodes.STATUS_OK);
results.add(user);
results.add(game);
context.updateGame(game.getGameData()).subscribe(new Action1<GameObject>() {
#Override
public void call(GameObject updateReply) {
...
}
});
return results;
}
}).subscribe(new Action1<List<Object>>() {
#Override
public void call(List<Object> results) {
int status = (int) results.get(0);
User user = (User) results.get(1);
Game game = (Game) results.get(2);
}
});
}
I would code this thing with the following idea in mind. May be map can be replace with flatMap if that's relevant for your use case. Also note I have only used Java 8 lambdas syntax, but for more readability I strongly advises you to have simple and well named methods (and use them with a method reference) for each of these functions/actions as it will raise understandability of the code (That's what we do on mockito, but everyone should do it in their own code base).
public void executeFind(ReplyMessage<JsonObject> reply_obj, String session_id, long template_id, GameModelType game_model) throws CommandException {
Observable<GameObject> userObs = context.getUser(session_id);
Observable<Game> gameObs = context.findGame(template_id, game_model, GameStateType.WAITING);
Observable.zip(userObs, gameObs, (userReply, game) -> {
User user = ...;
return GameOfUser.gameFound(game, user);
}).map(gou -> {
context.updateGame(gou.gameData()).susbcribe(...);
return gou;
}).subscribe(gou -> ...);
}

Why behaviour stop working with propertyModel inside autocompleteField

In my application I have autocompleteTextField. I need to get id of player when text in input changed. I am trying to play with models which are recommended by this question: using AutoCompleteTextField in wicket without String as the generic type but with no success. Behaviour stop working when I use PropertyModel or when I set class Player.class instead of null. I dont understand why.
final AutoCompleteTextField<Player> playersField = new AutoCompleteTextField<Player>("players",
new Model<Player>(selectedPlayer), null, new AbstractAutoCompleteRenderer<Player>() {
#Override
protected void renderChoice(Player player, Response response, String criteria) {
response.write(getTextValue(player));
}
#Override
protected String getTextValue(Player player) {
return player.getName() + " " + player.getSurname() + " "
+ player.getPlayerDiscriminator();
}
}
, settings) {
#Override
protected Iterator<Player> getChoices(String prefix) {
List<Player> choices = getPlayers();
return choices.iterator();
}
};
add(playersField);
playersField.add(new AjaxFormComponentUpdatingBehavior("onchange") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
System.out.println("do something");
// All I need here is just Id of player
}
}
});
From the question you linked to:
You probably already know this but if your custom class is really custom, you'll also need an IConverter that handles the String<->Someclass conversions: you can either register it with the application or override your component's getConverter(Class clazz ) method to return it.
Did you do that?
Also, if this doesn't fix the problem, please describe how it "stops working" in more details.

How do I get a certain value from a row in vaadin?

This is the problem, I have a vaadin table that represent people information (for example) and when someone clicks on a row I want to extract the cellphone number.
Here is part of the code of the listener:
table_2.addListener(new ItemClickEvent.ItemClickListener() {
#Override
public void itemClick(ItemClickEvent event) { // TODOAuto-generated // method stub
String resultado = (table_2.getItem((Object)event.getItemId()))
+ "";
resultado = resultado.substring(resultado.indexOf("phone"),
resultado.indexOf("|weight"));
label_3.setValue(resultado);
}
});
It worked one time but now it doesn't. The code returns a Null, so when I try to parse the object to string it crash.
Try the following:
table.addListener(new ItemClickListener() {
#Override
public void itemClick(ItemClickEvent event) {
Property itemProperty = event.getItem().getItemProperty("cellphone");
itemProperty.getValue(); // TODO: Do something with this value.
}
});

How to get reference to an anonymous object 2 levels up

I have code like this:
TextBox txt = new TextBox(){
public void onLoad(){
this.addFocusHandler(new FocusHandler(){
//some codes here
//if I use "this" keyword, it refers to the handler, but how can I get a reference to the textbox?
});
}
};
Question is embedded in the position.
Edit:
In respect to the answers, the creation of a pre-defined reference works for this situation, but this apparently lost (or at least reduce) the benefits of anonymous object/function.
I hope to find a way without creating a new reference. Rather just to get the reference from that scope.
After all the answers, here is a conclusion:
Reflection does not work in GWT. (at least I did not succeed) obj.getClass() works, but others like getMethods() or getEnclosingClass() don't work.
The way to get a reference can either be declaring a reference in the right scope, or get a higher level object reference and reference downwards. I prefer the latter simply because you don't need to create a new variable.
TextBox txt = new TextBox(){
public void onLoad(){
final TextBox finalThis = this;
this.addFocusHandler(new FocusHandler(){
finalThis.doSomething();
);
}
};
The enclosing instance of a non-static inner class (anonymous or named) in Java is available as ClassName.this, i.e.
TextBox txt = new TextBox(){
public void onLoad(){
this.addFocusHandler(new FocusHandler(){
doSomethingCleverWith(TextBox.this);
});
}
};
This has worked for me in the past. It works in client side js too. Here is a reference to more detail
What is the difference between Class.this and this in Java
public class FOO {
TextBox txt = new TextBox(){
public void onLoad(){
this.addFocusHandler(new FocusHandler(){
#Override
public void onFocus(FocusEvent event) {
FOO.this.txt.setHeight("100px");
}
});
}
};
}
This may work for you:
TextBox txt = new TextBox(){
public void onLoad(){
final TextBox ref = this;
this.addFocusHandler(new FocusHandler(){
public void doSomething(){
//some codes
ref.execute();
}
});
}
};
But I prefer to migrate inner classes to named classes:
public class Test {
public void demo(){
TextBox txt = new TextBox(){
public void onLoad(){
this.addFocusHandler(new DemoFocusHandler(this));
}
};
}
}
External FocusHandler:
public class DemoFocusHandler extends FocusHandler {
private TextBox textBox;
public DemoFocusHandler(TextBox textBox){
this.textBox = textBox;
}
public void doSomething(){
//some codes
textBox.execute();
}
}
If gwt supported reflection you could do something along the lines of this:
final TextBox txt = new TextBox() {
public void onLoad() {
final Object finalThis = this;
this.addFocusHandler(new FocusHandler() {
#Override
public void onFocus(FocusEvent event) {
try {
Method method= finalThis.getClass().getMethod("getVisibleLength");
method.invoke(finalThis);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
Without reflection the existing answers are you best bet. There are two gwt reflection projects gwt reflection and gwt-preprocessor both are in beta and I have not tried them.

pass class name via context and use it to store static value in different class

The dialogue and the array displays just fine, I just want to be able to set the static variable from the originating class within the onClick that is in a method that is in a different class. All of the try, catch and
<?> were things that I put in at the insistence of the compiler:
public class Setter
{
public void myList(Context context, Class<?> thisclass, int arrayid, String choice)
{
return new AlertDialog.Builder(context)
.setItems(arrayid, new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
setChoice(thisclass, context, arrayid, which, choice);
}
})
.create();
}
public void setChoice(Class<?> thisclass, Context context, int arrayid, int which, String choice)
{
String[] array = context.getResources().getStringArray(arrayid);
try
{
Field f = thisclass.getDeclaredField(choice);
f.set(null, array[which]);
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}
public class ClassA extends Activity
{
static String stringa;
Setter setted = new Setter();
...
public void onCreate()
{
super.onCreate();
...
AlertDialog thinga = setted.myList(this, getclass(), R.array.thinga, stringa).show();
...
}
}
When I select an item from the list, I get this from debugger:
ClassCache.findFieldByName(Field[], String) line: 438
Class.getDeclaredField(String) line: 666
Setter.setChoice(Class, Context, int, int, String) line: 45 // the line with the Field
I think I'm passing it the class wrong but this is a bit out of my current depth.
I have a number of different classes each with their own static Strings. I am passing the method below the name of the String (in choice) and the context of what I had hoped was the original class that called a method that called a method that led to the code below. I was hoping I could call context.choice = something and the machine would read that as ClassA.stringa = something; how do I do that?
Briefly, I want to have a list of items that the user can choose from be the content of a dialogue, and have their selection be saved and accessible to the class that called for the creation of the dialogue. Perhaps I'm going about this all wrong but I got tired of dealing with other 'kludges' involving using spinners to do the same thing.
Because onClick can't have non-final objects declared elsewhere (at least that is my understanding) I thought maybe I could get around that by calling to another method, setChoice that would store the value of whatever was chosen. I would definitively say this is a kludge and would love to be shown the light as to how you are supposed to deal with these things.
Java does not have closures, but you can get close with anonymous inner classes.
String output;
public void onCreate() {
Setter.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
output = "selected";
}
});
}
See also this swing tutorial: http://download.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Edit:
In spirit of your example, this should look like this:
public class Setter
{
public void setChoice(IsetString setter, String something)
{
setter.setString(something);
}
}
class ClassA extends Activity implements setString
{
static String stringa;
string polka = "dots";
Setter setted = new Setter();
...
public void onCreate()
{
super.onCreate();
...
setted.setChoice(new IsetString() {
#Override
public void setString(String s) {
stringa = s;
}
}, polka);
...
}
}
interface IsetString {
void setString(String s);
}
The short answer - use the Reflection API.
The long answer - you'll need to obtain access to the Fields of the desired Context Class. Once you gain access to the Field instances, you can set their values using the set() method; the API call is a bit tricky in that you'll need to pass in the object reference (the context object and not the context class) whose field you wish to modify.
It is necessary that your Context, choice and something parameters to the method, contain the necessary information to make this operation as simple as possible. In other words, the Context class might have to contain the actual Class object (or provides a way to get one) that contains the field.
You can use reflection for that. Suppose you context is class itself
public void setChoice(Class<?> context, String choice, String something)
{
try {
Field f = context.getDeclaredField(choice);
f.set(null, something);
} catch (....) {
}
}
Add proper exception handling
Note that first argument to set is null. That is only valid for static methods. So you may want to check that method is static using f.getModifiers().

Categories