繁体   English   中英

从其他包的方法返回 JSONArray

[英]Return JSONArray from other package's method

我正在尝试从其他 package 返回 JSONArray。

但我的日志是'D/test: []'。

如何从其他 package 返回 JSONArray?

我想要做

RemSeat r = new RemSeat();

JSONArray aj = r.getremseat(getApplicationContext(),"20220827","0671801","3112001");

Log.d("测试", aj.toString());

在我的 MainActivity 中。

TerCode.java

package remseatcomponent;

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
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;

import java.util.HashMap;
import java.util.Map;

public class RemSeat {
    public JSONArray getremseat (Context context, String timDte, String terFrI, String terToI) {
     /*
        String timDte = "20220827";
        String terFrI = "0671801";
        String terToI = "3112001";
    */

        JSONArray ja = new JSONArray();

        String url = "https://MY URL"; //myURL
        String timTimI = "0000";  //

        RequestQueue queue = Volley.newRequestQueue(context);


        JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url + "/ibt_list" + "/" + timDte + "/" + timTimI + "/" + terFrI + "/" + terToI + "/9/0",
                null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONArray jsonArray = response.getJSONObject("response").getJSONArray("LINE_LIST");


                    for (int a = 0; a < jsonArray.length(); a++) {
                        JSONObject jo = jsonArray.getJSONObject(a);

                        JSONObject joo = new JSONObject();
                        joo.put("TIM_TIM", jo.getString("TIM_TIM"));
                        joo.put("LIN_TIM", jo.getString("LIN_TIM"));
                        joo.put("REM_CNT", jo.getString("REM_CNT"));

                        ja.put(joo);

                    }


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

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("e", "Site Info Error: " + error.getMessage());
            }
        }) {
            // header
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("x-Gateway-APIKey", "MY PERSONAL KEY");
                return headers;
            }


        };

        queue.add(req);
        return ja;

    }
}

MainActivity.java

package com.example.terapi3;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import remseatcomponent.RemSeat;
import android.util.Log;
import org.json.JSONArray;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // I want to do this on MainActivity
        RemSeat r = new RemSeat();
        JSONArray aj = r.getremseat(getApplicationContext(),"20220827", "0671801", "3112001");
        Log.d("test", aj.toString());



    }




}

如何使用 volley 从其他包的方法返回 JSONArray?

Volley 调用是异步的 - 这意味着您的响应侦听器中的代码将在以后运行,但您的 function 立即返回,因此列表仍然为空。 从 Internet 或服务器获取内容需要“很长时间”,因此此类事情几乎总是使用异步 API 完成。

像这样使用异步 API 时,不能返回数据(除非可以使用协程/挂起函数)。 访问此类数据的方法是使用回调,如下所示:

public class RemSeat {
    public interface JsonCallback {
        void gotArray(JSONArray ar);
    }
    
    public void getremseat (Context context, String timDte, String terFrI, String terToI, JsonCallback callback) {
        RequestQueue queue = Volley.newRequestQueue(context);
        String path = "make_the_url";
        
        JsonObjectRequest req = new JsonObjectRequest(
            Request.Method.GET, path, null, 
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    JSONArray ja = new JSONArray();
                    // populate ja from response, and call the callback
                    // with the populated array
                    callback.gotArray(ja);
                }
            }, 
            new Response.ErrorListener() {
                // ...
            }
        );

        queue.add(req);
    }
}

然后您可以像这样调用它,在检索到数组后提供一个带有您想要运行的代码的回调。 由于这里的代码仍然是一个回调,所以gotArray中的行将在以后实际检索到数组时运行。

r.getremseat(getApplicationContext(),
    "20220827", "0671801", "3112001", 
    new RemSeat.JsonCallback() {
        @Override
        public void gotArray(JSONArray ar) {
            // anything that needs the array must run in here
            Log.d("test", ar.toString());
        }
    }
);
// this will run BEFORE the Log above gets run

暂无
暂无

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

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