我在doInBackground中有两个代码,但只有第二个代码将数据传递给onPostExecute
。
已经尝试调试代码,但它没有多大帮助。我认为,我使用的网络服务功能齐全。
public void onClickWheater(View view){
new HttpAsyncTask().execute(opa);
}
class HttpAsyncTask extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
@Override
protected String doInBackground(String... params) {
if(params.equals(opa)){
try {
HttpGet get = new HttpGet("http://ghelfer.net/weather.aspx?output=json");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
return data;
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
HttpGet get = new HttpGet("https://viacep.com.br/ws/" + params[0] + "/json/");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(get);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
return data;
}
} catch (Exception e) {
return null;
}
}
return null;
}
编辑 - PostExecute
@Override
public void onPostExecute(String result){
dialog.dismiss();
if (result != null){
try{
JSONObject obj = new JSONObject(result);
String logradouro = obj.getString("logradouro");
String complemento = obj.getString("complemento");
String bairro = obj.getString("bairro");
String localidade = obj.getString("localidade");
String uf = obj.getString("uf");
txtLogradouro.setText(logradouro);
txtComplemento.setText(complemento);
txtBairro.setText(bairro);
txtLocalidade.setText(localidade);
txtUF.setText(uf);
JSONObject res = new JSONObject(result);
JSONArray weather = res.getJSONArray("weather");
int dataLength = weather.length();
double avgTemp = 0.0;
double avgHumid = 0.0;
double tempSum = 0.0;
double humidSum = 0.0;
for (int i = 0; i < dataLength; i++) {
JSONObject tempObj = weather.getJSONObject(i);
tempSum += tempObj.getDouble("temperature");
humidSum += tempObj.getDouble("humidity");
}
if (dataLength != 0) {
avgTemp = tempSum/dataLength;
avgHumid = humidSum/dataLength;
}
String temp = Double.toString(avgTemp);
txtTemperature.setText(temp);
} catch (Exception e) {
e.printStackTrace();
}
}
}