.setBackgroundColor() not working outside click event - java

I have a seemingly simple problem. I am working with imagebuttons inside a linearlayout which is inside a scrollview. I have set an onClickListener for one of the buttons which switches the color to red then transparent and then back again. I have tried calling performClick() and manually coding a routine to fire when a condition is met. The problem I am having is no matter how I try to do this the method(s) that are calling .setBackgroundColor() are all exiting when it's called. I don't even get to see a return statement in my Log. here is the code. I am sure this is a simple fix but I am not familiar very familiar with these things. Also I am not using any XML and would like to avoid it if possible so please keep that in mind when posting suggestions. Thanks in advance!
I will try to clarify what I am trying to accomplish. I am attempting to emulate the events that are fired during a click event WITHOUT a click event happening. I have tried this with performClick() and in the way I have here. In both cases I have the call to .setBackgroundColor() not firing and prematurely exiting the method that is calling it and it is called in.
After messing around a bit I found that the method will fire the setBackgroundColor() AND continue the method when I use Color.RED when it is already the color red. If I try any other colors it doesn't work. So it appears to not want to change the color in this fashion. Any ideas anyone?
here is the handler:
IBFireBall.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "in onClick");
if (Fireball.activated) {
Fireball.activated = false;
AbilityWidget.IBFireBall.setBackgroundColor(0);
Log.d(TAG, "was activated");
} else {
Level.fireBall = new Fireball(context);
Fireball.activated = true;
AbilityWidget.IBFireBall.setBackgroundColor(Color.RED);
Log.d(TAG, "wasn't activated");
}
}
});
here is the other method Log only prints out 1 and 2:
public static void resetButton(String id) {
if (id.equals("Fireball")) {
if (Fireball.activated) {
Log.d(TAG,"inside resetbutton 1");
Fireball.activated = false;
Log.d(TAG,"inside resetbutton2" );
AbilityWidget.IBFireBall.setBackgroundColor(0);
Log.d(TAG,"inside resetbutton4" );
} else {
Level.fireBall = new Fireball(context);
Fireball.activated = true;
AbilityWidget.IBFireBall.setBackgroundColor(Color.RED);
Log.d(TAG, "wasn't activated");
}
}
}

1. First never use "=="`` to compare Objects, use.equals()`.
2. You are Not calling the resetButton() method from the onClick(), how will this method be invoked, if its not called.

It appears that the problem lies in threading. You can't update UI outside UI thread. Case closed :) I'll link some documentation on subject later.

Related

Attempt to call getDuration in wrong state: mPlayer=0x0, mCurrentState=1 How can I solve it?

I am a novice developer trying to make an audio player on android.
On Youtube (https://www.youtube.com/watch?v=hNbXrlrWzGY&list=PL9vy4y29rrd4x5pAbowit8gpjsXAai0yF&index=8),
I did the same way I implemented it at 18:19, but it was played in Youtube video, but I didn't.
I also tried applying the content here Media Player called in state 0, error (-38,0),
but the music still doesn't play.
Here is my code.
musicPlayer = new MediaPlayer();
MediaController controller = new MediaController(this);
try {
musicPlayer.setDataSource(song.getPath());
musicPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
String duration = millisecondsToString(musicPlayer.getDuration());`
What's the difference between that YouTube and the way I did it?
Thank you.
++I invoke start() in onClick()
public void onClick(View v) {
switch(v.getId()) {
case R.id.playbtn :
if(musicPlayer.isPlaying()) {
musicPlayer.pause();
playbtn.setBackgroundResource(R.drawable.resume);
} else {
musicPlayer.start();
playbtn.setBackgroundResource(R.drawable.play);
}
break;
Firstly sorry for my English.
Are you have invoked the method: player.start() ? .
If not,You need invoked it when player prepare successed.
It may be have a listener for when prepare Ready callback.
Invoke the player.start() when received the event.
Or invoke the player.autoStart() like it.
The method name maybe not to exit but maybe similar

Vaadin grid - save/cancel when setEnableEditor= true

I'm new to vaadin and I'm a bit confused with the save and cancel button when setEditorEnabled = true.
Do you need to provide additional codes in order to save the data or it automatically saves all the data to the database when you click on save?
If there are aditional codes, how do I add a listener to the save and cancel buttons?
Thanks!
If you use buffered mode, the edited values are written to the source object when you press the Save button. If you use unbuffered mode, the edition is written instantly, so the Save and Cancel button becomes meaningless.
If you want to write the edited object back to a database, you will need to add that functionality manually. It is practical to use buffered mode in this case and add the database calling method to a method that is called when the save button is pressed.
Besides adding it to a CommitHandler's postCommit method, like Daniel Dubec writes, you can also override the saveEditor() and doCancelEditor() methods of the Grid.
class MyGrid extends Grid {
public MyGrid() {
setEditorEnabled(true);
setEditorBuffered(true);
}
#Override
public void saveEditor() throws CommitException {
super.saveEditor();
// You can persist your data here.
Notification.show("Item " + getEditedItemId() + " was edited.");
}
// Be aware that doCancelEditor() is called whenever super.saveEditor() is called!
#Override
protected void doCancelEditor() {
super.doCancelEditor();
// editedItemId was already set to 'null'.
Notification.show("Cancel button was pressed");
}
}
What super.saveEditor() does is actually calling the commit() method on the editorFieldGroup. But this is only meaningful, if the editable grid is in buffered mode. Read more on Field Buffering here.
So what happens is, when you press the save button, and super.saveEditor() is called, then first the pre-commit event is fired, then the the changes in the editor field values are updated to the data source (that is the commit itself), then the post-commit event is fired. The doCancelEditor() method is called whenever the editor itself is closed, this is why it is called after a save too.
Or use saveListener. I am not sure if this is the best way, but it works for me.
Grid<Bean> grid;
grid.getEditor().addSaveListener(new EditorSaveListener<Bean>() {
#Override
public void onEditorSave(EditorSaveEvent<Bean> event) {
// You can persist your data here
persistBean(event.getBean());
}
});
try to add CommitHandler for FieldGroup
grid.setEditorEnabled(true);
// register save listener
grid.getEditorFieldGroup().addCommitHandler(new CommitHandler() {
#Override
public void preCommit(CommitEvent commitEvent) throws CommitException {
}
#Override
public void postCommit(CommitEvent commitEvent) throws CommitException {
// You can persist your data here
Notification.show("Item " + grid.getEditedItemId() + " was edited.");
}
});

Save on change of CommandStack

probably a really easy newbie question but I can't manage to get it for already a pair of days, so I'll aks it here. My scope: I have an RCP application with some Graphical Editors (extensions of EditorPart). In my editor I want to catch any changes and save them directly. For that I catch the moment in which my CommandStack gets changed and start a doSave method. The problem is that my save method calls a CommadStack change event and if i skip this call than my changes are saved but my editor has still got a dirty flag. My wished behaviour would be that the dirty flag is away(like a normal save behaviour).
Both my CommandStack change and my doSave method are below. Could you please help me?
#Override
public void commandStackChanged(EventObject event) {
firePropertyChange(IEditorPart.PROP_DIRTY);
doSave(null);
setDirty(false);
}
public void doSave(final IProgressMonitor progressMonitor) {
editorSaving = true;
SafeRunner.run(new SafeRunnable() {
public void run() throws Exception {
IFile targetFile = getFile();
List<GraphicalEditPart> editParts = DiagramUtil.getAllEditParts(NetEditor.this);
Rectangle offsetBounds = DiagramUtil.getBounds(editParts);
saveDiagramProperties();
List<INetTransition> transitionsToExpand = saveSubdiagramGroups();
FileUtil.saveDiagram(getNetDiagram(), targetFile,
NetEditor.this);
getCommandStack().markSaveLocation();
for (INetTransition trans : transitionsToExpand) {
trans.setExpanded(true);
}
}
});
setDirty(false);
editorSaving = false;
}
With getCommandStack().markSaveLocation() I call once more the commandStackChanged and get in a loop. How can I solve this problem? Without it my editor remains dirty after save.
Thanks and Greets,
Jeff
How about adding IPropertyListener to your Editor and listen for IEditorPart.PROP_DIRTY. For the listener implementation perform save if editor is dirty otherwise do nothing.

How to ignore the mouse events except the last one in Eclipse RCP

See below for code sample, the method handleMouseDoubleClick method will take seconds to run and open another layout screen containing buttons and links. End users may click many times on one listed item in the table control and create flood of mouse events, how can I handle the last mouse event only?
Table tableControl = (Table) control;
tableControl.addMouseListener(new MouseAdapter()
{
public void mouseDown(MouseEvent e)
{
handleMouseDown(e);
}
public void mouseUp(MouseEvent e)
{
handleMouseUp(e);
}
public void mouseDoubleClick(MouseEvent e)
{
handleMouseDoubleClick(e);
}
}
Create a flag field. Set it to true when handler was called. Initialize it with false.
You just need to check whether your screen is already initialized or not before creating another one.
Set the cursor to hourglass and/or disable the table, resetting these after the new "layout screen" is closed...

How to change JButton property?

I want to change button text when i click on it, but it does not appears on the GUI. In intellje IDE i can see it is changed but why does not appear in GUI?
This is code snip:
final WebLabel loading = new WebLabel("Disconnected...", IconLib.ICON_19X17_THICK_ARROW_RIGHT_LIGHTBLUE.getIcon(), SwingConstants.CENTER);
final WebLabel ipLabel = new WebLabel(host);
final JPanel horizontalMiddlePanel = new JPanel();
final WebButton disconnect = new WebButton("Connect", IconLib.ICON_16X16_QUESTIONMARK_ON_BLUE_CIRCLE.getIcon());
disconnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (loading.getText().equals("Connected...")) {
loading.setText("Disconnected...");
loading.setIcon(IconLib.ICON_19X17_THICK_ARROW_RIGHT_LIGHTBLUE.getIcon());
disconnect.setText("Connect");
} else {
loading.setText("test");
loading.setIcon(IconLib.ICON_19X17_THICK_ARROW_RIGHT.getIcon());
ipLabel.setText(ipLabel.getText().replace(" Unreachable try again",""));
ipLabel.setForeground(Color.green);
disconnect.setText("Connecting");
callflexConnection(ipLabel, 3001, loading, disconnect);
}
}
});
than not possible without spliting code to to the two parts
1) update JButton#setText
then
2) executing rest of code
by delaing by using javax.swing.Timer
execute from SwingWorker
wrap inside Runnble#Thread,
3) this code is executed on EDT, then all changes are done on EDT, end in same/one moment
It's hard to tell if it's the source of your current problem or not, but performing logic in code based on the current text on a button is a flimsy way to do things. You should maintain that connection state in a dedicated variable. Something like this:
private enum ConnState {
CONN_DISCONNECTED,
CONN_CONNECTING,
CONN_CONNECTED,
};
private ConnState connState;
private void setConnState(ConnState connState) {
this.connState = connState;
switch (connState) {
case CONN_DISCONNECTED:
loading.setText("Disconnected");
disconnect.setText("Connect");
break;
case CONN_CONNECTING:
loading.setText(...etc...);
disconnect.setText(...);
break;
case CONN_CONNECTED:
loading.setText(...);
disconnect.setText(...);
break;
}
}
And call this when setting up the GUI to initialize the button text and connState:
setConnState(CONN_DISCONNECTED);
Then you can reason robustly about the current state of the program by checking the connState variable instead of having to synchronize button strings everywhere.

Categories

Resources