-1

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
Erik
  • 21
  • 4

2 Answers2

0

You should check this answer: Running multiple AsyncTasks at the same time -- not possible?

It seems as though AsyncTask uses a thread pool which in some versions has a max size of 5, and in later versions it's the number of processors + 1.

In order to allow more threads you should do this:

@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
void startMyTask(BackgroundTask asyncTask, String... params) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    else
        asyncTask.execute(params);
}

And you should do this:

for (int i = 0; i < linksArray.length; i++) {
    startMyTask(new BackgroundTask(), "" + linksArray[i], "" + i);
}
Community
  • 1
  • 1
ACBM
  • 657
  • 1
  • 10
  • 26
0

Try first to load the text in a not asynctask using the console to see the result, maybe it's not a problem of the backgroundworker, it could be something in your logic when you read the text. If you show us that code it would be helpfull in order to find the origin of the problem

Edit: So i think the correct aproach is to send the array to the asyncTask

new BackgroundTask().execute(linksArray);

and let it do all the work

@Override
protected ArrayList<String> doInBackground(String[]... params) {
    try {
        String[] json_urls = paramas[0];
        //create array list that contains json strings
        ArrayList<String> json_strings = new ArrayList<String>();

        for (int i = 0; i < json_urls.length; i++) {
            json_url = json_urls[i];
            number = i;
            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();
            json_strings.add(stringBuilder.toString().trim());
        }
        return json_strings;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPostExecute(ArrayList<String> result) {
    loading.setVisibility(View.GONE);
    if (result!=null)   //PREVENTS INTERNET CRASH!
        loadJSON(result);
}
}

public void loadJSON(ArrayList<String> json_strings) {
    for (int i = 0; i < json_strings.size(); i++) {
        JSONresult = json_strings.get(i);
        System.out.println("test2 " + i);
    }
}

Also, don't forget to change the asyncTask declaration, something like this:

public class BackgroundTask extends AsyncTask<String[], Void, ArrayList<String>>{
//your methods here
}
karique
  • 533
  • 6
  • 17
  • Added some more code now. Hope it clears things up. I'm currently having trouble following given solutions or instructions as I am quite new to programming in general. – Erik Feb 16 '17 at 15:56
  • please, check my edit, maybe it could help :) – karique Feb 16 '17 at 17:04
  • Looks like a possible solution, think i forgo the asyncTask declaration when I tried it. I'll try it tomorrow and mark as accepted if it works since i mannaged to make a workaround that works fine. Wrote about it in the question :P – Erik Feb 16 '17 at 17:13
  • I believe this fills the purpose, didn't try it fully because my own solution fits the further work of the activity better. But thanks anyway =) – Erik Feb 17 '17 at 07:02