致电
新的AsyncFeed(strurl).execute();
之后它能够调用AsyncFeed的构造函数但不能执行doInBackground()。调试时我发现它调用构造函数,然后简单地返回调用语句,在后面的代码中生成一个nullpointer异常
public class HttpHandler {
public HttpHandler() {
}
URL url;
HttpURLConnection httpURLConnection = null;
InputStream inputStream;
BufferedReader bufferedReader = null;
StringBuffer stringBuffer;
String strurl;
public String getJsonString(String strurl){
new AsyncFeed(strurl).execute();
return String.valueOf(stringBuffer);
}
class AsyncFeed extends AsyncTask<String,Void,String>{
String urlStr;
public AsyncFeed(String urlStr) {
this.urlStr=urlStr;
}
@Override
protected String doInBackground(String... strings) {
try {
url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader !=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
}
return null;
}
答案 0 :(得分:2)
如果您认为stringBuffer
是null
,那么因为函数public String getJsonString(String strurl)
在String
之前返回未初始化stringBuffer
的{{1}}值} 完成了。你应该使用这样的东西:
AsyncFeed
有更多选项可以做到这一点,但很难在不看到更多代码或指定问题的情况下准确写出您需要的内容,所以如果您有一些 问我只是写评论:)或在这里阅读更多Android Developers - AsyncTask
修改强>
好的,我理解,尝试这样做,想法只是将调用对象传递给异步任务,并从那里onPostExecute()将更新数据 在ClassA中继续你需要的东西
public void loadJsonString(String strurl){
new AsyncFeed(strurl).execute();
//return String.valueOf(stringBuffer);
}
class AsyncFeed extends AsyncTask<Void,Void,Void>{
String urlStr;
public AsyncFeed(String urlStr) {
this.urlStr=urlStr;
}
@Override
protected String doInBackground(Void... records) {
try {
url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader !=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
}
return null;
}
@Override
protected void onPreExecute() {
//f.e. show progress dialog
}
@Override
protected void onPostExecute(Void result) {
//now you have initialized stringBuffer so do what you want with it
//hide progress dialog
//print String value of stringBuffer initialized in doInBackground
System.out.print(String.valueOf(stringBuffer));
}
)