如何解决为什么在我传递参数时没有调用第二个方法?
我以前从未见过,这很奇怪。我在 TestsViewModel.class 中有处理程序。我需要在 startMapThreads() 方法 (startMapThreads(viewModel.handler)) 中像参数一样设置它。当我在没有处理程序的情况下调用它时,一切正常。但是如果我设置像参数这样的处理程序,它就无法到达第二种方法。我也不做任何更改,只添加参数。有谁知道为什么我不能和参数一起到达第二种方法?
在第一张图片上,我到达了 3 方法,在第二张图片中,只有处理程序参数的第一个方法。
public class TestsViewModel extends ViewModel {
public MutableLiveData<DataClass> testResult = new MutableLiveData<>();
public Handler handler;
public TestsViewModel() {
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.i("tester","result: " + (DataClass) msg.obj);
}
};
}
}
public class FragmentMaps extends Fragment {
private static FragmentMaps mapsInstance;
private static FragmentMapsBinding binding;
public TestsViewModel viewModel;
public static FragmentMaps getMapsInstance() {
if (mapsInstance == null) {
mapsInstance = new FragmentMaps();
}
return mapsInstance;
}
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
binding = FragmentMapsBinding.inflate(inflater,container,false);
initObjects();
return binding.getRoot();
}
private void initObjects() {
viewModel = new ViewModelProvider(this,new TestModelFactory())
.get(TestsViewModel.class);
}
public void startMapThreads() {
Log.i("tester","method called 1");
ThreadsManager threadsManager = new ThreadsManager();
threadsManager.startMapThreads();
//displayProgressBars();
}
}
public class ThreadsManager {
public static boolean stopThreads = false; //We change this variable MainActivity
public static long timeOfStartTest = 0;
public void startMapThreads() {
Log.i("tester","method called 2");
createMapThreadWithMap(() -> new TreeMap());
createMapThreadWithMap(() -> new HashMap());
}
private void createMapThreadWithMap(MapFactory mapFactory) {
Log.i("tester","method called 3");
stopThreads = false;
timeOfStartTest = new Date().getTime();
MapRunnable mapRunnable = new MapRunnable();
new Thread(mapRunnable.addingNew(mapFactory.create())).start();
new Thread(mapRunnable.searchByKey(mapFactory.create())).start();
new Thread(mapRunnable.removing(mapFactory.create())).start();
}
}
解决方法
我终于找到了这一切的原因。我在 viewModel 中创建了处理程序,并在构造函数中初始化了它。但我没有初始化looper。因此,当我尝试获取方法 2 时,它处于另一个循环中。处理程序构造函数重复,您需要像这样初始化:
Handler handler = new Handler(Looper.getMainLooper());
重复:
Handler handler = new Handler();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。