I am adapting Mario Zechner's Beginning Android Games framework to create a toddler color learning app. In the final phases of testing I have found that if the user presses and releases two different buttons at the same time (such as the 'settings' and 'home' buttons in the screenshot below) the "Colors! has stopped." notification appears.
Zechner's framework provides the handling of inputs in the form of a list which then processes each individually. I believe the issue resides in the #Override update area of code:
#Override
public void update(float deltaTime) {
world.timer = world.timer + deltaTime;
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if (event.type == TouchEvent.TOUCH_UP) {
// This is where the guts of my app are
}
}
}
The following is from LogCat showing the exception (I have noticed that the "Invalid index" will be different depending on how many touches are used but the size is alway 0):
04-24 19:27:55.239: E/AndroidRuntime(28002): FATAL EXCEPTION: Thread-555
04-24 19:27:55.239: E/AndroidRuntime(28002): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
04-24 19:27:55.239: E/AndroidRuntime(28002): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
04-24 19:27:55.239: E/AndroidRuntime(28002): at java.util.ArrayList.get(ArrayList.java:304)
04-24 19:27:55.239: E/AndroidRuntime(28002): at com.lilyandrosieshow.colors.GameScreen.update(GameScreen.java:153)
04-24 19:27:55.239: E/AndroidRuntime(28002): at com.badlogic.androidgames.framework.impl.AndroidFastRenderView.run(AndroidFastRenderView.java:42)
04-24 19:27:55.239: E/AndroidRuntime(28002): at java.lang.Thread.run(Thread.java:856)
04-24 19:28:59.301: D/dalvikvm(28002): GC_CONCURRENT freed 482K, 4% free 15473K/16071K, paused 2ms+2ms
04-24 19:32:55.262: I/Process(28002): Sending signal. PID: 28002 SIG: 9
04-24 19:32:55.262: E/AndroidRuntime(28002): Handle UnCaght exceptions. KILLING PID: 28002
I have tried to add
if (len != 0)
before the for loop but received the same results
Thank you for any and all assistance!
The "settings" and "home" buttons lead to another Screen implementation, with a call such as game.setScreen(new HomeScreen()). Inside that method, the Screen argument is updated with a delta-time of zero. If the argument Screen's update method also iterates through touch events by fetching them from the events of the game's UserInput instance, the current events list is no longer the same as the one being iterated over in the old Screen. The fix is to return immediately from any call to setScreen(). No need to continue touch processing.
#Override
public void update(float deltaTime) {
world.timer = world.timer + deltaTime;
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if (event.type == TouchEvent.TOUCH_UP) {
if (touchingHomeButton(event)) {
game.setScreen(new HomeScreen());
return; // return immediately
}
}
}
Related
I have just started exploring wxWidgets. I have a main class and a thread that accepts incoming TCP connections. When data is available on the connection I want to post an event for the main thread to handle the data. Here is some code to show what I'm doing.
// My wxFrame class
class VisorFrame : public wxFrame
{
public:
VisorFrame(wxFrame* frame, const wxString& title, const wxPoint& pos, const wxSize& size);
virtual ~VisorFrame(){};
}
VisorFrame::VisorFrame(wxFrame* frame, const wxString& title, const wxPoint& pos, const wxSize& size) :
wxFrame(frame, wxID_ANY, title, pos, size)
{
// create thread to handle TCP connections
networkThread = new NetworkThread(this->GetEventHandler(), mutexKeepRunning, &keepRunning, mutexCond, cond);
}
This is what I have in my event table:
EVT_THREAD(ID_ProcClientCmd, VisorFrame::OnProcessClientCmd)
// My worker thread class
class NetworkThread : public wxThread
{
public:
NetworkThread(wxEvtHandler* parent, wxMutex* mutexKeepRunning, bool* keepRunning, wxMutex* mutexCond, wxCondition* cond);
}
NetworkThread::NetworkThread(wxEvtHandler* parent, wxMutex* mutexKeepRunning, bool* keepRunning, wxMutex* mutexCond, wxCondition* cond) :
mutexKeepRunning(mutexKeepRunning), keepRunning(keepRunning), mutexCond(mutexCond), cond(cond)
{
}
// This is how I post my event inside my Thread class:
if (parent != NULL)
{
wxThreadEvent event(wxEVT_THREAD, ID_ProcClientCmd);
event.SetPayload((void *) pkt_info);
wxQueueEvent(parent, event.Clone());
}
else
wxPuts(_("NetworkThread: parent is NULL"));
When wxQueueEvent() gets called it throws segmentation fault. I looked at the sampled/thread.cpp code and observed that it calls wxQueueEvent() with a wxFrame pointer. When I try doing the same thing, it won't compile because wxQueueEvent expects a wxEvtHandler* as the first arg.
What am I doing wrong that is causing this seg fault?
Thanks for your help
I think the problem is this part:
wxThreadEvent event(wxEVT_THREAD, ID_ProcClientCmd);
event.SetPayload((void *) pkt_info);
wxQueueEvent(parent, event.Clone());
wxQueueEvent calls wxEvtHandler::QueueEvent() and the documentation for that method states:
this method takes ownership of the event parameter, i.e. it will
delete it itself
So you should create the event with the new operator use that pointer like so:
wxThreadEvent* event = new wxThreadEvent(wxEVT_THREAD, ID_ProcClientCmd);
event->SetPayload((void *) pkt_info);
wxQueueEvent(parent, event);
At first I am not used to develop apps. Until now I only used LWJGL for computer games, so don't be too strict to me :)
I tried to implement a VAO class, which cares about all this VAO stuff (loading VAO's, VBO's, binding indices buffers etc.)
The problematic code snippet is the one in the bindIndicesBuffer(int[] indices) function.
Vao.java:
private void bindIndicesBuffer(int[] indices){
int vboID =genBuffers();
vbos.add(vboID);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, vboID);
IntBuffer buffer = Tools.makeIntBuffer(indices);
GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, indices.length*4, buffer, GLES20.GL_STATIC_DRAW);
}
Additional Code:
private int genBuffers(){
int[] ids = new int[1];
GLES20.glGenBuffers(1, ids, 0);
return ids[0];
}
Tools.java:
public static IntBuffer makeIntBuffer(int[] arr){
ByteBuffer bb = ByteBuffer.allocateDirect(arr.length *4).order(ByteOrder.nativeOrder());
IntBuffer ib = bb.asIntBuffer();
ib.put(arr);
ib.position(0);
ib.flip();
return ib;
}
The Main activity class calls a sub class of GLSurfaceView, which creates the MasterRenderer which implements GLSurfaceView.Renderer and calls the render methods of the seperate renderers in onDrawFrame();
I get the following error:
E/libEGL: call to OpenGL ES API with no current context (logged once per thread)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
...
Caused by: java.lang.IllegalArgumentException: remaining() < size < needed
At the line "GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, indices.length*4, buffer, GLES20.GL_STATIC_DRAW);"
And now the magic question: what did I do wrong? :D
Thank you for your time!
I have Status Bar Cocoa App that provides GUI with general information and preferences windows for my background running server. This server is implemented in C programming language and the only work it is doing now is simple echo to client.
Application has button that starts this server. When I press this button server starts and listens on randomly selected port. It works correctly, I can even restart server etc.
I start server using this code:
- (void) startServerInBackground: (server_t) serverFunc {
dispatch_queue_t server_dispatch_queue = dispatch_queue_create("click.remotely.Server", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(server_dispatch_queue, ^(void){
start_server(serverFunc, serverInfo);
/***
* dispatch_async(dispatch_get_main_queue(), ^(void){
* //Run UI Updates
* });
*/
});
}
The problem begins only when some client connects to the server.
I can connect using telnet 192.168.8.101 <PORT_NUMBER>. I can even talk to server and it replays correctly. Here the odd things happens!
When I try to open Status Bar Cocoa App I can get crashes like this:
1. No crash for very long time (client talking to server, restarting, switching windows and panes)
2. Get crash immediately after connecting client and selecting Status Bar Icon of App
3. Get crash some time later when I connect client, open Status Bar Icon, select some Menu Item and try to Open window.
4. The app can also crash a little later ex. not on first window opening but third, fourth or n-th window opening, button clicking.
Below screenshot shows how this nondeterministic looks
What causes the app to crash? How can I resolve this issue?
Here is my server loop in C
/**
* Function is looping infinitely and waiting
* for new incoming client connections.
* It handles connections one by one on the same thread.
*/
result_t iterative_stream_server_loop(server_info_t *server_info, connection_handler_t handle_connection) {
sock_fd_t cs_fd, ps_fd;
// get passive server socket
ps_fd = server_info_sock(server_info);
while(1) {
if(server_info_should_shut_down(server_info)) {
return CLOSED;
}
if(server_info_force_shut_down(server_info)) {
return FORCE_CLOSED;
}
// check to accept new connection on the main thread...
cs_fd = accept_new_connection(ps_fd);
if(cs_fd == FAILURE) {
fprintf(stderr, "accept_new_connection: failed!\n");
server_info_connection_error_event(server_info, cs_fd, CONN_ERROR_ACCEPT, "accept_new_connection: failed!");
return FAILURE;
} else if(cs_fd == CONTINUE) {
continue;
}
// publish client connected event
server_info_client_connected_event(server_info, cs_fd);
printf("Handle connection on the main thread...\n");
switch (handle_connection(server_info, cs_fd)) {
case FAILURE:
fprintf(stderr, "handle_connection: failed!\n");
// publish connection error event
server_info_connection_error_event(server_info, cs_fd, CONN_ERROR_HANDLER, "handle_connection: failed!");
break;
case CLOSED:
printf("handle_connection: closed!\n");
// publish client disconnecting event
server_info_client_disconnecting_event(server_info, cs_fd);
break;
default:
break;
}
if(close(cs_fd) < 0){
fprintf(stderr, "close: %s\n", strerror(errno));
server_info_connection_error_event(server_info, cs_fd, CONN_ERROR_CLOSE, strerror(errno));
return FAILURE;
}
}
}
And here is the client connection handling (echo service)
result_t echo_service_connection_handler(server_info_t *server_info, sock_fd_t sock_fd) {
char buf[MAX_BUF_SIZE];
int n_recv; // number of bytes received
int n_sent; // number of bytes sent
fcntl(sock_fd, F_SETFL, O_NONBLOCK);
while(1) {
if(server_info_should_shut_down(server_info))
return CLOSED;
if ((n_recv = recv(sock_fd, buf, sizeof(buf) - 1, 0)) <= 0) {
if(n_recv == 0) {
printf("echo connection is closing...\n");
return CLOSED;
}
if( (errno == EAGAIN) || (errno == EWOULDBLOCK)) {
// call to recv() on non-blocking socket result with nothing to receive
continue;
}
perror("recv");
// publish connection error event
server_info_connection_error_event(server_info, sock_fd, CONN_ERROR_RECV, strerror(errno));
return FAILURE;
}
buf[n_recv] = '\0';
printf(ANSI_COLOR_BLUE "server: received '%s'" ANSI_COLOR_RESET "\n", buf);
if ((n_sent = send(sock_fd, buf, strlen(buf), 0)) < 0) {
perror("send");
// publish connection error event
server_info_connection_error_event(server_info, sock_fd, CONN_ERROR_SEND, strerror(errno));
return FAILURE;
}
}
return SUCCESS;
}
I'm trying to debug a charm project. I've set break points in the code, but each time execution reaches a break point, Netbeans freezes and I'm obliged to forcefully close it.
For what it's worth, I'm using Ubuntu 15.04
[Edit 1]
Here's an image of a set break point
I am getting an exception:
Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException
that doesn't point to any line in my code, so I want to debug and get what is causing the problem. Immediately the code gets to line 106, everything freezes.
[Edit 2]
Ok here's most of the controller code.
public void initialize(URL url, ResourceBundle rb) {
departmentList.setPlaceholder(new Label("Oops!! EMPTY!!!"));
/*
Populate SideMenu
*/
ObservableList<Label> schools = FXCollections.observableArrayList();
ListView<Label> schoolList = new ListView<>(schools);
for (School school : schoolsList) {
schools.add(new Label(school.getName(), MaterialDesignIcon.ACCOUNT_BALANCE.graphic()));
}
/*
Add Listeners to side Menu ListView
*/
schoolList.getSelectionModel().selectedItemProperty().addListener(
(ObservableValue<? extends Label> observable, Label oldValue, Label newValue) -> {
selectedSchool = parser.findSchool(newValue.getText());
loadDepartments();
MobileApplication.getInstance().hideLayer("Side Menu");
});
/*
Add Listener to departments ListView
*/
departmentList.getSelectionModel().selectedItemProperty().addListener(
(ObservableValue<? extends Label> observable, Label oldValue, Label newValue) -> {
if (newValue == null) {//Got fired by clearing the Observable list
return;
}
System.out.println(newValue);
facDept[1] = newValue.getText();
/*
Reset before leaving; *to be removed and tried on mobile
*/
loadDepartments();
MobileApplication.getInstance().switchView(SEMESTER_VIEW);
});
borderPane.setCenter(schoolList);
center.getChildren().add(departmentList);
}
#FXML
private void showLayer(ActionEvent event) {
MobileApplication.getInstance().showLayer("Side Menu");
}
I set a break point in the showLayer method(MobileApplication...), and debugging works. I set another one the line selectedSchool = parser.findSchool(newValue.getText());, but here debugging freezes. Note that the exception doesn't occur here.
I'am very new to threading and quite unclear as to why this is happening in my code, when I click on a button that verifies hyperlinks in my document, I start a new thread that does the verification once it starts I want to disable the ribbon button and enable it again after thread finished but this is not happening and I dont know what is the mistake .Here is what I have tried so far:
public class Alpha :Ribbon1
{
// This method that will be called when the thread is started
public void Beta()
{
foreach() { //do something } after this loop ,enable the button again
button.enable=true //not applying
} }
private void button_Click(object sender, RibbonControlEventArgs e)
{
Alpha oAlpha = new Alpha();
// Create the thread object, passing in the Alpha.Beta method
Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
// MessageBox.Show("Please wait till the document is checked for invalid links");
// Start the thread
oThread.Start();
button7.Label = "Pls wait";
button7.Enabled = false;
}
Ribbon needs to be rendered again after enable/disable for change to take effect, you can do this by calling IRibbonUI.Invalidate()