Nexon Isdumb
Nexon Isdumb

Reputation: 57

How to return httpResponse result LIbGDX

So I have been trying to return the content grabbed from httpResponse from a class, however, im not very successful at the moment.

    String requestContent = null;
    Net.HttpRequest httpRequest;
    httpRequest = new Net.HttpRequest(Net.HttpMethods.GET);
    httpRequest.setUrl("https://api.parse.com/1/classes/gamerooms/");
    System.out.println(Parse.getRestAPIKey() + Parse.getApplicationId());
    httpRequest.setHeader("X-Parse-Application-Id", Parse.getApplicationId());
    httpRequest.setHeader("X-Parse-REST-API-Key", Parse.getRestAPIKey());
    httpRequest.setContent(requestContent);

    Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {


        @Override
        public void handleHttpResponse(Net.HttpResponse httpResponse) {
            content = httpResponse.getResultAsString();
        }

        @Override
        public void failed(Throwable t) {

        }

        @Override
        public void cancelled() {

        }
    });
    return content;
}

When I return content, it is empty but when i print the content in handleHttpResponse, i can see it there. Any solutions?

Upvotes: 2

Views: 944

Answers (1)

Quallenmann
Quallenmann

Reputation: 323

The problem is, that it is handled like a Thread. So when you're returning the content, the answer maybe not already arrived. So you must handle the result in the handleHttpResponse method. If you don't want all the code in that method, you could also call a function.

Also because you're in a Thread I think you should call Gdx.app.postRunnable(Runnable runnable) if you want to change something in the code, which you shouldn't while you are in the render method or need OpenGL context. The Runnable will be called directly before the render method. Threading libGdx

Upvotes: 3

Related Questions