java - 在类方法上创建回调

标签 java android

我正在努力处理我创建的网络连接类。我创建的 Runnable 的结果返回一个 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,因为线程仍在访问服务器以获取响应。

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

有什么帮助吗?

最佳答案

我只会同意对您的问题的评论,并让您知道您可以在这里做什么。

如果您创建一个线程只是为了获取主 UI 线程来执行网络调用,您可能需要使用 OkHttp该功能允许您从线程中获取网络调用,并为您提供回调以获取类似这样的结果。你可以查看一些例子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() {

                }
            });
        }
    });

或者您可以使用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 的示例

关于java - 在类方法上创建回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37140805/

相关文章:

android - Gradle sync更新到2.0.0-rc2版本后找不到add-on

java - 为什么这个断言不起作用 - assertThat(foo, is(not(null)));

android - 从 CustomTextView 更改颜色文本

java - 使用父类(super class)实例构造子类

Java:使用子级的成员变量调用父级的方法

java - 为什么我的 View 没有改变?

android - 带有 MediaPlayer 的 TYPE_NOTIFICATION

android - 在delphi中将Jnet_uri转换为Tbitmap

java - 区域的 LocalDateTime 不显示区域的一天中的小时

java - 如何使用远程 Java 编译器?