Android Volley在节点服务器的最后一次响应之前得到一个

时间:2018-01-23 22:10:46

标签: android node.js android-volley

这是我的代码:

 Observable<String> observable = Observable.create(
            new ObservableOnSubscribe<String>() {
                @Override
                public void subscribe(final  ObservableEmitter<String> e) throws Exception {

                    MyRequestQueue = Volley.newRequestQueue(PlanActivity.this);

                    String url = AppConfig.BASE_URL + "/api/v1/getPlan/" + planId;
                    // Request a string response from the provided URL.

                    StringRequest strRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {

                                @Override
                                public synchronized void onResponse(String response) {

                                    Log.e("plan response is", "" + response);

                                    AppConfig.indexJson = response;

                                    e.onNext(response);
                                    e.onComplete();

                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Log.e("Error in request ", "=>" + error);
                                    e.onNext(error.toString());
                                    e.onComplete();
                                    MyRequestQueue.cancelAll(this);
                                }
                            }) {
                        @Override
                        public Map<String, String> getHeaders() {
                            HashMap<String, String> headers = new HashMap<>();

                            headers.put("x-access-token", AppConfig.token);

                            return headers;
                        }
                    };

                    strRequest.setRetryPolicy(new DefaultRetryPolicy(
                            400000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

                    strRequest.setTag(TAG);
                    // Add the request to the RequestQueue.
                    MyRequestQueue.add(strRequest);

                }
            }
    );

    Observer<String> observer = new Observer<String>() {
        @Override
        public synchronized void onSubscribe(Disposable d) {
            Log.i(TAG, "onSubscribe");
        }

        @Override
        public synchronized void onNext(String response) {
            Log.i(TAG, "onNext: " + response);
            setUiElement(response);

        }

        @Override
        public void onError(Throwable e) {
            Log.i(TAG, "Oops! Something happened");
        }

        @Override
        public void onComplete() {

            donateBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(getApplicationContext(), PaymentActivity.class);
                    intent.putExtra("planId", planId);
                    getApplicationContext().startActivity(intent);
                }
            });

        }
    };

    observable.subscribe(observer);
}

boolean first = true;
public Timer timer;

public synchronized void setUiElement(String json) {
    try {

        loading.setVisibility(View.GONE);
        Gson gson = new Gson();

        List<String> imgSlider = gson.fromJson(json, Plans.class).getImgSrc();

        Plans planJsonRes = gson.fromJson(json, Plans.class);

        //description
        String planDesc = planJsonRes.getPlanDesc();
        planDescV.setText(planDesc);
        //stats
        Integer helpCount = planJsonRes.getPlanHelperCount();
        Integer helpAmount = planJsonRes.getPlanHelpedCount();
        Integer Amount = planJsonRes.getPlanAmount();
        Integer userCount = planJsonRes.getUserCount();

        count_animation_textView
                .setAnimationDuration(animationDuration)
                .countAnimation(0, helpCount);
        count_animation_textView2
                .setAnimationDuration(animationDuration)
                .countAnimation(0, helpAmount);

        Float amountDarsad = ((float)helpAmount *  100) / (float) Amount  ;
        Float countDarsad = ((float)helpCount *  100) / (float) userCount  ;

        statHami.setProgressWithAnimation(countDarsad, animationDuration); // Default duration = 1500ms
        statAmount.setProgressWithAnimation(amountDarsad, animationDuration); // Default duration = 1500ms

        //title and location
        String planName = planJsonRes.getPlanName();
        String planLoc = planJsonRes.getPlanLocation();


        amountV.setText(convertToFormalString(Amount.toString()) + " تومان");
        planTitleV.setText(planName);
        planLocV.setText(planLoc);

        //image slider
        adapter = new CustomPagerAdapterByUrlMain(getApplicationContext());

        for (String item : imgSlider) {
            adapter.imageLink.add(AppConfig.BASE_URL + '/' + item.toString());
            adapter.planId.add(null);
        }

        //slider
        final Handler handler = new Handler();
        final Runnable Update = new Runnable() {
            public void run() {

                if (first) {
                    first = false;
                } else if (planPager.getCurrentItem() == planPager.getAdapter().getCount() - 1) {
                    planPager.setCurrentItem(0);
                } else {
                    planPager.setCurrentItem(planPager.getCurrentItem() + 1, true);
                }

            }
        };
        timer = new Timer(); // This will create a new Thread
        timer.schedule(new TimerTask() { // task to be scheduled

            @Override
            public void run() {
                handler.post(Update);
            }
        }, 500, 4000);

        planPager.setAdapter(adapter);
        customIndicator.setViewPager(planPager);

    } catch (Exception error) {
        Log.e("JsonError", "" + error);
    }

}

和节点js代码:

app.use('/api/v1/getPlan/:planId', getPagesController.getPlan);
exports.getPlan = function (req, res) {

knex('users').count('userId as c').first().then(function (usersCount) {

    knex('plans').where('plans.planId', req.params.planId).first().then(function (plan) {

        knex('files').select('fileSrc').where('plan_planId', plan.planId).then(function (files) {

            var imgSrcs = [];
            planJson = plan;
            for (var i in files) {
                imgSrcs.push(files[i].fileSrc);
            }
            planJson.imgSrc = imgSrcs;
            planJson.usersCount = usersCount.c;

        });

    });
});
res.send(planJson);
};

我用pm2运行我的节点服务器,问题是Volley在节点服务器的最后一次响应之前得到一个!

这是我的节点表达pm2日志:

0|www      | POST /api/v1/getPlan/7 200 4.924 ms - 265
0|www      | POST /api/v1/getPlan/7 200 4.466 ms - 894
0|www      | POST /api/v1/getPlan/1 200 4.964 ms - 894

这是我的android studio日志:

the response is: plan no 7

我原以为答案应该是1号计划。

凌空是否保留缓存的请求队列?

1 个答案:

答案 0 :(得分:0)

使用&#34; 同步&#34;您的方法的关键字ex。 私有已同步onNext(){..} - 也尝试使用&#34;同步&#34;在onResponse方法之前:                                 的 @覆盖                                 public synchronized void onResponse(String response){...}