安卓 Java函数在函数执行前返回一个值
我目前正在开发一款安卓应用程序,可以访问在线API。我有一个专门用于此任务的类,还有一个只使用从API检索的信息的类。问题是,当我调用API访问类时,它必须是异步的(由安卓 studio定义),所以我使用了一个新线程,但当API访问类返回良好结果时,使用数据的类中的返回为null
我已经试着用线连接两条线了。join()但它不起作用
下面是在API访问类中访问API的函数。系统。最后,out按预期工作(我在控制台中看到了良好的结果)
Thread t = new Thread() {
public void run() {
try {
String url = "-----------------------------------------------"+id;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("x-api-key", "-------------------------------");
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
HttpRequest.retour = new JSONArray(response.toString());
System.out.println(HttpRequest.retour.toString());
}catch(Exception e){
e.printStackTrace();
}
}
};
t.start();
但当我在另一节课上尝试这样做时:
System.out.println(retour.toString());
我得到一个空指针异常,因为前一个方法的返回值为空
我犯了什么错
共 (0) 个答案