在类方法上创建回调(Creating a callback on a class method)

编程入门 行业动态 更新时间:2024-10-26 00:32:19
在类方法上创建回调(Creating a callback on a class method)

我正在努力学习我创建的网络连接类。 Runnable I create的结果返回一个JSON对象,其中包含服务器所需的所有信息。 线程运行,并完美地接收数据,但当然,程序在此期间保持运行,这导致JSONException为NULL。

我创建了一个名为NetworkManager的类,它具有以下方法(jsonResponse在类的开头初始化)

JSONObject jsonResponse; public void createNetworkThread(Context context, final String requestURI, final RequestBody formParameters) { Runnable runnable = new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(requestURI).post(formParameters).build(); Response response = null; try { response = client.newCall(request).execute(); String stringResponse = response.body().string(); NetworkManager.this.jsonResponse = new JSONObject(stringResponse); // This works perfectly, "message" is received and printed to the log // Log.d("Net", NetworkManager.this.jsonResponse.getString("message")); } catch (IOException e) { Log.d("Net", "Failed"); e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }; Thread thread = new Thread(runnable); thread.start(); }

以上是从Activity中调用的,如下所示:

Net.createNetworkThread(SignupActivity.this, requestURI, formVars); JSONObject jsonResponse = Net.jsonResponse;

JSON对象jsonResponse返回为NULL,因为Thread仍在访问服务器以获取响应。

我需要弄清楚如何阻止jsonResponse对象被Net.jsonResponse填充,直到线程完成以阻止它返回NULL。

有帮助吗?

I'm struggling with a network connection class I've created. The result of the Runnable I create returns a JSON object that contains all the information needed from the server. The thread runs, and receives the data perfectly, but of course, the program keeps running in the meantime, which results in a JSONException as being NULL.

I created a class called NetworkManager, which has the following method (jsonResponse is initialized at the beginning of the class)

JSONObject jsonResponse; public void createNetworkThread(Context context, final String requestURI, final RequestBody formParameters) { Runnable runnable = new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(requestURI).post(formParameters).build(); Response response = null; try { response = client.newCall(request).execute(); String stringResponse = response.body().string(); NetworkManager.this.jsonResponse = new JSONObject(stringResponse); // This works perfectly, "message" is received and printed to the log // Log.d("Net", NetworkManager.this.jsonResponse.getString("message")); } catch (IOException e) { Log.d("Net", "Failed"); e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }; Thread thread = new Thread(runnable); thread.start(); }

The above is called from the Activity, as:

Net.createNetworkThread(SignupActivity.this, requestURI, formVars); JSONObject jsonResponse = Net.jsonResponse;

The JSON object jsonResponse is returning as NULL because the Thread is still accessing the server for the response.

I need to figure out how to stop the jsonResponse Object from being populated by Net.jsonResponse until the thread completes in order to stop it from returning NULL.

Any help?

最满意答案

我只会同意您对问题的评论,并告诉您,您可以在此处做些什么。

如果你正在创建一个线程只是为了获得主要的UI线程来进行网络调用你可能想要使用OkHttp功能,它允许你从线程中获取网络调用并为你提供回调以获得这样的结果。 你可以在这里查看一些例子

Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { // this is the callback which tells you the network call was successful, If like to make some changes to UI, you should call `runOnUiThread`. "YourClassName".this.runOnUiThread(new Runnable() { @Override public void run() { } }); } });

或者您可以使用AsyncTask ,它也可以在主UI线程中完成您的工作,并在回调中提供结果。

private class MyTask extends AsyncTask<Void, Void, Void> { //you can change the Type Void, Void, Void here to something which you want //First Void belongs to doInBackground(Void... avoid) //Second Void belongs to onProgressUpdate(Void... progress) //Third Void belongs to onPostExecute(Void result) // you may change these as you fit, //when you want to start this class with your argument you can do something like this. //new MyTask().execute("your argument to doInBackground"); @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { // this is the method where you provide your implementation for doing a task off the main UI thread. return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); // in this callback you are back in the main UI thread to make changes to UI depending on your response } }

这是AsyncTask的一个例子

I would only agree to the comments on your question and let you know, what you can do here.

If you are creating a thread just to get of the main UI thread to do the Network call you probably want to use OkHttp feature which allows you to get the Network call off the thread and provides you with callbacks to get the result something like this. you can check some example here

Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { // this is the callback which tells you the network call was successful, If like to make some changes to UI, you should call `runOnUiThread`. "YourClassName".this.runOnUiThread(new Runnable() { @Override public void run() { } }); } });

or you can use AsyncTask which also gets your job done off the main UI thread and gives you the result in the callbacks.

private class MyTask extends AsyncTask<Void, Void, Void> { //you can change the Type Void, Void, Void here to something which you want //First Void belongs to doInBackground(Void... avoid) //Second Void belongs to onProgressUpdate(Void... progress) //Third Void belongs to onPostExecute(Void result) // you may change these as you fit, //when you want to start this class with your argument you can do something like this. //new MyTask().execute("your argument to doInBackground"); @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { // this is the method where you provide your implementation for doing a task off the main UI thread. return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); // in this callback you are back in the main UI thread to make changes to UI depending on your response } }

here is an example of AsyncTask

更多推荐

本文发布于:2023-07-05 15:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1039133.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   方法   Creating   method   class

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!