[英]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. 我的嵌套Java类有问题,它看到外部类对象,但以某种方式无法对其进行修改。 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.
我有Sorter类在后台执行一些计算,我决定使用AsyncTask在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. 我试图在Sorter构造函数中实例化workingList,但是嵌套类无论如何都无法将项目添加到workingList。 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?
指示您要实例化Sorter类的对象?
So, the first thing to fix your problem - get a better understanding of the concepts you are using. 因此,解决问题的第一件事-更好地了解您所使用的概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.