Can we write JUnits for JavaFX? - javafx

I am currently working on a javafx project. I want to write the JUnit test cases for it how can i write it?
I am really not sure about writing the junit test cases for it?
I can do functional testing but not sure about writing JUnit.
Suppose I have a below method :
#FXML
public void makeDeviceContentsEditable() {
ObservableList<TextField> list = FXCollections.observableArrayList(vehicleId, vehicleName, deviceType,
offboardBroker1, offboardBroker2, postfixQueue, pKIServer);
if (editDeviceContents.isSelected() && devicePlugged) {
isDeviceSideEnabled();
for (final TextField tf : list) {
tf.setEditable(true);
tf.setStyle(GREY_OUT_REMOVED);
final String originalval = tf.getText();
tf.textProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable, String oldValue,
String newValue) {
//if (!originalval.isEmpty() && originalval != null & isWritten) {
if (originalval != null && !originalval.isEmpty() && isWritten) {
tf.setStyle(CHANGED_TXT_COLOR);
if (newValue.equalsIgnoreCase(originalval)) {
tf.setStyle(NORMAL_COLOR);
}
if (tf.getId().equalsIgnoreCase("vehicleId")) {
editedValuesMap.put(0, newValue);
} else if (tf.getId().equalsIgnoreCase("vehicleName")) {
editedValuesMap.put(1, newValue);
} else if (tf.getId().equalsIgnoreCase("deviceType")) {
editedValuesMap.put(2, newValue);
} else if (tf.getId().equalsIgnoreCase("offboardBroker1")) {
editedValuesMap.put(3, newValue);
} else if (tf.getId().equalsIgnoreCase("offboardBroker2")) {
editedValuesMap.put(4, newValue);
} else if (tf.getId().equalsIgnoreCase("postfixQueue")) {
editedValuesMap.put(5, newValue);
} else if (tf.getId().equalsIgnoreCase("pKIServer")) {
editedValuesMap.put(6, newValue);
}
}
maxTextFieldLengthCheck(tf, newValue);
}
});
}
} else if (!editDeviceContents.isSelected()) {
for (final TextField tf : list) {
tf.setEditable(false);
}
textfieldStyle(TEXTFIELD_GREY_OUT);
bWriteToDevice.setDisable(true);
}
//isWritten=false;
}

Related

D365 new form is not populated with values

There is need to show all parts of one area. I created new form PMCContractAreasDialog. When I click on specific contract line into contract form it should open new form and show all parts of one area. In sum there should be same like on contract line. But every time when I click on button form is empty. Am I missing something ?
[Form]
public class PMCContractAreasDialog extends FormRun
{
[FormObservable]
date currWorkingDate;
[FormObservable]
boolean commonAreasRead;
PMERentalObjectAreaValueCl tmpRentalAreaCl;
PMETmpRentalObjectArea tmpArea;
public void init ()
{
super();
pmcContractLine_ds.linkActive();
}
public void activate(boolean _active)
{
PMCContractArea contractArea;
AmountMST sumContractArea;
pmcContractLine_ds.readCommonAreas(pmcContractLine);
h1_h2.realValue(pmcContractLine_ds.h1_h2(pmcContractLine));
efa.realValue(pmcContractLine_ds.efa(pmcContractLine));
bfa.realValue(pmcContractLine_ds.bfa(pmcContractLine));
mfa.realValue(pmcContractLine_ds.mfa(pmcContractLine));
sumArea.realValue(h1_h2.realValue() + efa.realValue() + bfa.realValue() + mfa.realValue());
}
[DataSource]
class PMCContract
{
public int active()
{
int ret;
ret = super();
return ret;
}
}
[DataSource]
class PMCContractLine
{
public int active()
{
int ret;
ret = super();
return ret;
}
display PMEAreaCommonBuildingSum BFA(PMCContractLine _contractLine)
{
if (commonAreasRead)
{
if (_contractLine.RentalObjectId)
{
return PMERentalObjectAreaCl::getRentalObjectCommonAreaBuildingSum(_contractLine.RentalObjectId, currWorkingDate, tmpArea, false);
}
else
{
return 0;
}
}
return 0;
}
void readCommonAreas(PMCContractLine _contractLine)
{
if (!commonAreasRead)
{
if (pmcContractLine.RentalObjectId)
{
tmpRentalAreaCl = new PMERentalObjectAreaValueCl();
tmpRentalAreaCl.clear();
tmpRentalAreaCl.getRentalObjectAreas(_contractLine.RentalObjectId, PMGUser::find().currDate());
tmpArea.setTmpData(tmpRentalAreaCl.getTempTable());
commonAreasRead = true;
}
}
}
//BP Deviation Documented
display PMEAreaCommonSectionSum EFA(PMCContractLine _contractLine)
{
if (commonAreasRead)
{
if (_contractLine.RentalObjectId)
{
return PMERentalObjectAreaCl::getRentalObjectCommonAreaSectionSum(_contractLine.RentalObjectId, currWorkingDate, tmpArea, false);
}
else
{
return 0;
}
}
return 0;
}
//BP Deviation Documented
display PMEAreaTotal H1_H2(PMCContractLine _contractLine)
{
if (commonAreasRead)
{
if (_contractLine.RentalObjectId)
{
return PMERentalObjectAreaCl::getRentalObjectMainAreaSectionSum(_contractLine.RentalObjectId, currWorkingDate, tmpArea, false);
}
else
{
return 0;
}
}
return 0;
}
//BP Deviation Documented
display PMEAreaTotal MFA(PMCContractLine _contractLine)
{
if (commonAreasRead)
{
if (_contractLine.RentalObjectId)
{
return PMERentalObjectAreaCl::getRentalObjectCommonAreaFixedSum(_contractLine.RentalObjectId, currWorkingDate, tmpArea, false);
}
else
{
return 0;
}
}
return 0;
}
}
[DataSource]
class PMCContractArea
{
public void delete()
{
super();
this.updateLines();
}
public void write()
{
super();
this.updateLines();
}
void updateLines()
{
;
PMCContractArea::updateLineAreas(pmcContractArea.ContractId, pmcContractArea.RentalObjectId);
}
}
}

How can i integrate QR-reader in Weex App?

React.Native has plugins like react-native-qrcode-scanner.
How can I do that on Weex?
Here comes a solution named EMAS. like weex-market, there are a lot of components and modules. One of these is the scan component which meets your requirement.
But the portal website is only in the Chinese language now.
Here is an android demo using ZXing to do qrcode. Copy this and register as a scan component. Have a look at this Demo.
public class WXQRCodeScannerComponent extends WXComponent<ZXingScannerView> implements ZXingScannerView.ResultHandler{
private static final String VF_WIDTH = "vfWidth";
private static final String VF_HEIGHT = "vfHeight";
private static final String VF_TOP_MARGIN = "vfTopMargin";
private static final String AUTO_STOP = "autoStop";
private static final String ON_SCAN = "scan";
private static final String TAG = "scan";
private boolean isAutoStop = false;
private boolean hasScanned = false;
private Handler mHandler = new Handler(Looper.getMainLooper());
private static final int CAMERA_PERMISSION_REQUEST_CODE = 0x1001;
private OnRequestPermissionCallback mPermissionCallback = new OnRequestPermissionCallback() {
#Override
public void onPermissionGranted() {
ZXingScannerView hostView = getHostView();
if(hostView != null) {
hostView.startCamera();
}
}
#Override
public void onPermissionDenied() {
// nope
}
};
public WXQRCodeScannerComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent) {
super(instance, dom, parent);
}
public WXQRCodeScannerComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, int type) {
super(instance, dom, parent, type);
}
#Override
protected ZXingScannerView initComponentHostView(#NonNull Context context) {
requestPermissionIfNeeded();
ZXingScannerView qrCodeView = new ZXingScannerView(context);
qrCodeView.setSquareViewFinder(true);
qrCodeView.setResultHandler(this); // Register ourselves as a handler for scan results.
return qrCodeView;
}
private void requestPermissionIfNeeded() {
Context c = getContext();
if(c != null && c instanceof Activity) {
if(ContextCompat.checkSelfPermission(c, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) c, Manifest.permission.CAMERA)) {
Toast.makeText(c, "请授予相机权限以用于扫码", Toast.LENGTH_LONG).show();
}
LocalBroadcastManager.getInstance(c)
.registerReceiver(new InnerReceiver(mPermissionCallback), new IntentFilter(WXModule.ACTION_REQUEST_PERMISSIONS_RESULT));
ActivityCompat.requestPermissions((Activity) c,
new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
} else {
//Nope
}
}
}
static class InnerReceiver extends BroadcastReceiver{
private OnRequestPermissionCallback mCallback;
InnerReceiver(OnRequestPermissionCallback callback) {
this.mCallback = callback;
}
#Override
public void onReceive(Context context, Intent intent) {
int code = intent.getIntExtra(WXModule.REQUEST_CODE, 0);
int[] grantResults = intent.getIntArrayExtra(WXModule.GRANT_RESULTS);
String[] permissions = intent.getStringArrayExtra(WXModule.PERMISSIONS);
if(code == CAMERA_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限申请成功
if(mCallback != null) {
mCallback.onPermissionGranted();
}
} else {
Toast.makeText(context, "相机权限申请失败!将无法使用扫码功能!", Toast.LENGTH_SHORT).show();
if(mCallback != null) {
mCallback.onPermissionDenied();
}
}
}
LocalBroadcastManager.getInstance(context).unregisterReceiver(this);
}
}
interface OnRequestPermissionCallback {
void onPermissionGranted();
void onPermissionDenied();
}
#Override
protected boolean setProperty(String key, Object param) {
switch (key) {
case VF_WIDTH:
Float width = WXUtils.getFloat(param,null);
if(width != null) {
setVfWidth(width);
}
return true;
case VF_HEIGHT:
Float height = WXUtils.getFloat(param,null);
if(height != null) {
setVfHeight(height);
}
return true;
case VF_TOP_MARGIN:
Float topMargin = WXUtils.getFloat(param,null);
if(topMargin != null) {
setVfTopMargin(topMargin);
}
return true;
case AUTO_STOP:
Boolean autoStop = WXUtils.getBoolean(param, false);
if(autoStop != null) {
setAutoStop(autoStop);
}
return true;
}
return super.setProperty(key, param);
}
#Override
protected void onHostViewInitialized(ZXingScannerView host) {
super.onHostViewInitialized(host);
ZXingScannerView hostView = getHostView();
if(hostView != null) {
hostView.startCamera();
}
}
#WXComponentProp(name = VF_WIDTH)
public void setVfWidth(float width) {
float finalWidth = WXViewUtils.getRealSubPxByWidth(width,getInstance().getInstanceViewPortWidth());
if(getHostView() != null) {
// ScanBoxView scanBoxView = getHostView().getScanBox();
// if(scanBoxView != null) {
// scanBoxView.setRectWidth((int) finalWidth);
// }
}
}
#WXComponentProp(name = VF_HEIGHT)
public void setVfHeight(float height) {
float finalHeight = WXViewUtils.getRealSubPxByWidth(height,getInstance().getInstanceViewPortWidth());
if(getHostView() != null) {
// ScanBoxView scanBoxView = getHostView().getScanBox();
// if(scanBoxView != null) {
// scanBoxView.setRectHeight((int) finalHeight);
// }
}
}
#WXComponentProp(name = VF_TOP_MARGIN)
public void setVfTopMargin(float topMargin) {
float finalTopMargin = WXViewUtils.getRealSubPxByWidth(topMargin,getInstance().getInstanceViewPortWidth());
if(getHostView() != null) {
// ScanBoxView scanBoxView = getHostView().getScanBox();
// if(scanBoxView != null) {
// scanBoxView.setTopOffset((int) finalTopMargin);
// }
}
}
#WXComponentProp(name = AUTO_STOP)
public void setAutoStop(boolean autoStop) {
this.isAutoStop = autoStop;
}
#Override
public void onActivityResume() {
super.onActivityResume();
ZXingScannerView hostView = getHostView();
if(hostView != null) {
hostView.startCamera();
}
}
#Override
public void onActivityPause() {
super.onActivityPause();
ZXingScannerView hostView = getHostView();
if(hostView != null) {
hostView.stopCamera(); // Stop camera on pause
}
}
#Override
public void onActivityDestroy() {
if(mHandler != null) {
ZXingScannerView hostView = getHostView();
if(hostView != null) {
hostView.stopCamera();
}
mHandler.removeCallbacksAndMessages(null);
}
}
#Override
public void handleResult(Result result) {
if(isAutoStop && hasScanned) {
resumeCameraPreviewDelayed();
return;
}
fireEventByResult(result);
resumeCameraPreviewDelayed();
hasScanned = true;
}
private void fireEventByResult(Result result) {
if(result == null || TextUtils.isEmpty(result.getText())) {
Map<String,Object> callback = new HashMap<>(4);
callback.put("result","failed");
fireEvent(ON_SCAN,callback);
if(WXEnvironment.isApkDebugable()) {
WXLogUtils.d(TAG, "scan failed");
}
} else {
Map<String,String> data = new HashMap<>(4);
data.put("timestamp", System.currentTimeMillis()+"");
data.put("code", result.getText());
Map<String,Object> callback = new HashMap<>(4);
callback.put("result","success");
callback.put("data", data);
fireEvent(ON_SCAN,callback);
if(WXEnvironment.isApkDebugable()) {
WXLogUtils.d(TAG, "scan success: " + result.getText());
}
}
}
private void resumeCameraPreviewDelayed() {
if(mHandler == null) {
return;
}
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
ZXingScannerView hostView = getHostView();
if(hostView != null) {
hostView.resumeCameraPreview(WXQRCodeScannerComponent.this);
}
}
}, 1000);
}
}

onRequestPermissionsResult() does not finish before onViewCreated() conduct

public class PdfRendererBasicFragment extends Fragment implements View.OnClickListener {
/**
* Key string for saving the state of current page index.
*/
private static final String STATE_CURRENT_PAGE_INDEX = "current_page_index";
public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
/**
* File descriptor of the PDF.
*/
/**
* {#link android.graphics.pdf.PdfRenderer} to render the PDF.
*/
private PdfRenderer mPdfRenderer;
/**
* Page that is currently shown on the screen.
*/
private PdfRenderer.Page mCurrentPage;
/**
* {#link android.widget.ImageView} that shows a PDF page as a {#link android.graphics.Bitmap}
*/
private ImageView mImageView;
/**
* {#link android.widget.Button} to move to the previous page.
*/
private Button mButtonPrevious;
/**
* {#link android.widget.Button} to move to the next page.
*/
private Button mButtonNext;
private Bundle copySavedInstanceState;
public PdfRendererBasicFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_pdf_renderer_basic, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Retain view references.
mImageView = (ImageView) view.findViewById(R.id.image);
mButtonPrevious = (Button) view.findViewById(R.id.previous);
mButtonNext = (Button) view.findViewById(R.id.next);
// Bind events.
mButtonPrevious.setOnClickListener(this);
mButtonNext.setOnClickListener(this);
mImageView.setOnClickListener(this);
copySavedInstanceState = savedInstanceState;
while (true) {
int rc = ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (rc == PackageManager.PERMISSION_GRANTED)
break;
}
// Show the first page by default.
int index = 0;
// If there is a savedInstanceState (screen orientations, etc.), we restore the page index.
if (null != copySavedInstanceState) {
index = copySavedInstanceState.getInt(STATE_CURRENT_PAGE_INDEX, 0);
}
Log.d("check","index : " + index);
showPage(index);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
int rc = ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (rc == PackageManager.PERMISSION_GRANTED) {
try {
openRenderer(activity);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(activity, "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
activity.finish();
}
} else {
requestExternalStoragePermission();
}
}
#Override
public void onDetach() {
try {
closeRenderer();
} catch (IOException e) {
e.printStackTrace();
}
super.onDetach();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mCurrentPage) {
outState.putInt(STATE_CURRENT_PAGE_INDEX, mCurrentPage.getIndex());
}
}
private void requestExternalStoragePermission() {
final String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(getActivity(), permissions, EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
return;
}
final Activity thisActivity = getActivity();
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(thisActivity, permissions,
EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
};
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
Log.d("TAG", "Got unexpected permission result: " + requestCode);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
return;
}
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("TAG", "Camera permission granted - initialize the camera source");
// we have permission, so can read SD Card now.
try {
openRenderer(getActivity());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
getActivity().finish();
}
return;
}
Log.e("TAG", "Permission not granted: results len = " + grantResults.length +
" Result code = " + (grantResults.length > 0 ? grantResults[0] : "(empty)"));
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
};
}
/**
* Sets up a {#link android.graphics.pdf.PdfRenderer} and related resources.
*/
private void openRenderer(Context context) throws IOException {
File file = new File("/sdcard/Download/test.pdf");
mPdfRenderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
}
/**
* Closes the {#link android.graphics.pdf.PdfRenderer} and related resources.
*
* #throws java.io.IOException When the PDF file cannot be closed.
*/
private void closeRenderer() throws IOException {
if (null != mCurrentPage) {
mCurrentPage.close();
}
mPdfRenderer.close();
}
/**
* Shows the specified page of PDF to the screen.
*
* #param index The page index.
*/
private void showPage(int index) {
if (mPdfRenderer.getPageCount() <= index) {
return;
}
// Make sure to close the current page before opening another one.
if (null != mCurrentPage) {
mCurrentPage.close();
}
// Use `openPage` to open a specific page in PDF.
mCurrentPage = mPdfRenderer.openPage(index);
// Important: the destination bitmap must be ARGB (not RGB).
Bitmap bitmap = Bitmap.createBitmap(mCurrentPage.getWidth(), mCurrentPage.getHeight(),
Bitmap.Config.ARGB_8888);
// Here, we render the page onto the Bitmap.
// To render a portion of the page, use the second and third parameter. Pass nulls to get
// the default result.
// Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
mCurrentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
// We are ready to show the Bitmap to user.
mImageView.setImageBitmap(bitmap);
updateUi();
}
/**
* Updates the state of 2 control buttons in response to the current page index.
*/
private void updateUi() {
int index = mCurrentPage.getIndex();
int pageCount = mPdfRenderer.getPageCount();
mButtonPrevious.setEnabled(0 != index);
mButtonNext.setEnabled(index + 1 < pageCount);
getActivity().setTitle(getString(R.string.app_name_with_index, index + 1, pageCount));
}
/**
* Gets the number of pages in the PDF. This method is marked as public for testing.
*
* #return The number of pages.
*/
public int getPageCount() {
return mPdfRenderer.getPageCount();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.previous: {
// Move to the previous page
showPage(mCurrentPage.getIndex() - 1);
break;
}
case R.id.next: {
// Move to the next page
Log.d("name", mCurrentPage.getIndex() + "");
showPage(mCurrentPage.getIndex() + 1);
break;
}
case R.id.image: {
Log.d("name", mCurrentPage.getIndex() + "");
break;
}
}
}
}
HI, this is my code.
I try to fix. but it's not going well.
problem is this.
When I conduct this app. Android request permission, and I Approve.
but at that time android perform 'onViewCreated(View view, Bundle savedInstanceState)' method before 'openRenderer(activity)' is done.
so 'showPage(index)' raise some error. and after then (I mean permission already approved, and execute again) app doing well.
but I want to fix that.
I think
At the first time, onAttach(Activity activity) execute
and after permission approved,
onAttach(Activity activity) and
onViewCreated(View view, Bundle savedInstanceState)
methods seems to run at the same time.
Please advice me.
Thank you.
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Retain view references.
Log.d("timeStamp", "onViewCreated ");
mImageView = (ImageView) view.findViewById(R.id.image);
mButtonPrevious = (Button) view.findViewById(R.id.previous);
mButtonNext = (Button) view.findViewById(R.id.next);
// Bind events.
mButtonPrevious.setOnClickListener(this);
mButtonNext.setOnClickListener(this);
mImageView.setOnClickListener(this);
Log.d("timeStamp", "onViewCreated 할당완료");
while (true) {
int rc = getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (rc == PackageManager.PERMISSION_GRANTED){
try {
openRenderer(getActivity());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
getActivity().finish();
}
break;
}
Log.d("timeStamp", "얼마나 기다리는겨");
}
// Show the first page by default.
int index = 0;
// If there is a savedInstanceState (screen orientations, etc.), we restore the page index.
if (null != savedInstanceState) {
index = savedInstanceState.getInt(STATE_CURRENT_PAGE_INDEX, 0);
}
Log.d("timeStamp", "showPage 호출 직전");
showPage(index);
}
}
I avoid this problem to add this code.
while (true) {
int rc = getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (rc == PackageManager.PERMISSION_GRANTED){
try {
openRenderer(getActivity());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
getActivity().finish();
}
break;
}
Log.d("timeStamp", "얼마나 기다리는겨");
}
but. this is not a best.
I figured this happen because onAttach method call requestPermissions method and end. onViewCreated start before User answer to request and onRequestPermissionsResult called (So openRenderer start).
So I suspend showPage method until PERMISSION_GRANTED.

Controlling more than one properties for custom component on scenebuilder

I cannot see the old values of a property of custom component on Scene Builder.
I want to get the old value of "Speed Unit Type" to change the Min/Max values accordingly.
Maybe I can use static Min / Max values and bind these to "Speed Unit Type". But just wonderwhether it is possible to use old values at design tima on SB.
public static enum SpeedUnitType {KILO_METERS_PER_HOUR,METERS_PER_SECOND,DATA_MILES_PER_HOUR}
public static final int SPEED_MAX_DEFAULT_VALUE = 1000;
public static final int SPEED_MAX_LIMIT_VALUE = 999;
public static final double SPEED_MIN_LIMIT_VALUE = -100;
private final IntegerProperty minValue = new SimpleIntegerProperty(0);
private final IntegerProperty maxValue = new SimpleIntegerProperty(Integer.MAX_VALUE);
private final IntegerProperty value = new SimpleIntegerProperty(0);
private SpeedUnitType _speedUnit = SpeedUnitType.KILO_METERS_PER_HOUR;
private ObjectProperty<SpeedUnitType> speedUnitTypeProperty ;
public final SpeedUnitType getSpeedUnitType() {
return null == speedUnitTypeProperty ? _speedUnit : speedUnitTypeProperty.get();
}
public final void setSpeedUnitType(final SpeedUnitType UNIT) {
if (null == speedUnitTypeProperty) {
_speedUnit = UNIT;
} else {
speedUnitTypeProperty.set(UNIT);
}
}
public final ObjectProperty<SpeedUnitType> speedUnitTypeProperty() {
if (null == speedUnitTypeProperty) {
speedUnitTypeProperty = new SimpleObjectProperty<>(this, "speedUnitTypeProperty", _speedUnit);
}
return speedUnitTypeProperty;
}
public Speed() {
this.construct();
}
public void setMinValue(int min){ this.minValue.set(min); }
public int getMinValue() { return this.minValue.get(); }
public IntegerProperty minValueProperty() { return this.minValue;}
public void setMaxValue(int max) { this.maxValue.set(max);}
public int getMaxValue(){ return this.maxValue.get();}
public IntegerProperty maxValueProperty() { return this.maxValue; }
public final int getValue() { return value.get(); }
public final void setValue(final int VALUE) { value.set(VALUE);}
public final IntegerProperty valueProperty() {return value;}
private void construct()
{
this.maxValueProperty().addListener((observable, oldValue, newValue) ->
{
try
{
System.out.println("maxValueProperty --> The value was changed from " + oldValue.toString() + " to " + newValue.toString());
}
catch (Exception e)
{
System.err.println("Exception: " + e.getLocalizedMessage());
setText("ERROR");
}
});
speedUnitTypeProperty().addListener((observable, oldValue, newValue) -> {
this.convertSpeedUnit(oldValue, newValue);
});
// this.maxValueProperty().bind(Bindings.add(10, this.minValueProperty())); test to bind property min to property max
}
// ******************** Utility Methods ***********************************
public void convertSpeedUnit(SpeedUnitType oldValue, SpeedUnitType newValue)
{
if (oldValue == null)
return;
if (oldValue == newValue){}
else{
switch (oldValue){
case KILO_METERS_PER_HOUR:
System.out.println("convertSpeedUnit::formerUnit - KILO_METERS_PER_HOUR");
switch (newValue){
case METERS_PER_SECOND:
System.out.println("convertSpeedUnit::currentUnit - METERS_PER_SECOND");
setMinValue(10);
setMaxValue(20);
break;
case DATA_MILES_PER_HOUR:
System.out.println("convertSpeedUnit::currentUnit - DATA_MILES_PER_HOUR");
setMinValue(11);
setMaxValue(21);
break;
}
break;
case METERS_PER_SECOND:
System.out.println("convertSpeedUnit::formerUnit - METERS_PER_SECOND");
switch (newValue){
case KILO_METERS_PER_HOUR:
System.out.println("convertSpeedUnit::currentUnit - KILO_METERS_PER_HOUR");
setMinValue(12);
setMaxValue(22);
break;
case DATA_MILES_PER_HOUR:
System.out.println("convertSpeedUnit::currentUnit - DATA_MILES_PER_HOUR");
setMinValue(13);
setMaxValue(23);
break;
}
break;
case DATA_MILES_PER_HOUR:
System.out.println("convertSpeedUnit::formerUnit - DATA_MILES_PER_HOUR");
switch (newValue){
case KILO_METERS_PER_HOUR:
System.out.println("convertSpeedUnit::currentUnit - KILO_METERS_PER_HOUR");
setMinValue(34);
setMaxValue(45);
break;
case METERS_PER_SECOND:
System.out.println("convertSpeedUnit::currentUnit - METERS_PER_SECOND");
setMinValue(56);
setMaxValue(67);
break;
}
break;
}
}
}

Android implement CursorLoader to SQLite database loader

I want to have two ListView in one Activity. I am trying to use Fragments. Data will loaded to ListViews from Sqlite database. I implement AsyncTaskLoader for working with SQllite used source code of cursorloader, but method doInBackground() issue mistake. This is my code:
public class DatabaseLoader extends AsyncTaskLoader<Cursor> {
final ForceLoadContentObserver mObserver;
SQLiteDatabase mDb;
String mTable;
String[] mColumns;
String mSelection;
String[] mSelectionArgs;
String mSortOrder;
Cursor mCursor;
/* Runs on a worker thread */
#Override
public Cursor loadInBackground() {
Cursor cursor = mDb.query(mTable, mColumns, mSelection,
mSelectionArgs, null, null, mSortOrder, null);
if (cursor != null) {
cursor.getCount();
registerContentObserver(cursor, mObserver);
}
return cursor;
}
void registerContentObserver(Cursor cursor, ContentObserver observer) {
cursor.registerContentObserver(mObserver);
}
/* Runs on the UI thread */
#Override
public void deliverResult(Cursor cursor) {
if (isReset()) {
// An async query came in while the loader is stopped
if (cursor != null) {
cursor.close();
}
return;
}
Cursor oldCursor = mCursor;
mCursor = cursor;
if (isStarted()) {
super.deliverResult(cursor);
}
if (oldCursor != null && oldCursor != cursor && !oldCursor.isClosed()) {
oldCursor.close();
}
}
public DatabaseLoader(Context context) {
super(context);
mObserver = new ForceLoadContentObserver();
}
public DatabaseLoader(Context context, String table, String[] columns, String selection,
String[] selectionArgs, String sortOrder) {
super(context);
mObserver = new ForceLoadContentObserver();
mTable = table;
mColumns = columns;
mSelection = selection;
mSelectionArgs = selectionArgs;
mSortOrder = sortOrder;
}
#Override
protected void onStartLoading() {
if (mCursor != null) {
deliverResult(mCursor);
}
if (takeContentChanged() || mCursor == null) {
forceLoad();
}
}
/**
* Must be called from the UI thread
*/
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
#Override
public void onCanceled(Cursor cursor) {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
if (mCursor != null && !mCursor.isClosed()) {
mCursor.close();
}
mCursor = null;
}
public String getTable() {
return mTable;
}
public void setTable(String table) {
mTable = table;
}
public String[] getColumns() {
return mColumns;
}
public void setColumns(String[] columns) {
mColumns = columns;
}
public String getSelection() {
return mSelection;
}
public void setSelection(String selection) {
mSelection = selection;
}
public String[] getSelectionArgs() {
return mSelectionArgs;
}
public void setSelectionArgs(String[] selectionArgs) {
mSelectionArgs = selectionArgs;
}
public String getSortOrder() {
return mSortOrder;
}
public void setSortOrder(String sortOrder) {
mSortOrder = sortOrder;
}
#Override
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
// writer.print(prefix); writer.print("mUri="); writer.println(mUri);
writer.print(prefix); writer.print("mTable="); writer.println(mTable);
writer.print(prefix); writer.print("mColumns="); writer.println(Arrays.toString(mColumns));
writer.print(prefix); writer.print("mSelection="); writer.println(mSelection);
writer.print(prefix); writer.print("mSelectionArgs="); writer.println(Arrays.toString(mSelectionArgs));
writer.print(prefix); writer.print("mSortOrder="); writer.println(mSortOrder);
writer.print(prefix); writer.print("mCursor="); writer.println(mCursor);
// writer.print(prefix); writer.print("mContentChanged=");
writer.println(mContentChanged);
}
}
Can help me somebody. Why method doInBackground() don't work?
You have to open the Database mDb before performing query on it.

Resources