I have written an Async task below
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;
}
}
Here the AsyncTask returns a string
value.
In the onCreate
method I have called the object of this 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();
}
}
This code works without an error. But my doubt is don't we need a variable of type string to catch the returned value of AsyncTask. Here no variable is used and it's simply written as task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
. Why doesn't this raise an error. Can anybody please explain. I am new to Android.