Httpget 空错误
Httpget Null Error
我正在尝试获取 .php 的 json 数据
class RequestTask2 extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals(null)){
}else{
Title=result;}
}
}
new RequestTask2().execute("http://www.****.com/test/***.php"); (With handler)
当有活跃的互联网时,它工作得很好。但我不需要互联网检查方法。我已经完成了,错误是在执行 asynctask 时没有互联网时返回 null。
请帮助我如何在没有互联网时检查 Null 或停止任务。该错误导致强制关闭应用程序。感谢您对我的问题感兴趣。并希望它能尽快解决。
如果 internet 为空,则您的方法 doinbackground return 为空。
在你的方法中 onPostExecute "result" 是空的。
此代码抛出 nullPointerException,因为您尝试访问空对象。
if(result.equals(null)) {
...
}
替换为
if(result != null) {
Title=result;
}
如果你想取消你的任务,你可以在你的 doInBackground 方法(或你想要的地方)上调用 cancel(true) 并且方法 "onPostExecute" 不会被调用。
我正在尝试获取 .php 的 json 数据
class RequestTask2 extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals(null)){
}else{
Title=result;}
}
}
new RequestTask2().execute("http://www.****.com/test/***.php"); (With handler)
当有活跃的互联网时,它工作得很好。但我不需要互联网检查方法。我已经完成了,错误是在执行 asynctask 时没有互联网时返回 null。
请帮助我如何在没有互联网时检查 Null 或停止任务。该错误导致强制关闭应用程序。感谢您对我的问题感兴趣。并希望它能尽快解决。
如果 internet 为空,则您的方法 doinbackground return 为空。 在你的方法中 onPostExecute "result" 是空的。
此代码抛出 nullPointerException,因为您尝试访问空对象。
if(result.equals(null)) {
...
}
替换为
if(result != null) {
Title=result;
}
如果你想取消你的任务,你可以在你的 doInBackground 方法(或你想要的地方)上调用 cancel(true) 并且方法 "onPostExecute" 不会被调用。