Issue
I have a simple class that extends AsyncTask
where I access a textfile on the web and extract content to String tmpString
. All this is done in doInBackground()
. Right after calling execute();
I call method my own method parseContent();
from another class that extract substrings from tmpString
.
Now to the problem, when I run this code I get tmpString = null
, meaning the content from the website is null but I know the content is retrieved by checking with Log.d("--------INFO--------", inputLine);
that prints line by line from the source file. I suspect that the download is too slow before the next method call. It all works fine when I debug because the download had time to finish.
Using execute().get();
works, but I read that this isn't an optimal solution especially since it's blocking the thread. Later on I'd like to add a progress bar for the download but combining this with get()
won't work... apparently.
What I'd like to do is to call the next method only if the download is complete, how can I achieve this?
Code here:
public class AccessFile extends AsyncTask<Object, Void, String>{
private String urlContent = "";
@Override
protected String doInBackground(Object[] params) {
URL url= null;
url= new URL((String) params[0]);
BufferedReader in = null;
try {
assert url!= null;
in = new BufferedReader(
new InputStreamReader(
url.openStream()));
} catch (IOException e) {
e.printStackTrace();
}
String inputLine = null;
inputLine = in.readLine();
while (inputLine != null){
Log.d("--------INFO--------", inputLine);
urlContent += inputLine;
inputLine = in.readLine();
}
in.close();
return "";
}
}
I call this with:
AccessFile af = new AccessFile();
af.execute("Link here").get();
Solution
You can try
AccessFile af = new AccessFile()
{
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//code which should be executed after task completion
}
};
af.execute("link);
Answered By - Jyoti JK
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.