Java 使用接口更新全局变量

Java 使用接口更新全局变量,java,android,android-asynctask,java-native-interface,okhttp,Java,Android,Android Asynctask,Java Native Interface,Okhttp,我在MainActivity.java中有一个异步类 class Register extends AsyncTask<String, String, JSONObject> { JSONObject json; @Override protected JSONObject doInBackground(String[] args) { String function = args[3]; String email = ar

我在MainActivity.java中有一个异步类

class Register extends AsyncTask<String, String, JSONObject> {
JSONObject json;

     @Override
     protected JSONObject doInBackground(String[] args) {

         String function = args[3];
         String email = args[2];
         String password = args[1];
         String name = args[0];

         ContentValues params = new ContentValues();
         params.put("username", name);
         params.put("password", password);
         params.put("function", function);
         if (email.length() > 0)
             params.put("email", email);

         String URL = "https://lamp.ms.wits.ac.za/home/s2090704/index.php";
         new PhpHandler().makeHttpRequest(act, URL, params, new RequestHandler() {
             @Override
             public void processRequest(String response) throws JSONException {
                json = new JSONObject(response);
                 System.out.println(json); //outputs {response: " ...",message:"..."}


             }
         });
         System.out.println(json); //outputs null
         return json;
     }
}

RequestHandler是在mainUiThread上处理请求的接口

package com.example.registration;

import org.json.JSONException;

public interface RequestHandler{
   void processRequest(String response) throws JSONException;
}

现在json不会在我的异步类寄存器的doInBackground方法中的processRequest方法之外更新。我知道接口会使变量成为静态变量和最终变量。有什么方法可以更新json的值吗?

processRequest
方法将在您从
doInBackground
返回
json
很久之后执行,因为
makeHttpRequest
执行异步http请求

知道了这一点,您可能会想重新设计这个类(不需要在
AsyncTask
中包装已经异步的请求),但是如果您真的想这样做,您必须等待请求完成后再返回json(例如,使用CountDownLatch)

CountDownLatch闩锁=新的CountDownLatch(1);
someField=null;
AtomicReference someValue=新的AtomicReference();
//不要像这样开始新的线程,我只是想让这个例子保持简单
新线程(){
Thread.sleep(1000);//睡眠1秒
someValue.set(“abc”);//请注意,因为在使用AtomicReference时,您可以使用`set`方法而不是`=`运算符来指定它的值,因此可以将其保留为局部变量,而不是字段类
lock.countDown();//将闩锁计数减少一
}.run();
System.out.println(someValue.get());//null-因为赋值将在一秒钟内发生
闩锁。等待();//这将强制当前线程等待,直到闩锁计数达到零(初始值为1,传递给构造函数)
System.out.println(someValue.get());//“abc”

Java中没有全局变量。谢谢,我完全忘记了okHttp是异步调用的。我已经辞去了主要的活动课,现在一切都很好
package com.example.registration;

import org.json.JSONException;

public interface RequestHandler{
   void processRequest(String response) throws JSONException;
}