简体   繁体   中英

Nested class AsyncTask can't modify Outer Class static objects

I have a problem with Nested java class, it sees outer class object but somehow fails to modify it. I read a lot of similar questions but couldn't find solution for this one. It might be something really simple but I'm not good enough to figure it out. I have Sorter class to do some calculations in the background, I decided to use AsyncTask to perform those calculations outside of UI Thread. My class looks like this

public class Sorter
{
    private static List<Long> workingList;
    private static int _numberOfContainers, _containerSize, _timesToRepeat;
    private static Long _numbersFrom, _numbersTo, _sortingAlgorithmId;

    public Sorter(int numberOfContainers, int containerSize, Long numbersFrom, Long numbersTo,
                  int timesToRepeat, Long sortingAlgorithmId)
    {
        _numberOfContainers = numberOfContainers;
        _containerSize = containerSize;
        _numbersFrom = numbersFrom;
        _numbersTo = numbersTo;
        _timesToRepeat = timesToRepeat;
        _sortingAlgorithmId = sortingAlgorithmId;
        // perform calculations in the background
        new BackgroundCalculations().execute();
    }

    static class BackgroundCalculations extends AsyncTask<Void,Void,Void>
    {

        @Override
        protected Void doInBackground(Void... voids)
        {
            workingList = new ArrayList<>(_containerSize);
            // workingList is still null after this
            _numbersTo += 1; // to fix exclusive number range to inclusive
            Random rand = new Random();
            for (int i = 0; i < _containerSize; i++)
            {
                workingList.add((long) (rand.nextDouble() * (_numbersTo - _numbersFrom)) + _numbersFrom))
            }
            // some calc
            return null;
        }
    }


}

I tried to instantiate workingList in Sorter constructor but nested class fails to add items to workingList anyway. Any solutions? Maybe better way to implement background calculations without such problems?

You are mixing up two concepts here.

Your methods are all static; and your fields are two. So why do you then use a constructor; indicating that you want an object of your Sorter class to be instantiated?

So, the first thing to fix your problem - get a better understanding of the concepts you are using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM