我在下面写了一个异步任务
public class DownloadTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
String result = "";
HttpsURLConnection urlConnection = null;
try {
URL url = new URL(urls[0]);
urlConnection = (HttpsURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1){
char currentData = (char)data;
result+=currentData;
data = reader.read();
}
Log.i("Downloaded data",result);
}catch (Exception e){
e.printStackTrace();
}
return result;
}
}
这里 AsyncTask 返回一个string
值。在onCreate
我调用这个 AsyncTask 的对象的方法中
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
titles = new ArrayList<String>();
arrayAdapter =new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,titles);
listView.setAdapter(arrayAdapter);
//To get json data
DownloadTask task = new DownloadTask();
try {
task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
}catch (Exception e){
e.printStackTrace();
}
}
此代码可以正常工作。但我怀疑我们是否需要一个字符串类型的变量来捕获 AsyncTask 的返回值。这里没有使用变量,它只是写成task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
. 为什么这不会引发错误。谁能解释一下。我是安卓新手。