简体   繁体   English

如何使我的代码成为同步 POST volley 请求?

[英]How can I make my code a synchronous POST volley request?

I'm building a tracking app for exercise.我正在构建一个用于锻炼的跟踪应用程序。 As the gps updates every 1 second, the latitude and longitude is added to an array.由于 gps 每 1 秒更新一次,因此将纬度和经度添加到数组中。 At the end of the exercise, when you press save, below method is executed, sending all co-ordinates to a database.在练习结束时,当您按下保存时,将执行以下方法,将所有坐标发送到数据库。 Because it's an asynchronous request, the co-ordinates don't get loaded into the database in correct order.因为它是一个异步请求,所以坐标不会以正确的顺序加载到数据库中。 How can I fix this so it will wait until each iteration of loop is complete or something like that.我该如何解决这个问题,所以它会等到循环的每次迭代完成或类似的事情。 Thanks谢谢

/* Inserts the latitude and longitude points from the latitudeAndLongitudePoints ArrayList into the latitudeandlongitudepoints table in db*/ /* 将latitudeAndLongitudePoints ArrayList中的经纬度点插入db中的latitudeandlongitudepoints表*/

private void insertLatitudeAndLongitudePoints(){私人无效插入纬度和经度点(){

    //iterates though array of co-ordinates, and adds to database
    for(int loop=0; loop<latitudeAndLongitudePoints.size();loop++) {

        final int index = loop;

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                "http://rrush01.lampt.eeecs.qub.ac.uk/insertLatitudeAndLongitudePoints.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();

                params.put("Latitude", String.valueOf(latitudeAndLongitudePoints.get(index).latitude));
                params.put("Longitude", String.valueOf(latitudeAndLongitudePoints.get(index).longitude));
                params.put("User", AccountInfo.accountEmail);

                return params;
            }
        };

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(stringRequest);
    }
}

Add dependency for Volley library in your build.gradle.在 build.gradle 中添加 Volley 库的依赖项。

compile 'com.android.volley:volley:1.0.0'

Volley is a network library which makes fast and easier to make HTTP Request for android application. Volley 是一个网络库,它可以让 HTTP 对 android 应用程序的请求变得更快更容易。 Using Volley library we don't need to create AsyncTask to make multiple API calls in volley there is RequestQueue where we can enqueue each request.使用 Volley 库,我们不需要创建 AsyncTask 来在 volley 中进行多个 API 调用,我们可以在 RequestQueue 中将每个请求排入队列。 Here in this example, We used Google place autocomplete API.在此示例中,我们使用了 Google 放置自动完成 API。 We are going to make synchronous HTTP Request using volley.我们将使用 volley 发出同步 HTTP 请求。 To make synchronous HTTP request make a RequestFuture object.要发出同步 HTTP 请求,请发出 RequestFuture object。 And make JsonObjectRequest pass this parameter RequestMethod, URL, pass object of type Json and pass RequestFuture instance.并使JsonObjectRequest传递这个参数RequestMethod,URL,传递Json类型的object,传递RequestFuture实例。

    RequestFuture<JSONObject> requestFuture=RequestFuture.newFuture();
    final String mURL = "https://maps.googleapis.com/maps/api/place/
    autocomplete/json?key="+KEY+"&input=" + input;
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
    mURL,new JSONObject(),requestFuture,requestFuture);
    MySingleton.getInstance(mContext).addToRequestQueue(request);

Add your request in RequestQueue.在 RequestQueue 中添加您的请求。 Now, whenever the user makes an HTTP request each request added to RequestQueue.To get response object from the requestFuture we call get() method.现在,每当用户发出 HTTP 请求时,每个请求都会添加到 RequestQueue。为了从 requestFuture 获取响应 object,我们调用 get() 方法。 And we also set a timeout of let's say 10 seconds so we don't block the UI thread indefinitely in case our request times out.我们还设置了一个超时时间,比如说 10 秒,这样我们就不会无限期地阻塞 UI 线程,以防我们的请求超时。

try {
        JSONObject object= requestFuture.get(10,TimeUnit.SECONDS);
    } catch (InterruptedException e|ExecutionException e|TimeoutException e) {
        e.printStackTrace();
    }

Hope this helps you to understand how we can use volley used to make the synchronous HTTP request希望这可以帮助您了解我们如何使用 volley 来发出同步 HTTP 请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM