0

I have an app in swift where I created a class ApiRequest to handle all my calls to the API, so I don't have any logic in the UI, I just return objects which I use to populate my views.

I would like to do the same in java, but for what I understand there are no anonymous functions or closures like in swift, but only anonymous objects that implement an interface. So I'm trying to convert my swift class into a java one using these concepts, volley and possibly GSON libraries, but I'm not sure how to do that exactly, or even if it makes sense in java.

Here is my swift class:

class ApiResponse {
    var success: Bool = false
    var message: String = ""
    var data: AnyObject!
}

//The wrapper
class queryAPI {

    var hostname = APP_DELEGATE.hostname

    func requestAPI(url:String, params:String, completion: (ApiResponse) -> ()) {

        let session = NSURLSession.sharedSession()
        let urlStr = hostname+url

        var request = NSMutableURLRequest(URL: NSURL(string:urlStr )!)
        request.HTTPMethod = "POST"

        request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)
        var out = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding)

        request.addValue("XMLHTTPRequest", forHTTPHeaderField: "X-Requested-With")
        request.addValue("KaliMessenger", forHTTPHeaderField: "User-Agent")

        var task = session.dataTaskWithRequest(request){
            (data, response, error) -> Void in

            var res = ApiResponse();

            if error != nil {
                res.success = false
                res.message = error.localizedDescription
                res.data = nil;

                println(error.localizedDescription)

            }
            else {

                var error: NSError?
                println("Performing request: "+urlStr)
                if let  jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary //return a dictionnary with a list of indexes (array)
                {

                    res.success = jsonResult["success"] as! Bool;
                    if(res.success)
                    {
                        res.message = "";
                        res.data = jsonResult["data"]
                    }
                    else
                    {
                        res.message = jsonResult["msg"] as! String;
                        res.data = nil
                    }
                } else {
                    //when we do not manage to get the result, we display the url called, what we have received, and set the response to false
                    var dataContent = NSString(data: data, encoding: NSASCIIStringEncoding);
                    println("Error decoding JSON: ")
                    println(dataContent)
                    res.message = "error decoding json response"
                    res.data = nil
                    res.success = false
                }

            }

            //we return our items to the main thread
            let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
            dispatch_async(dispatch_get_global_queue(priority, 0)){

                dispatch_async(dispatch_get_main_queue()){

                    completion(res)

                }

            }

        }

        task.resume()

    }

     //an example of a function using the wrapper
     func conversationList(completion: ([ModelConversation]) -> ()) {

        self.requestAPI("owapi/messenger/conversationList", params: "") { (res: ApiResponse) -> () in
            var items = [ModelConversation]() //TODO error checking

            if(res.success)
            {
                var data = res.data as! NSArray

                for item in data{
                    let item = ModelConversation(data: item as! NSDictionary)
                    items.append(item)
                }
            }
            completion(items)
        }

    }

}

Then I call the function in the controller like this:

query.allUsers(String(self.first), completion: { (users:[ModelUser]) -> () in
        self.users = users
        self.collectionView.reloadData()
    })

And what I have so far in java:

public class QueryAPI {

    public class ApiResult
    {
        public Boolean success;
        public String message;
        public Object data;
    }

    public interface ApiResponse<ApiResult>
    {
        public void onCompletion(ApiResult result);
    }

    public void requestApi( String url, final ApiResponse<ModelConversation> completion  )
    {

        JsonObjectRequest apiRequest = new JsonObjectRequest(Request.Method.GET, url, (JSONObject) null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response)
            {

                Log.v("Data: ", response.toString());
                try {
                    Boolean success = response.getBoolean("success");
                    Log.v("Success: ", success.toString());
                    JSONArray data = response.getJSONArray("data");
                    Log.v("DataArray: ", data.toString());
                    ApiResult res = new ApiResult();
                    res.success = success;
                    res.data = data;
                    completion.onCompletion(res);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }
        );
    }

}

Any advice, links, tips or code would be awesome!

Kalianey
  • 2,738
  • 6
  • 25
  • 43
  • I don't know your need is the same as mine or not, however, you can have a read at my last answer [Android/Java: how to delay return in a method](http://stackoverflow.com/questions/31602042/android-java-how-to-delay-return-in-a-method) – BNK Aug 11 '15 at 09:23
  • 1
    Thank you for your answer, I'm having a look – Kalianey Aug 11 '15 at 10:18

0 Answers0