Issue
I'm trying to download the source code of a page. But when I'm running the code it is running for eternity and the log is showing something like that forever.
GC_FOR_ALLOC freed 274K, 13% free 6863K/7815K, paused 0ms
Here is my code :
class downloadSource extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String line = "";
int x;
try {
URL url = new URL(params[0]);
InputStream inputStream = url.openStream();
InputStreamReader reader = new InputStreamReader(inputStream);
x = reader.read();
while (x != -1) {
char c = (char) x;
x = reader.read();
line += c;
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return line;
}
And I'm calling it like that from the OnCreate method :
downloadSource task2=new downloadSource();
String source = "";
try {
source = task2.execute("https://www.imdb.com/list/ls052283250/").get();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Please help me ! Thanks
Solution
Your problem is probably not related to a memory leak. While your approach to read the stream is inefficient as mentioned by Holger, it is also not your main problem.
Try adding the following line as the first line in your onCreate:
System.setProperty("http.keepAlive", "false");
What was happening is that without setting this property, your connection was kept alive waiting for more requests to be done, and was only returning when it timed out. Setting it to false makes it return right when your request has completed. To understand this concept better, read this answer: How to interpret "Connection: keep-alive, close"?.
Regarding the inefficient stream reading, I would recommend you to change your implementation to something similar to the following code:
URL url = new URL(params[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder builder = new StringBuilder();
String current;
while ((current = reader.readLine()) != null) {
builder.append(current);
}
line = builder.toString();
reader.close();
Answered By - Amirton Chagas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.