Skip to content Skip to sidebar Skip to footer

Inner Class With Global Variable

I want to check if the user liked post or not, so I wrote this function and it needs to return boolean value. Any trick or hint would be appreciated. Thanks so much, everyone. p

Solution 1:

Do this:

PLEASE SEE EDIT BELOW

Create a listener interface so we can listen for our response.

publicinterfaceRequestResponseListener{
    voidonResponse(boolean posted);
}

Modify your method to include a listener parameter and utilize that listener to send your response.

publicvoid imLike (String url, final RequestResponseListener listener){ 
    requestQueue = Volley.newRequestQueue(context);
    requestQueue.start();
    StringRequest request = newStringRequest(Request.Method.GET, url, newResponse.Listener<String>() {
        @OverridepublicvoidonResponse(String response) {
               listener.onResponse(response.equals("yes")));
        }
    }, newResponse.ErrorListener() {
        @OverridepublicvoidonErrorResponse(VolleyError error) {
            Log.e("Vollley Error", "Error ");
            listener.onResponse(false);
        }
    });
    requestQueue.add(request);
}

Then to make the call and listen for a response.

imLike([some_url], newRequestResponseListener(){
    @OverridepublicvoidonResponse(boolean posted){
        // do what you wanted to do with the response
    }
});

This is the basic concept behind Listeners. They are very useful for multi-threading/asynchronous tasks.

EDIT

I should have looked at what I was actually answering a bit more. You are making a volley request, and Volley provides its own listeners. What you need to do is this.

publicvoidimLike(String url, Response.Listener<String> listener, Response.ErrorListener errorListener){
    requestQueue = Volley.newRequestQueue(context);
    requestQueue.start();
    StringRequest request = newStringRequest(Request.Method.GET, url, listener, errorListener);
    requestQueue.add(request);
}

And then make the request as so

imLike([some_url], newResponse.Listener<String>(){
        @OverridepublicvoidonResponse(String response) {
            if(response.equals("yes")){
                // do what you want if it is yes
            }
            else{
                // do what you want if it is no
            }
        }
    }, newResponse.ErrorListener() {
        @OverridepublicvoidonErrorResponse(VolleyError error) {
        Log.e("Volley Error", "Error ");
        }
    }
}

It is also noted that you should probably handle initializing your VolleyQueue in a separate way, as you are creating a new queue every time you make this call. You should have a single instance for your application so that it actually creates a queue.

Post a Comment for "Inner Class With Global Variable"