Reputation: 5
I have an android application and using AsyncTask I want to download a JSON file from a website.
So far I have
public class DownloaderTask extends AsyncTask<String, Void, String[]> {
private MyActivity myactivity;
private Context context;
private String rawFeed[] = new String[3];
DownloaderTask(MyActivity parent) {
myactivity = parent;
context = parent.getApplicationContext();
}
@Override
protected String[] doInBackground(String... params) {
boolean complete = false;
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
for (int i = 0; i < params.length; i++) {
try {
URL url = new URL(params[i]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
input = connection.getInputStream();
}
catch (Exception e) {
}
}
return rawFeed;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String[] strings) {
if (myactivity != null) {
myactivity.setRefreshed(strings);
}
}
Im not sure how to continue from here
The website I'm downloading from is : https://d396qusza40orc.cloudfront.net/android%2FLabs%2FUserNotifications%2Ftaylorswift.txt
and when you go to the site it's just a page with a bunch of text on it, a JSON file.
The parameters that get passed into the AsyncTask is an array of 3 strings, each string containing the URL that I need to download from
Upvotes: 0
Views: 888
Reputation: 721
To read all the contents of an input stream I use:
String inputStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
is.close();
}
catch (IOException e)
{ }
return stringBuilder.toString();
}
Then, to parse it as a JSON you just can user the Java JSONObject constructing it with that string.
Upvotes: 1