java - 方法未按时间顺序调用

标签 java android android-volley jsonobjectrequest

我试图按时间顺序调用函数,但函数 parseJSONTwo() 似乎在函数 parseJSON() 之前执行(这两个函数都只是从 URL 获取 JSON 数据)

package com.example.rechev;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class pratim extends AppCompatActivity {

    RequestQueue queue;
    TextView degem;
    String model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pratim);
        degem = findViewById(R.id.pratim);
        queue = Volley.newRequestQueue(this);
        parseJSON();
        parseJSONTwo();
    }


    public void parseJSON() {
        Intent intent = getIntent();
        int number = intent.getIntExtra("inumber", 1234567);
        String url = "http://apiurl.com" + number}";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject result = response.getJSONObject("res");
                    JSONArray jsonArray = result.getJSONArray("rec");
                    String test = result.getString("total");

                    if (Integer.parseInt(test) == 1) {

                        for (int i = 0; i < jsonArray.length(); i++) {

                            JSONObject number = jsonArray.getJSONObject(i);

                            String carMaker = number.getString("toze");

                            degem.append(String.valueOf("\n maj: " + carMaker));

                            model = number.getString("degem_nm");

                            if (carGimur.length() >= 1) {
                                degem.append(String.valueOf("\n type: " + carGimur));
                            }
                        }
                    } else {
                        degem.append("invalid");
                    }
                } catch (JSONException e) {
                    degem.append(e.toString());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                degem.append("Error");
            }
        });

        queue.add(request);
    }


    public void parseJSONTwo() {
        String url = "http://apiurl.com"+model}";
        JsonObjectRequest requestt = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject result = response.getJSONObject("res");
                    JSONArray jsonArray = result.getJSONArray("rec");
                    String test = result.getString("total");

                    if (Integer.parseInt(test) == 1) {

                        for (int i = 0; i < jsonArray.length(); i++) {

                            JSONObject number = jsonArray.getJSONObject(i);

                            String carNefah = number.getString("nefah_manoa");

                            degem.append(String.valueOf("num: " + carNefah));
                         }
                    }
                } catch (JSONException e) {
                    degem.append(e.toString());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                degem.append("Error");
            }
        });

        queue.add(requestt);
    }
}


函数parseJSON()url获取JSON数据并将其放入TextView,并且它还设置了一个全局变量(model ) 一个值,parseJSONTWO() 在其 URL 中使用该值,因此它可以根据第一个 parseJSON() 函数获取数据。

问题是 parseJSONTwo() 由于某种原因首先被调用,所以它不能使用 parseJSON() 检索的信息。

更新后的代码:

package com.example.rechev;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class pratim extends AppCompatActivity {

    RequestQueue queue;
    TextView degem;
    String model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pratim);
        degem = findViewById(R.id.pratim);
        queue = Volley.newRequestQueue(this);
        parseJSON();

    }


    public void parseJSON() {
        Intent intent = getIntent();
        int number = intent.getIntExtra("inumber", 1234567);
        String url = "http://apiurl.com" + number}";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject result = response.getJSONObject("res");
                    JSONArray jsonArray = result.getJSONArray("rec");
                    String test = result.getString("total");

                    if (Integer.parseInt(test) == 1) {

                        for (int i = 0; i < jsonArray.length(); i++) {

                            JSONObject number = jsonArray.getJSONObject(i);

                            String carMaker = number.getString("toze");

                            degem.append(String.valueOf("\n maj: " + carMaker));

                            model = number.getString("degem_nm");

                            if (carGimur.length() >= 1) {
                                degem.append(String.valueOf("\n type: " + carGimur));
                            }
                        }
                    } else {
                        degem.append("invalid");
                    }

                  if(model.length() >= 1){
                      parseJSONTwo();
                   }
                } catch (JSONException e) {
                    degem.append(e.toString());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                degem.append("Error");
            }
        });

        queue.add(request);
    }


    public void parseJSONTwo() {
        String url = "http://apiurl.com"+model}";
        JsonObjectRequest requestt = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject result = response.getJSONObject("res");
                    JSONArray jsonArray = result.getJSONArray("rec");
                    String test = result.getString("total");

                    if (Integer.parseInt(test) == 1) {

                        for (int i = 0; i < jsonArray.length(); i++) {

                            JSONObject number = jsonArray.getJSONObject(i);

                            String carNefah = number.getString("nefah_manoa");

                            degem.append(String.valueOf("num: " + carNefah));
                         }
                    }
                } catch (JSONException e) {
                    degem.append(e.toString());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                degem.append("Error");
            }
        });

        queue.add(requestt);
    }
}


现在 parseJSONTwo 将获得正确的 URL 但不会完成该功能。

最佳答案

在每个函数中,parseJSON()parseJSONTWO(),您都在发出异步网络请求。网络请求不是即时的,从几毫秒到几十毫秒不等,这比您的程序执行要慢得多。由于网络请求需要一些时间来解析相应的 onResponse() 函数也会延迟并在相关请求返回时触发。

因此,您的代码中的操作顺序是

  1. 调用 parseJSON() 启动一个需要一段时间的 GET 请求
  2. 调用 parseJSONTwo() 启动另一个 GET 请求,而不等待 parseJSON() 的 GET 请求的响应,这也可能需要一段时间

函数 parseJSONTwo() 在函数 parseJSON() 开始 GET 请求后返回后立即调用,该请求可能尚未完成,因为 GET 请求可能需要一会儿。因此当函数parseJSONTwo()被调用开始下一个GET请求时,parseJSON()的GET请求可能还在处理中并且没有响应。

当每个请求返回时,其 onResponse() 回调将触发。但是,未指定它们返回的顺序。这将取决于服务器和网络状况以及每个请求完成所需的时间。

并且由于函数 parseJSONTwo() 需要函数 parseJSON() 的响应,所以您必须链接这些函数,以便第二个函数 parseJSONTwo () 仅在收到第一个函数的 GET 请求的响应时调用。

链接这些函数的一种方法是在函数 parseJSON()OnResponse() 处理程序中调用函数 parseJSONTwo() .

关于java - 方法未按时间顺序调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58346669/

相关文章:

java - getStringExtra() 总是抛出 NullPointerException

java - HashMap 重复值 - 查找重复项的数量

android 自动完成在第一次不起作用

android - Gallery/AdapterView 子绘图状态

android - 通过 Android Studio 和 Volley 的 CURL 请求

java - 为什么我的代码从嵌套的 JSON 数组返回值 'null'

java - 在 Hadoop 2.2.0 中打开缓存文件

java - 文件写入器不工作?

android - 在 android ics 中禁用屏幕截图

java - 长时间运行后,Volley 导致服务崩溃应用程序