In my following code I am trying to retrieve some JSON data by passing an URL. It works fine but does take some time in fetching data from the Internet. Even though the data isn't that bulky but still it takes like few seconds and then I can see data in log. But I really want to improve the speed with which I could improve retrieving data from internet.
public class DownloadData extends AsyncTask<String, Void, String> {
private static final String TAG = "DownloadData";
@Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
String result = "";
int data;
data = inputStreamReader.read();
while (data != -1) {
char currentChar = (char) data;
result += currentChar;
data = inputStreamReader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Failed";
}
@Override
protected void onPostExecute(String s) {
Log.d(TAG, "downloaded JSON Data: " + s);
}
}
Dont read characters one by one. Takes too much time. Use .readLine() instead.
Dont use string concatenation as that takes a lot of time too. Instead use a StringBuilder to add the lines to.