我正在使用异步任务来运行JSON下载器:(删节)
public class JSONDownloader extends AsyncTask<Object, Object, Object>{
@Override
protected Object doInBackground(Object... params) {
if(JSONstate == false){
try {
final URL url = new URL([REDACTED]);
final URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
urlConnection.connect();
final InputStream inputStream = urlConnection.getInputStream();
final StringBuilder sb = new StringBuilder();
while (inputStream.available() > 0) {
sb.append((char) inputStream.read());
}
String result = sb.toString();
JSONObject jsonOrg = new JSONObject(result);
String ok = "ok";
Response = jsonOrg.getString("response");
System.out.println(Response);
if(Response.equals(ok)){
Settingsresponse = true;
orgName = jsonOrg.getString("orgName");
System.out.println("orgName" + orgName);
accessPointName = jsonOrg.getString("attendanceRecorderName");
System.out.println("accessPointName" + accessPointName);
lat = jsonOrg.getString("latitude");
System.out.println("lat" + lat);
longi = jsonOrg.getString("longitude");
System.out.println("longi" + longi);
floor = jsonOrg.getString("floor");
System.out.println("floor" + floor);
orgId = jsonOrg.getString("orgId");
System.out.println("orgId" + orgId);
}
else{
System.out.println("Data sent was erroneous");
Settingsresponse = false;
}
} catch (Exception e) {
System.err.print(e);
}
}
else if(JSONstate == true){
try {
[redacted]
}
else{
System.out.println("Data sent was erroneous");
Settingsresponse = false;
}
} catch (Exception e) {
System.err.print(e);
}
}
return null;
}
protected void onPostExecute(Void result){
if(JSONstate == false){
System.out.println("This piece of code is definitely being run");
setfields();
}
else if(JSONstate == true){
settestfields();
//This method does not run upon the completion of the JSON request, as it supposedly should
}
}
}
Run Code Online (Sandbox Code Playgroud)
完成JSONRequest后,'onPostExecute'方法不会运行.我一直在尝试使用此方法,以便在请求完成后立即更新一组字段,而不必设置明确的等待时间.我只是简单地利用代码错了吗?还是有什么我错过的?
您没有覆盖onPostExecute的正确方法.
你有:
protected void onPostExecute(Void result)
Run Code Online (Sandbox Code Playgroud)
你需要:
protected void onPostExecute(Object result)
Run Code Online (Sandbox Code Playgroud)
请注意,您提供的第三个通用参数是类型Object.这是onPostExecute用作参数的类型.所以,方法签名onPostExecute需要接受一个Object,而不是Void.
你应该在这里使用boolean的结果类型而不是object,并删除Json状态类变量.这使您的AsyncTask更加灵活,并且可以允许您在执行后向用户显示操作完成的一些指示.