EDIT:
I solved this question myself with the following code:
@Override
protected void onPostExecute(String result) {
loading.setVisibility(View.GONE);
if (result!=null) { //PREVENTS INTERNET CRASH!
loadJSON(result);
loadNext();
}
}
where loadNext() triggers a new loop
private void loadNext() {
link = link + 1;
if (link < linksArray.length){
new BackgroundTask().execute("" + names[link]);
}
}
Because of this I can't mark any answer as accepted because I tried them without success.
QUESTION STARTS HERE:
So, i use AsyncTask to load text from different websites. The websites is listed in an array. When calling the Asynctask I use the following loop inside the onCreate method.
for (int i = 0; i < linksArray.length; i++) {
new BackgroundTask().execute("" + linksArray[i], "" + i);
}
Inside the "doInBackground" I load the text using: params[0]
The problem I'm having is that the backgroundworker seems to skip some links and it does some links twice.
Example: I could get something like this: 1, 2, 3, 4, 4, 6, 7, 8, 8 when the expected outcome is 0, 1, 2, 3, 4, 5, 6, 7, 8
Does any1 have any solution for this. I've been trying to create the loop inside the AsyncTask instead but was unsuccessful. Thanks in advance :)
edit:
@Override
protected String doInBackground(String... params) {
try {
json_url = params[0];
number = Integer.parseInt(params[1]);
System.out.println("test " + number);
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoInput(true);
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String JSON_STRING;
while((JSON_STRING = bufferedReader.readLine())!=null){
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
loading.setVisibility(View.GONE);
if (result!=null) //PREVENTS INTERNET CRASH!
loadJSON(result);
}
}
public void loadJSON(String json_string) {
JSONresult = json_string;
System.out.println("test2 " + number);
}
Using this code the output became:
I/System.out: test 0
I/System.out: test 1
I/System.out: test2 1
I/System.out: test 2
I/System.out: test2 2
I/System.out: test 3
I/System.out: test2 3
I/System.out: test 4
I/System.out: test2 4
I/System.out: test 5
I/System.out: test2 5
I/System.out: test2 5