use of androidx.lifecycle.ViewModelProvider in project grocy-android by patzly.
the class TransferFragment method onViewCreated.
@Override
public void onViewCreated(@Nullable View view, @Nullable Bundle savedInstanceState) {
activity = (MainActivity) requireActivity();
TransferFragmentArgs args = TransferFragmentArgs.fromBundle(requireArguments());
viewModel = new ViewModelProvider(this, new TransferViewModelFactory(activity.getApplication(), args)).get(TransferViewModel.class);
binding.setActivity(activity);
binding.setViewModel(viewModel);
binding.setFragment(this);
binding.setFormData(viewModel.getFormData());
binding.setLifecycleOwner(getViewLifecycleOwner());
infoFullscreenHelper = new InfoFullscreenHelper(binding.container);
viewModel.getInfoFullscreenLive().observe(getViewLifecycleOwner(), infoFullscreen -> infoFullscreenHelper.setInfo(infoFullscreen));
viewModel.getIsLoadingLive().observe(getViewLifecycleOwner(), isDownloading -> binding.swipe.setRefreshing(isDownloading));
viewModel.getEventHandler().observeEvent(getViewLifecycleOwner(), event -> {
if (event.getType() == Event.SNACKBAR_MESSAGE) {
activity.showSnackbar(((SnackbarMessage) event).getSnackbar(activity, activity.binding.frameMainContainer));
} else if (event.getType() == Event.CONSUME_SUCCESS) {
assert getArguments() != null;
if (PurchaseFragmentArgs.fromBundle(getArguments()).getCloseWhenFinished()) {
activity.navigateUp();
} else {
viewModel.getFormData().clearForm();
focusProductInputIfNecessary();
embeddedFragmentScanner.startScannerIfVisible();
}
} else if (event.getType() == Event.BOTTOM_SHEET) {
BottomSheetEvent bottomSheetEvent = (BottomSheetEvent) event;
activity.showBottomSheet(bottomSheetEvent.getBottomSheet(), event.getBundle());
} else if (event.getType() == Event.FOCUS_INVALID_VIEWS) {
focusNextInvalidView();
} else if (event.getType() == Event.QUICK_MODE_ENABLED) {
focusProductInputIfNecessary();
} else if (event.getType() == Event.QUICK_MODE_DISABLED) {
clearInputFocus();
} else if (event.getType() == Event.CONTINUE_SCANNING) {
embeddedFragmentScanner.startScannerIfVisible();
} else if (event.getType() == Event.CHOOSE_PRODUCT) {
String barcode = event.getBundle().getString(ARGUMENT.BARCODE);
navigate(TransferFragmentDirections.actionTransferFragmentToChooseProductFragment(barcode).setForbidCreateProduct(true));
}
});
Integer productIdSavedSate = (Integer) getFromThisDestinationNow(Constants.ARGUMENT.PRODUCT_ID);
if (productIdSavedSate != null) {
removeForThisDestination(Constants.ARGUMENT.PRODUCT_ID);
viewModel.setQueueEmptyAction(() -> viewModel.setProduct(productIdSavedSate, null, null));
} else if (NumUtil.isStringInt(args.getProductId())) {
int productId = Integer.parseInt(args.getProductId());
setArguments(new TransferFragmentArgs.Builder(args).setProductId(null).build().toBundle());
viewModel.setQueueEmptyAction(() -> viewModel.setProduct(productId, null, null));
}
String barcode = (String) getFromThisDestinationNow(ARGUMENT.BARCODE);
if (barcode != null) {
removeForThisDestination(Constants.ARGUMENT.BARCODE);
viewModel.addBarcodeToExistingProduct(barcode);
}
embeddedFragmentScanner.setScannerVisibilityLive(viewModel.getFormData().getScannerVisibilityLive());
// following line is necessary because no observers are set in Views
viewModel.getFormData().getQuantityUnitStockLive().observe(getViewLifecycleOwner(), i -> {
});
if (savedInstanceState == null) {
viewModel.loadFromDatabase(true);
}
focusProductInputIfNecessary();
updateUI(args.getAnimateStart() && savedInstanceState == null);
}
use of androidx.lifecycle.ViewModelProvider in project grocy-android by patzly.
the class ShoppingModeFragment method onViewCreated.
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
activity = (MainActivity) requireActivity();
viewModel = new ViewModelProvider(this).get(ShoppingModeViewModel.class);
viewModel.setOfflineLive(!activity.isOnline());
binding.setViewModel(viewModel);
binding.setActivity(activity);
binding.setFragment(this);
binding.setLifecycleOwner(getViewLifecycleOwner());
infoFullscreenHelper = new InfoFullscreenHelper(binding.frame);
clickUtil = new ClickUtil();
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
debug = PrefsUtil.isDebuggingEnabled(sharedPrefs);
handler = new Handler();
if (savedInstanceState == null) {
binding.recycler.scrollTo(0, 0);
}
binding.recycler.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
binding.recycler.setAdapter(new ShoppingPlaceholderAdapter());
viewModel.getIsLoadingLive().observe(getViewLifecycleOwner(), state -> {
if (!state) {
viewModel.setCurrentQueueLoading(null);
}
});
viewModel.getInfoFullscreenLive().observe(getViewLifecycleOwner(), infoFullscreen -> infoFullscreenHelper.setInfo(infoFullscreen));
viewModel.getSelectedShoppingListIdLive().observe(getViewLifecycleOwner(), this::changeAppBarTitle);
viewModel.getFilteredGroupedListItemsLive().observe(getViewLifecycleOwner(), items -> {
if (items == null) {
return;
}
if (items.isEmpty()) {
InfoFullscreen info = new InfoFullscreen(InfoFullscreen.INFO_EMPTY_SHOPPING_LIST);
viewModel.getInfoFullscreenLive().setValue(info);
} else {
viewModel.getInfoFullscreenLive().setValue(null);
}
if (binding.recycler.getAdapter() instanceof ShoppingModeItemAdapter) {
((ShoppingModeItemAdapter) binding.recycler.getAdapter()).updateData(items, viewModel.getProductHashMap(), viewModel.getQuantityUnitHashMap(), viewModel.getShoppingListItemAmountsHashMap(), viewModel.getMissingProductIds());
} else {
binding.recycler.setAdapter(new ShoppingModeItemAdapter(activity, (LinearLayoutManager) binding.recycler.getLayoutManager(), items, viewModel.getProductHashMap(), viewModel.getQuantityUnitHashMap(), viewModel.getShoppingListItemAmountsHashMap(), viewModel.getMissingProductIds(), this, sharedPrefs.getBoolean(SHOPPING_MODE.USE_SMALLER_FONT, SETTINGS_DEFAULT.SHOPPING_MODE.USE_SMALLER_FONT), sharedPrefs.getBoolean(SHOPPING_MODE.SHOW_PRODUCT_DESCRIPTION, SETTINGS_DEFAULT.SHOPPING_MODE.SHOW_PRODUCT_DESCRIPTION)));
binding.recycler.scheduleLayoutAnimation();
}
});
viewModel.getEventHandler().observeEvent(getViewLifecycleOwner(), event -> {
if (event.getType() == Event.SNACKBAR_MESSAGE) {
activity.showSnackbar(((SnackbarMessage) event).getSnackbar(activity, activity.binding.frameMainContainer));
}
});
hideDisabledFeatures();
if (savedInstanceState == null) {
viewModel.loadFromDatabase(true);
}
updateUI(ShoppingModeFragmentArgs.fromBundle(requireArguments()).getAnimateStart() && savedInstanceState == null);
}
use of androidx.lifecycle.ViewModelProvider in project grocy-android by patzly.
the class TasksFragment method onViewCreated.
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
activity = (MainActivity) requireActivity();
viewModel = new ViewModelProvider(this).get(TasksViewModel.class);
viewModel.setOfflineLive(!activity.isOnline());
binding.setViewModel(viewModel);
binding.setActivity(activity);
binding.setFragment(this);
binding.setLifecycleOwner(getViewLifecycleOwner());
infoFullscreenHelper = new InfoFullscreenHelper(binding.frame);
clickUtil = new ClickUtil();
// APP BAR BEHAVIOR
appBarBehavior = new AppBarBehavior(activity, binding.appBarDefault, binding.appBarSearch, savedInstanceState);
binding.recycler.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
binding.recycler.setAdapter(new MasterPlaceholderAdapter());
if (savedInstanceState == null) {
binding.recycler.scrollToPosition(0);
viewModel.resetSearch();
}
viewModel.getIsLoadingLive().observe(getViewLifecycleOwner(), state -> {
if (!state) {
viewModel.setCurrentQueueLoading(null);
}
});
viewModel.getInfoFullscreenLive().observe(getViewLifecycleOwner(), infoFullscreen -> infoFullscreenHelper.setInfo(infoFullscreen));
viewModel.getFilteredTasksLive().observe(getViewLifecycleOwner(), items -> {
if (items == null) {
return;
}
if (items.isEmpty()) {
InfoFullscreen info;
if (viewModel.isSearchActive()) {
info = new InfoFullscreen(InfoFullscreen.INFO_NO_SEARCH_RESULTS);
} else {
info = new InfoFullscreen(InfoFullscreen.INFO_EMPTY_TASKS);
}
viewModel.getInfoFullscreenLive().setValue(info);
} else {
viewModel.getInfoFullscreenLive().setValue(null);
}
if (binding.recycler.getAdapter() instanceof TasksItemAdapter) {
((TasksItemAdapter) binding.recycler.getAdapter()).updateData(items, viewModel.getSortMode());
} else {
binding.recycler.setAdapter(new TasksItemAdapter(requireContext(), items, this, viewModel.getSortMode()));
}
});
viewModel.getEventHandler().observeEvent(getViewLifecycleOwner(), event -> {
if (event.getType() == Event.SNACKBAR_MESSAGE) {
activity.showSnackbar(((SnackbarMessage) event).getSnackbar(activity, activity.binding.frameMainContainer));
}
});
if (swipeBehavior == null) {
swipeBehavior = new SwipeBehavior(activity, swipeStarted -> binding.swipe.setEnabled(!swipeStarted)) {
@Override
public void instantiateUnderlayButton(RecyclerView.ViewHolder viewHolder, List<UnderlayButton> underlayButtons) {
int position = viewHolder.getAdapterPosition();
ArrayList<Task> displayedItems = viewModel.getFilteredTasksLive().getValue();
if (displayedItems == null || position < 0 || position >= displayedItems.size()) {
return;
}
Task task = displayedItems.get(position);
underlayButtons.add(new UnderlayButton(R.drawable.ic_round_done, pos -> {
if (pos >= displayedItems.size()) {
return;
}
swipeBehavior.recoverLatestSwipedItem();
viewModel.performAction(ACTION.UNDO, displayedItems.get(pos));
}));
}
};
}
swipeBehavior.attachToRecyclerView(binding.recycler);
hideDisabledFeatures();
if (savedInstanceState == null) {
viewModel.loadFromDatabase(true);
}
updateUI(savedInstanceState == null);
}
use of androidx.lifecycle.ViewModelProvider in project OpenBot by isl-org.
the class ControlsFragment method onViewCreated.
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
requireActivity().getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
phoneController = PhoneController.getInstance(requireContext());
preferencesManager = new SharedPreferencesManager(requireContext());
audioPlayer = new AudioPlayer(requireContext());
masterList = FileUtils.loadConfigJSONFromAsset(requireActivity());
serverCommunication = new ServerCommunication(requireContext(), this);
requireActivity().getSupportFragmentManager().setFragmentResultListener(Constants.GENERIC_MOTION_EVENT, this, (requestKey, result) -> {
MotionEvent motionEvent = result.getParcelable(Constants.DATA);
vehicle.setControl(vehicle.getGameController().processJoystickInput(motionEvent, -1));
processControllerKeyData(Constants.CMD_DRIVE);
});
requireActivity().getSupportFragmentManager().setFragmentResultListener(Constants.KEY_EVENT, this, (requestKey, result) -> processKeyEvent(result.getParcelable(Constants.DATA)));
mViewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
vehicle = mViewModel.getVehicle().getValue();
startAnimation = AnimationUtils.loadAnimation(requireContext(), R.anim.blink);
mViewModel.getUsbData().observe(getViewLifecycleOwner(), data -> {
char header = data.charAt(0);
String body = data.substring(1);
switch(header) {
case 'f':
vehicle.processVehicleConfig(body);
break;
case 'v':
if (FormatUtils.isNumeric(body)) {
vehicle.setBatteryVoltage(Float.parseFloat(body));
} else {
String[] msgParts = body.split(":");
switch(msgParts[0]) {
case "min":
vehicle.setMinMotorVoltage(Float.parseFloat(msgParts[1]));
case "low":
vehicle.setLowBatteryVoltage(Float.parseFloat(msgParts[1]));
break;
case "max":
vehicle.setMaxBatteryVoltage(Float.parseFloat(msgParts[1]));
break;
default:
Toast.makeText(requireContext().getApplicationContext(), "Invalid voltage message received!", Toast.LENGTH_SHORT).show();
break;
}
}
break;
case 's':
if (FormatUtils.isNumeric(body)) {
vehicle.setSonarReading(Float.parseFloat(body));
}
break;
case 'w':
String[] itemList = body.split(",");
if (itemList.length == 2 && FormatUtils.isNumeric(itemList[0]) && FormatUtils.isNumeric(itemList[1])) {
vehicle.setLeftWheelRpm(Float.parseFloat(itemList[0]));
vehicle.setRightWheelRpm(Float.parseFloat(itemList[1]));
}
break;
case 'b':
// do nothing
break;
}
processUSBData(data);
});
handlePhoneControllerEvents();
vehicle.requestVehicleConfig();
}
use of androidx.lifecycle.ViewModelProvider in project OpenBot by isl-org.
the class MainActivity method onCreate.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewModel = new ViewModelProvider(this).get(MainViewModel.class);
vehicle = OpenBotApplication.vehicle;
// if (vehicle == null) {
// SharedPreferences sharedPreferences =
// PreferenceManager.getDefaultSharedPreferences(this);
// int baudRate = Integer.parseInt(sharedPreferences.getString("baud_rate", "115200"));
// vehicle = new Vehicle(this, baudRate);
// vehicle.connectUsb();
viewModel.setVehicle(vehicle);
// }
localBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null) {
switch(action) {
case UsbManager.ACTION_USB_DEVICE_ATTACHED:
if (!vehicle.isUsbConnected()) {
vehicle.connectUsb();
viewModel.setUsbStatus(vehicle.isUsbConnected());
}
Timber.i("USB device attached");
break;
// Case activated when app is not set to open default when usb is connected
case UsbConnection.ACTION_USB_PERMISSION:
synchronized (this) {
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (usbDevice != null) {
// call method to set up device communication
if (!vehicle.isUsbConnected()) {
vehicle.connectUsb();
}
viewModel.setUsbStatus(vehicle.isUsbConnected());
Timber.i("USB device attached");
}
}
}
break;
case UsbManager.ACTION_USB_DEVICE_DETACHED:
vehicle.disconnectUsb();
viewModel.setUsbStatus(vehicle.isUsbConnected());
Timber.i("USB device detached");
break;
case USB_ACTION_DATA_RECEIVED:
viewModel.setUsbData(intent.getStringExtra("data"));
break;
}
}
}
};
IntentFilter localIntentFilter = new IntentFilter();
localIntentFilter.addAction(USB_ACTION_DATA_RECEIVED);
localIntentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
localIntentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
localIntentFilter.addAction(UsbConnection.ACTION_USB_PERMISSION);
localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.registerReceiver(localBroadcastReceiver, localIntentFilter);
registerReceiver(localBroadcastReceiver, localIntentFilter);
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
NavController navController = navHostFragment.getNavController();
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration);
navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
if (destination.getId() == R.id.mainFragment || destination.getId() == R.id.settingsFragment)
toolbar.setVisibility(View.VISIBLE);
else
toolbar.setVisibility(View.GONE);
});
// if (savedInstanceState == null) {
// // Default to open this when app opens
// Intent intent = new Intent(this, DefaultActivity.class);
// startActivity(intent);
// }
}
Aggregations