繁体   English   中英

如何从 Volley 的 onResponse 函数返回值?

[英]How can I return value from function onResponse of Volley?

public class getString  {
String tag_string_req = "string_raq";
String url = "http://10.0.2.2/eat/locations/index.json";
String result="";

public String get_String() {
    StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            result=response;
            System.out.println(response);
            ;

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            System.out.println(volleyError.getMessage());
        }
    });
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    return result;
}}

我会构建一个 getString 对象并在其他字段中调用 get_String 。 但似乎很难从 onResponse 中得到结果。 我知道它不能以目前的方式工作。 谁能帮我解决这个问题?

你想像这样使用回调接口:

public void getString(final VolleyCallback callback) {
    StringRequest strReq = new StringRequest(Request.Method.GET, url, new     Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            ...  // (optionally) some manipulation of the response 
            callback.onSuccess(response);
        }
    }...
}}

其中回调定义为

public interface VolleyCallback{
    void onSuccess(String result);
}

活动中的示例代码:

public void onResume(){
    super.onResume();

    getString(new VolleyCallback(){
         @Override
         public void onSuccess(String result){
             ... //do stuff here
         }
    });
}

您还可以使VolleyCallback更加健壮,如果您想进行处理,可以使用泛型类型,或者添加start()failed(Exception e)complete()等方法来进行更细粒度的状态检查。

请记住,这是一个异步调用,因此当您返回结果(在success() )时,您必须更新视图等。

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {


    val rootView = inflater.inflate(R.layout.mission_fragment_list, container, false)
    val recycler = rootView.findViewById(R.id.list) as RecyclerView

    GlobalScope.async {
        val queue = Volley.newRequestQueue(context)
        val gson = Gson()

        val url = "YPUR_API"
        val stringRequest = StringRequest(
            Request.Method.GET, url,
            Response.Listener<String> { response ->

                recycler.layoutManager = LinearLayoutManager(context)
                val listType: Type = object : TypeToken<MutableList<MissionModel>?>() {}.type
                val data: MutableList<MissionModel> = gson.fromJson(response, listType)
                recycler.adapter = MissionAdapter(data)
            },
            Response.ErrorListener { error ->
                error.printStackTrace()
            })

        queue.add(stringRequest)


    }
    return rootView

}

简单的代码。 你需要添加依赖实现 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1'

正如 wblaschko 提到的一个非常好的解决方案所提到的,我理解这个解决方案对于那些经验较少的人来说可能会有点混乱。 在 wblaschko 的解决方案之上我编辑的解决方案下方:

VolleyCallback.java(接口)

public interface VolleyCallback {
    void onSuccess(String result);
    void onError(String result);
}

我做了一个 HTTPRequest 类来保持干净。

HTTPReq.java (类)

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

public class HTTPReq {
    public static StringRequest getRequest(String path, final VolleyCallback callback) {
        // Instantiate the RequestQueue.
        String url = "https:// **FILL HERE BASE API URL** /" + path;

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string.
                        callback.onSuccess(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                callback.onError(error.toString());
            }
        });

        return stringRequest;
    }
}

最后,在活动中,您要实现以下代码:

创建一个全局变量:

private RequestQueue mQueue;

之后,在活动的 onCreate 函数中应用 VolleyRequestQue:

mQueue = Volley.newRequestQueue(this);

最后,实际执行 API 请求并捕获响应的函数:

mQueue.add(HTTPReq.getRequest( **FILL WITH PATH AND/OR PARAMS**, new VolleyCallback() {
    @Override
    public void onSuccess(String result) {
        System.out.println(result);
    }

    @Override
    public void onError(String result) {
        System.out.println(result);
    }
}));

希望这更清楚。

暂无
暂无

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

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