One Event Handler for many Actions - events

Im struggling to understand how to reduce my code so that 5 TextField inputs are all directed to one Event Handler class. It all works, there is just so much repetition. Any advice is appreciated.
Heres the code:
TextField studentIdTf = new TextField("Student ID");
studentIdTf.setTooltip(new Tooltip("Enter unique Student ID"));
studentIdTf.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
int studentIdTfInt = Integer.parseInt(studentIdTf.getText());
System.out.println(studentIdTfInt);
}
catch(NumberFormatException ex) {
System.out.println("Please enter a number");
}
}
});
TextField quizTf = new TextField("Quiz");
quizTf.setTooltip(new Tooltip("Enter Quiz score"));
quizTf.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
int quizTfInt = Integer.parseInt(quizTf.getText());
System.out.println(quizTfInt);
}
catch(NumberFormatException ex) {
System.out.println("Please enter a number");
}
}
});
TextField asg1Tf = new TextField("Assignment 1");
asg1Tf.setTooltip(new Tooltip("Enter Assignment 1 score"));
asg1Tf.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
int asg1TfInt = Integer.parseInt(asg1Tf.getText());
System.out.println(asg1TfInt);
if (asg1TfInt < 0) {
throw new InputMismatchException();
}
if (asg1TfInt > 100) {
throw new InputMismatchException();
}
}
catch(NumberFormatException ex) {
System.out.println("Please enter a number");
}
catch(InputMismatchException ex2) {
System.out.println("Enter a number within the range 0 - 100");
}
}
});
TextField asg2Tf = new TextField("Assignment 2");
asg2Tf.setTooltip(new Tooltip("Enter Assignment 2 score"));
asg2Tf.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
int asg2TfInt = Integer.parseInt(asg2Tf.getText());
System.out.println(asg2TfInt);
if (asg2TfInt < 0) {
throw new InputMismatchException();
}
if (asg2TfInt > 100) {
throw new InputMismatchException();
}
}
catch(NumberFormatException ex) {
System.out.println("Please enter a number");
}
catch(InputMismatchException ex2) {
System.out.println("Enter a number within the range 0 - 100");
}
}
});
TextField examTf = new TextField("Final Exam");
examTf.setTooltip(new Tooltip("Enter Exam score"));
examTf.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
int examTfInt = Integer.parseInt(examTf.getText());
System.out.println(examTfInt);
if (examTfInt < 0) {
throw new InputMismatchException();
}
if (examTfInt > 100) {
throw new InputMismatchException();
}
}
catch(NumberFormatException ex) {
System.out.println("Please enter a number");
}
catch(InputMismatchException ex2) {
System.out.println("Enter a number within the range 0 - 100");
}
}
});

Why not just define a method:
private TextField createTextField(String text, String tooltip) {
TextField textField = new TextField(text);
textField.setTooltip(new Tooltip(tooltip));
textField.setOnAction(event -> {
try {
int value = Integer.parseInt(textField.getText());
System.out.println(value);
} catch (NumberFormatException exc) {
System.out.println("Please enter a number");
}
});
return textField ;
}
and then you can just do
TextField studentIdTf = createTextField("Student ID", "Enter Unique Student ID");
TextField quizTf = createTextField("Quiz", "Enter Quiz Score");
// etc etc

Related

How to make focus event / effect for every IOS element?

I have made the following focus effect for Xamarin.Forms.Android so when the keyboard is focused on the element it shows blue rectangle around it.:
protected override void OnAttached()
{
try
{
OriginalBackground = Container.Background;
if(Control != null)
{
Control.FocusChange += Control_FocusChange;
}
else
{
Container.FocusChange += Control_FocusChange;
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
}
private void Control_FocusChange(object sender, FocusChangeEventArgs e)
{
if(Control != null)
{
if (Control.HasFocus)
{
Control.SetBackgroundColor(Android.Graphics.Color.Transparent);
Control.SetBackgroundResource(Resource.Drawable.focusFrame);
}
else
{
Control.SetBackground(OriginalBackground);
}
}
else
{
if (Container.HasFocus)
{
Container.SetBackgroundColor(Android.Graphics.Color.Red);
Container.SetBackgroundResource(Resource.Drawable.focusFrame);
}
else
{
Container.SetBackground(OriginalBackground);
}
}
}
Can someone tell me how to the same effect for Xamarin.Forms.IOS ? I tried the following code but it doesn't work on focusing the app the same way as Android. Somehow there isn't an event or perhaps I am missing it for IOS:
UIColor backgroundColor;
UIView view;
public Func<Brush, CALayer> OriginalBackground { get; private set; }
protected override void OnAttached()
{
try
{
OriginalBackground = Container.GetBackgroundLayer;
if (Container != null)
{
this.Container.DidUpdateFocus()
CreateRectange();
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
private void CreateRectange()
{
view = new UIView();
view.BackgroundColor = UIColor.Clear;
view.Frame = new CGRect(30, 100, 36, 36);
var maskLayer = new CAShapeLayer();
UIBezierPath bezierPath = UIBezierPath.FromRoundedRect(view.Bounds, (UIRectCorner.TopLeft | UIRectCorner.BottomLeft), new CGSize(18.0, 18.0));
maskLayer.Path = bezierPath.CGPath;
maskLayer.Frame = view.Bounds;
maskLayer.StrokeColor = UIColor.Black.CGColor; //set the borderColor
maskLayer.FillColor = UIColor.Red.CGColor; //set the background color
maskLayer.LineWidth = 1; //set the border width
view.Layer.AddSublayer(maskLayer);
Container.AddSubview(view);
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
try
{
if (args.PropertyName == "IsFocused")
{
Control.AddSubview(view);
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
At first, the frame's size should fit the control. And then you need to set the maskLayer.FillColor as UIColor.Clear.CGColor to make the control's content will show correctly.
You can try the following code:
UIView view;
float width,height;
public Func<Brush, CALayer> OriginalBackground { get; private set; }
protected override void OnAttached()
{
}
private void CreateRectange()
{
height = (float)Control.Frame.Height;
width = (float)Control.Frame.Width;
view = new UIView();
view.BackgroundColor = UIColor.Clear;
view.Frame = new CGRect(0,0,width,height);
var maskLayer = new CAShapeLayer();
UIBezierPath bezierPath = UIBezierPath.FromRoundedRect(view.Bounds, (UIRectCorner.TopLeft | UIRectCorner.BottomLeft), new CGSize(0,0));
maskLayer.Path = bezierPath.CGPath;
maskLayer.Frame = view.Bounds;
maskLayer.StrokeColor = UIColor.Red.CGColor; //set the borderColor
maskLayer.FillColor = UIColor.Clear.CGColor; //set the background color
maskLayer.LineWidth = 1; //set the border width
view.Layer.AddSublayer(maskLayer);
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
try
{
if (args.PropertyName == "IsFocused")
{
CreateRectange();
Control.AddSubview(view);
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}

Insert Image into PDF Document

Is it possible to add an image to the PDF document? My layout has one (Button) and one (ImageView), I would like that when I click (Button), it will open the Gallery to select the image, show it in (ImageView) and add it to the PDF document, as if it were a generator curriculum, thank you in advance.
*Using com.itextpdf:itextg:5.5.10
here is the complete code of what you wanted. Try this and let me know.
In the onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_to_pdf);
imageView = findViewById(R.id.imageView);
galleryBtn = findViewById(R.id.gallery);
convertBtn = findViewById(R.id.convert);
galleryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "PDF_" + timeStamp + "_";
File storageDir = getAlbumDir();
try {
pdfPath = File.createTempFile(
imageFileName, /* prefix */
".pdf", /* suffix */
storageDir /* directory */
);
} catch (IOException e) {
e.printStackTrace();
}
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(photoPickerIntent, GALLERY_INTENT);
}
});
convertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(ImageToPDF.this, "Please select the image from gallery", Toast.LENGTH_LONG).show();
} else {
convertToPDF(pdfPath);
}
}
});
}
Create a directory for PDF file:
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStorageDirectory()
+ "/dcim/"
+ "Image to pdf");
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
On camera activity intent result:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT) {
if (resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
bitmap = BitmapFactory.decodeFile(imagePath);
imageView.setImageBitmap(bitmap);
cursor.close();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("Canceled", "Image not selected");
}
}
}
Now code to convert image to PDF and save to the directory:
private void convertToPDF(File pdfPath) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
PdfDocument pdfDocument = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(width, height, 1).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0, null);
pdfDocument.finishPage(page);
try {
pdfDocument.writeTo(new FileOutputStream(pdfPath));
Toast.makeText(ImageToPDF.this, "Image is successfully converted to PDF", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
pdfDocument.close();
}

How to show image on imageview using webservices and json

I am using web service for showing image in imageview. But web service image show in SYSTEM.BYTE[] Format. So how to Convert or display the image in imageview in xamarin android application??
Webservice.asmx:
[WebMethod(MessageName = "BindHospName", Description = "Bind Hospital Name Control")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[System.Xml.Serialization.XmlInclude(typeof(GetHospName))]
public string BindHosp(decimal SpecID)
{
JavaScriptSerializer objJss = new JavaScriptSerializer();
List<GetHospName> HospName = new List<GetHospName>();
try
{
ConnectionString();
cmd = new SqlCommand("select b.HID,b.HospName,b.Logo from HospitalRegBasic b inner join HospitalRegClinical c on b.HID=c.HID " +
"where b.EmailActivationCode <> '' and b.EmailActivationStatus = 1 and b.Status = 1 and c.SPEC_ID = #SpecID ", conn);
cmd.Parameters.AddWithValue("#SpecID", SpecID);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
var getHosp = new GetHospName
{
HospID = dr["HID"].ToString(),
HospName = dr["HospName"].ToString(),
HospLogo = dr["Logo"].ToString()
};
HospName.Add(getHosp);
}
}
dr.Close();
cmd.Dispose();
conn.Close();
}
catch (Exception)
{
throw;
}
return objJss.Serialize(HospName);
}
Class.cs:
namespace HSAPP
{
class ContListViewHospNameClass : BaseAdapter<GetHospNames>
{
List<GetHospNames> objList;
Activity objActivity;
public ContListViewHospNameClass (Activity objMyAct, List<GetHospNames> objMyList) : base()
{
this.objActivity = objMyAct;
this.objList = objMyList;
}
public override GetHospNames this[int position]
{
get
{
return objList[position];
}
}
public override int Count
{
get
{
return objList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public static Bitmap bytesToBitmap(byte[] imageBytes)
{
Bitmap bitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
return bitmap;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = objList[position];
if (convertView == null)
{
convertView = objActivity.LayoutInflater.Inflate(Resource.Layout.ContListViewHospName, null);
}
convertView.FindViewById<TextView>(Resource.Id.tvHospID).Text = item.HospID;
convertView.FindViewById<TextView>(Resource.Id.tvHospName).Text = item.HospName;
byte[] img =item.HospLogo;
Bitmap bitmap = BitmapFactory.DecodeByteArray(img, 0, img.Length);
convertView.FindViewById<ImageView>(Resource.Id.imgLogo).SetImageBitmap(bitmap);
return convertView;
}
}
}
This is JSON Code:
private void BindControl_BindHospCompleted(object sender, BindControl.BindHospCompletedEventArgs e)
{
jsonValue = e.Result.ToString();
if (jsonValue == null)
{
Toast.MakeText(this, "No Data For Bind", ToastLength.Long).Show();
return;
}
try
{
JArrayValue = JArray.Parse(jsonValue);
list = new List<GetHospNames>();
int count = 0;
while (count < JArrayValue.Count)
{
GetHospNames getHospName = new GetHospNames(JArrayValue[count]["HospID"].ToString(), JArrayValue[count]["HospName"].ToString(),JArrayValue[count]["Logo"]);
list.Add(getHospName);
count++;
}
listView.Adapter = new ContListViewHospNameClass(this, list);
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
}
}
public static void SetImageFromByteArray (byte[] iArray, UIImageView imageView)
{
if (iArray != null && iArray.Length > 0) {
Bitmap bitmap = BitmapFactory.DecodeByteArray (iArray, 0, iArray.Length);
imageView.SetImageBitmap (bitmap);
}
}
That's it. If this is not working, your byte array may not be a valid image.
public static bool IsValidImage(byte[] bytes)
{
try {
using(MemoryStream ms = new MemoryStream(bytes))
Image.FromStream(ms);
}
catch (ArgumentException) {
return false;
}
return true;
}

MVVMCross ZXing back button

I have got a problem with back button in MVVMCross when using zxing barcode scanner. Unfortunetly, when I press back button, there is an error: Java.Lang.NullPointerException: Attempt to invoke virtual method 'long android.graphics.Paint.getNativeInstance()' on a null object reference
When I comment metohs scan() weverything is ok.
Someone know what's going wrong?
This is my fragment scann view class:
public class ScannView : MvxFragmentActivity, IBarcodeFragmentOptions
{
protected ScannViewModel MainViewModel
{
get { return ViewModel as ScannViewModel; }
}
public static ZXingScannerFragment scanFragment;
protected override void OnResume()
{
base.OnResume();
try
{
if (scanFragment == null)
{
scanFragment = new ZXingScannerFragment();
SupportFragmentManager.BeginTransaction()
.Replace(Resource.Id.frameScanner, scanFragment)
.Commit();
}
scan();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
protected override void OnPause()
{
try
{
scanFragment?.StopScanning();
base.OnPause();
}catch(Exception ex)
{
Console.WriteLine(ex);
}
}
protected override void OnRestart()
{
base.OnRestart();
}
public void ToogleFlashLight(bool on)
{
if (scanFragment != null)
scanFragment.SetTorch(on);
}
public void scan()
{
try
{
// var results = await CrossPermissions.Current.RequestPermissionsAsync(Plugin.Permissions.Abstractions.Permission.Camera);
// var status = results[Plugin.Permissions.Abstractions.Permission.Camera];
// if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
// {
var opts = new MobileBarcodeScanningOptions
{
PossibleFormats = new List<ZXing.BarcodeFormat> {
ZXing.BarcodeFormat.QR_CODE
},
CameraResolutionSelector = availableResolutions => {
foreach (var ar in availableResolutions)
{
Console.WriteLine("Resolution: " + ar.Width + "x" + ar.Height);
}
return null;
}
};
scanFragment?.StartScanning(opts,result =>
{
if (result == null || string.IsNullOrEmpty(result.Text))
{
RunOnUiThread(() => Toast.MakeText(this, "Anulowanie skanowanie", ToastLength.Long).Show());
return;
}
MainViewModel.ScannedCode = result.Text; //ChangePropertyToEmpty();
RunOnUiThread(() => Toast.MakeText(this, "Zeskanowano: " + result.Text, ToastLength.Short).Show());
});
// }
}catch(Exception ex)
{
Debug.WriteLine(ex);
}
}
protected override void OnViewModelSet()
{
MobileBarcodeScanner.Initialize(Application);
base.OnViewModelSet();
SetContentView(Resource.Layout.layout_scann);
}
}
And here in my viewmdoel I have simple method to close current viewmodel:
public void ButtonBackClick()
{
Close(this);
}

java.sql.SQLException: I/O Error: Socket closed

I want to sync data from MSSQL to android sqllite.All syncdata method write in ansync class.But sometime application return java.sql.SQLException: I/O Error: Socket closed error and not finish sync data . Sometime application successfully sync all update data.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
{
CheckProductGroupInfoHasNew();
CheckProductInfoHasNew();
CheckProductPriceInfoHasNew();
CheckCustomerInfoHasNew();
}
private void CheckProductInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PC");
else
_AsyncSyncData.execute("PC");
}
private void CheckProductPriceInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PPRICE");
else
_AsyncSyncData.execute("PPRICE");
}
private void CheckCustomerInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"CV");
else
_AsyncSyncData.execute("CV");
}
private void CheckProductGroupInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PG");
else
_AsyncSyncData.execute("PG");
}
class AsyncSyncData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
if (params[0].toString().equals("PG")) {
_ListProductGroupInfo = _MSDBConnection
.SelectProductGroupInfo(_Query);}
} else if (params[0].equals("PC")) {
_ListProductInfo = _MSDBConnection
.SelectProductInfo(_Query);
} else if (params[0].equals("CV")) {
_ListCustomerInfo = _MSDBConnection
.SelectCustomerInfo(_Query);
} else if (params[0].equals("PPRICE")) {
_ListProductPriceInfo = _MSDBConnection
.SelectProductPriceInfo(_Query);
} else if (params[0].equals("VAT")) {
_ListCustomerInfo = _MSDBConnection
.SelectCustomerInfo(_Query);
}
#Override
protected void onPostExecute(String result) {
try {
if (result.equals("PG")) {
int _result = 0;
if ((_result = SyncProductGroupInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Group Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("PC")) {
int _result = 0;
if ((_result = SyncProductInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("PPRICE")) {
int _result = 0;
if ((_result = SyncProductPriceInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Price Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("CV")) {
int _result = 0;
if ((_result = SyncCustomerInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Customer Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
HomeFragment.BindProductGroup();
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
} else if (result.equals("VAT")) {
if (SyncVatInfo()) {
Toast.makeText(_context, "Save Successfully Vat Data",
Toast.LENGTH_SHORT).show();
}
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
}
} catch (Exception ex) {
Log.i("onPostExecute Ex",
" Chan I'm onPostExecute" + ex.getMessage());
ex.printStackTrace();
Toast.makeText(_context, ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
} finally {
}
}

Resources