JavaFX TextInputDialog for Password (Masking) - javafx

I didn't found a simple solution for my problem. I want to use a TextInputDialog where you have to type your user password, to reset all data in the database. The problem of the TextInputDialog is that it isn't masking the text and I don't know any option to do this.
My code:
public void buttonReset() {
TextInputDialog dialog = new TextInputDialog("Test");
dialog.setTitle("Alle Daten löschen");
dialog.setHeaderText("Sind Sie sich ganz sicher? Damit werden alle im Programm vorhandenen Daten gelöscht.");
dialog.setContentText("Bitte geben Sie zur Bestätigung ihr Passwort ein:");
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/icons8-blockchain-technology-64.png"));
Optional<String> result = dialog.showAndWait();
if (result.isPresent()){
try {
if (connector.checkUserPassword(userName, result.get())) {
System.out.println("Your name: " + result.get());
} else {
exc.alertWrongPassword();
buttonReset();
}
} catch (TimeoutException te) {
te.printStackTrace();
exc.alertServerNotReached();
}
}
So is there any possibility of a dialog or something to mask the TextInput?

Though there can be other ways to solve this, I would recommend to implement custom Dialog for your requirement. This way you can have more control over the things.
public void buttonReset() {
Dialog<String> dialog = new Dialog<>();
dialog.setTitle("Alle Daten löschen");
dialog.setHeaderText("Sind Sie sich ganz sicher? Damit werden alle im Programm vorhandenen Daten gelöscht.");
dialog.setGraphic(new Circle(15, Color.RED)); // Custom graphic
dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
PasswordField pwd = new PasswordField();
HBox content = new HBox();
content.setAlignment(Pos.CENTER_LEFT);
content.setSpacing(10);
content.getChildren().addAll(new Label("Bitte geben Sie zur Bestätigung ihr Passwort ein:"), pwd);
dialog.getDialogPane().setContent(content);
dialog.setResultConverter(dialogButton -> {
if (dialogButton == ButtonType.OK) {
return pwd.getText();
}
return null;
});
Optional<String> result = dialog.showAndWait();
if (result.isPresent()) {
System.out.println(result.get());
}
}

Related

Background location service stops working after a few minutes [closed]

Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 2 days ago.
Improve this question
Estoy realizando una app en xamarin forms y xamarin.android para el tracking de una servicio, ya tengo creado mi servicio y la peticion de la ubicacion, el problema radica en que el dispositivo deja de obtener la ubicacion luego de un tiempo cuando se encuentra suspendido o en segundo plano, esto me pasa solo en mi dispositivo fisico ya que con el emulador no se me presenta este error
Service
[Service]
public class AndroidLocationService : Service
{
CancellationTokenSource _cts;
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10001;
public static string NAME = "com.swfactorygroup.bongoadm.WakefulIntentService";
private static volatile PowerManager.WakeLock lockStatic = null;
[MethodImpl(MethodImplOptions.Synchronized)]
private static PowerManager.WakeLock GetLock(Context context)
{
if (lockStatic == null)
{
PowerManager manager = (PowerManager)context.GetSystemService(Context.PowerService);
lockStatic = manager.NewWakeLock(WakeLockFlags.Partial, NAME);
lockStatic.SetReferenceCounted(false);
}
return (lockStatic);
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
_cts = new CancellationTokenSource();
Notification notification = new NotificationHelper().GetServiceStartedNotification();
StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
PowerManager.WakeLock wakeLock = GetLock(this.ApplicationContext);
wakeLock.Acquire();
Task.Run(() => {
try
{
var locShared = new GetLocationService();
locShared.Run(_cts.Token).Wait();
}
catch (Android.OS.OperationCanceledException)
{
}
finally
{
if (_cts.IsCancellationRequested)
{
var message = new StopServiceMessage();
Device.BeginInvokeOnMainThread(
() => MessagingCenter.Send(message, "ServiceStopped")
);
}
PowerManager.WakeLock wakeLock = GetLock(this.ApplicationContext);
if (wakeLock.IsHeld)
{
try
{
wakeLock.Release();
}
catch (Exception ex)
{
Log.Error(Class.SimpleName, "Exception when releasing wakelock", ex);
//Log exception when releasing wakelock
}
}
}
}, _cts.Token);
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
if (_cts != null)
{
_cts.Token.ThrowIfCancellationRequested();
_cts.Cancel();
}
base.OnDestroy();
}
}
public class GetLocationService
{
readonly bool stopping = false;
SQLiteHelper _bd = App.BDSQLite;
public GetLocationService()
{
}
public async Task Run(CancellationToken token)
{
await Task.Run(async () => {
while (!stopping)
{
token.ThrowIfCancellationRequested();
try
{
await Task.Delay(10000);
var request = new GeolocationRequest(GeolocationAccuracy.Best);
var location = await Geolocation.GetLocationAsync(request);
if (location != null)
{
var message = new LocationMessage
{
Latitude = location.Latitude,
Longitude = location.Longitude
};
Device.BeginInvokeOnMainThread(() =>
{
MessagingCenter.Send(message, "Location");
});
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
var errormessage = new LocationErrorMessage();
MessagingCenter.Send(errormessage, "LocationError");
});
}
}
return;
}, token);
}
}
I tried using a PowerManager.WakeLock, but it is not poorly implemented, it seems that the device will kill the process after a few minutes

Where to put and how to read txt file

I am passing an app to CSS and I have not been able to read a flat file that I am using.
In the figure I show where I had it at the beginning and the folder where I placed it in the "maven" version.
What is the correct way and if it is necessary to change the CSS?
My Method:
public ListModel tomarDatosLocalizacion() {
Vector aL = new Vector();
try {
aL = leeArchivo("/localidades.txt");
} catch (IOException ex) {
Dialog.show(idioma.getError(), ex.getMessage(), idioma.getContinuar(), null);
}
ListModel localidad = new DefaultListModel(aL);
return localidad;
}
// Rutina que lee el archivo de subzonas en Texto y carga tabla de datos
private Vector leeArchivo(String nombreArchivo) throws IOException {
InputStream lectura = Display.getInstance().getResourceAsStream(getClass(), nombreArchivo);
String registro = null;
Vector datos = new Vector();
// Lee una un registro desde del archivo. null representa el EOF.
while ((registro = leeRegistro(lectura)) != null) {
Vector tmp = dividirCadena(registro, ",");
datos.addElement(new Localidades(Integer.parseInt(tmp.elementAt(0).toString()), tmp.elementAt(1).toString(), tmp.elementAt(2).toString()));
}
lectura.close();
return datos;
}
Open the Common project. Under the source hierarchy you can create a resources directory which is a special case in Maven. In it you can place arbitrary files and they will behave in the way you expect.

How do i add record from data table

I would add record to my table with a form to fill out, but there is a error from ListerPF()
"Object reference not set to an instance of an object"
Here is the whole process:
await App.methode.AddNewPF(Label_NumeroNF.Text, DatePicker_Date.Date, Editor_LibelleNF.Text, Picker_TypeFrais.SelectedItem.ToString(), double.Parse(Entry_Quantite.Text), double.Parse(Entry_Tarif.Text), double.Parse(Entry_Montant.Text), double.Parse(Entry_MontantTotal.Text), CheckBox_CCEntreprise.IsChecked, int.Parse(Entry_Imputation.Text));
Navigation.PushAsync(new PostesNF());
And the code behind "AddNewPF" is:
public async Task AddNewPF(string numero , DateTime date, string libelle, string typeFrais, double quantite, double tarif, double montant, double montantTotal, bool carteCredit, int imputationCC)
{
int result = 0;
try
{
result = await connection.InsertAsync(new DB_PosteNF { Numero = numero, Date = date, Libelle = libelle, TypeFrais = typeFrais, Quantite = quantite, Tarif = tarif, Montant = montant, MontantTotal = montantTotal, CarteCredit = carteCredit, ImputationCC = imputationCC});
StatutMessage = $"{result} poste de frais ajouté : {numero} | {typeFrais} ";
}
catch (Exception ex)
{
StatutMessage = $"Impossible d'ajouter le poste de frais avec le numéro: {numero}. \nErreur : {ex.Message}";
}
}
When the "PosteNF" page appears, I have this code
protected override async void OnAppearing()
{
base.OnAppearing();
CollectionViewPF.ItemsSource = await App.methode.ListerPF();
}
the problematic code "ListerPF" is:
public async Task<List<DB_PosteNF>> ListerPF(DB_ListeNF datareceived)
{
try
{
string numero = datareceived.Numero;
//return await connection.Table<DB_PosteNF>().ToListAsync();
return await connection.Table<DB_PosteNF>().Where(x => x.Numero == numero).ToListAsync();
}
catch (Exception ex)
{
StatutMessage = $"Impossible d'afficher la liste des postes de frais. \nErreur : {ex.Message}";
}
return new List<DB_PosteNF>();
}
But when I go back to the "PostesNF" page, the registered data is not displayed. Thanks for your help !
Per your code snippets, the model is DB_PosteNF with 10 properties.The key is that when you retrieve the records from the data table, I think you need a ObservableCollection<DB_PosteNF> to receive these entities that read from the database.Below is the code snippets for your reference:
First, define a UserCollection using ObservableCollection
public ObservableCollection<User> UserCollection { get; set; }
Then, in OnAppearing method:
protected override async void OnAppearing()
{
base.OnAppearing();
UserDB db = await UserDB.Instance;
List<User> a = await db.GetUserAsync();
UserCollection = new ObservableCollection<User>(a);
userinfodata.ItemsSource = UserCollection;
}
PS: In my case, the mode is User.

Request camera permissions xamarin forms

I have an app that needs permissions for the camera, this is well implemented, but asks for permission on the home screen (splash). What I would like is to appear after logging in or on a specific page (Is this possible?). And as I could implement the same for IOS, I thank you very much for your help and have a great day.
Thanks for you help.
Here my code
MainActivity.cs
const int requestCameraId = 0;
const int requestStorageId = 1;
const int requestId = 2;
readonly string[] permissions =
{
Android.Manifest.Permission.Camera,
Android.Manifest.Permission.ReadExternalStorage,
Android.Manifest.Permission.WriteExternalStorage,
Android.Manifest.Permission.Internet,
Android.Manifest.Permission.ForegroundService,
Android.Manifest.Permission.RequestCompanionUseDataInBackground,
Android.Manifest.Permission.RequestCompanionRunInBackground,
Android.Manifest.Permission.StatusBar,
Android.Manifest.Permission.Vibrate,
Android.Manifest.Permission.Flashlight
};
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
switch (requestCode)
{
case requestCameraId:
{
if (grantResults[0] == (int)Android.Content.PM.Permission.Granted)
{
Toast.MakeText(this, "Permiso concedido para la camara", ToastLength.Short).Show();
}
else
{
//Permission Denied :(
Toast.MakeText(this, "Permiso denegado para la camara", ToastLength.Short).Show();
}
}
break;
case requestStorageId:
{
if (grantResults[0] == (int)Android.Content.PM.Permission.Granted)
{
Toast.MakeText(this, "Permiso concedido para el almacenamiento", ToastLength.Short).Show();
}
else
{
//Permission Denied :(
Toast.MakeText(this, "Permiso denegado para el almacenamiento", ToastLength.Short).Show();
}
}
break;
}
}
async Task GetCameraPermissionAsync()
{
const string permission = Manifest.Permission.Camera;
if (CheckSelfPermission(permission) == (int)Android.Content.PM.Permission.Granted)
{
//TODO change the message to show the permissions name
Toast.MakeText(this, "Permisos para la camara listos", ToastLength.Short).Show();
return;
}
if (ShouldShowRequestPermissionRationale(permission))
{
//set alert for executing the task
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Permisos necesarios");
alert.SetMessage("La aplicación necesita acceder a la camara para tomar una fotografía del trabajo terminado");
alert.SetPositiveButton("Conceder permiso", (senderAlert, args) =>
{
RequestPermissions(permissions, requestCameraId);
});
alert.SetNegativeButton("Cancelar", (senderAlert, args) =>
{
Toast.MakeText(this, "Cancelado", ToastLength.Short).Show();
});
Dialog dialog = alert.Create();
dialog.Show();
return;
}
}
async Task GetStoragePermissionAsync()
{
const string permission = Manifest.Permission.ReadExternalStorage;
if (CheckSelfPermission(permission) == (int)Android.Content.PM.Permission.Granted)
{
//TODO change the message to show the permissions name
Toast.MakeText(this, "Permisos para leer carpetas listos", ToastLength.Short).Show();
return;
}
if (ShouldShowRequestPermissionRationale(permission))
{
//set alert for executing the task
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Permisos necesarios");
alert.SetMessage("La aplicación necesita acceder a sus archivos para subir una imagen con el trabajo terminado");
alert.SetPositiveButton("Conceder permiso", (senderAlert, args) =>
{
RequestPermissions(permissions, requestStorageId);
});
alert.SetNegativeButton("Cancelar", (senderAlert, args) =>
{
Toast.MakeText(this, "Cancelado", ToastLength.Short).Show();
});
Dialog dialog = alert.Create();
dialog.Show();
return;
}
}
async Task GetPermissionsAsync()
{
await GetCameraPermissionAsync();
await GetStoragePermissionAsync();
RequestPermissions(permissions, requestId);
}
async Task TryToGetPermissions()
{
if ((int)Build.VERSION.SdkInt >= 23)
{
await GetPermissionsAsync();
return;
}
}
protected async override void OnCreate(Bundle savedInstanceState)
{
await TryToGetPermissions();
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// RequestPermissions(permissions, requestId);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
Xamarin.Forms.Application.Current.On<Xamarin.Forms.PlatformConfiguration.Android>().UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);
CreateNotificationFromIntent(Intent);
//notificationServiceIntent = new Intent(this.BaseContext, typeof(PDANotificationService));
//StartService(notificationServiceIntent);
WireUpLongRunningTask();
var message = new StartLongRunningTaskMessage();
MessagingCenter.Send(message, "StartLongRunningTaskMessage");
}
As #Jason said, your code requests permission on main Activity create, so as soon as you open your app, it will ask for all the permissions you listed. You need to request permission separately.
Say camera permission:
if (CheckSelfPermission(Manifest.Permission.Camera) != (int)Permission.Granted)
{
//request permission
}else
{
//call camera
}
And OnRequestPermissionsResult will be called after user granted/denied the permission request, you can check the result and call camera if the permission was granted.
Please refer to this for detail workflow about permission.

android mapsforge overlay doesn't show in view

I need a little help. I wrote an android app using "org.mapsforge.android.maps".
There I create a custom overlay wich I wanna show in the map. The map is shown but without my Overlay. I see that "mapView.getOverlays().add(myOverlay)" adds myOverlay to mapView but on the screen nothing happens.
Does someone has an idea why not?
Thanks a lot
Tom
#Override
public void onCreate(Bundle savedInstanceState) {
try
{
res= this.getResources();
context=this;
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.openstreet);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.main_title_back);
// get the pointers to different system services
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
this.myLocationListener = new MyLocationListener(this);
if(getIntent().hasExtra("comingfrom") == true)
comingfrom = getIntent().getExtras().getString("comingfrom");
if(getIntent().hasExtra("latitude") == true)
mlatitude = getIntent().getExtras().getDouble("latitude");
if(getIntent().hasExtra("longitude") == true)
mlongitude = getIntent().getExtras().getDouble("longitude");
initMapView();
Log.i(Properties.getProgramname(), "OpenStreetActivity->onCreate: Übergebene Koordinate Lat=" + mlatitude + " Lon=" + mlongitude);
if (comingfrom.equals("ButtonArea"))
{
LoadData();
}
else
{
}
if (this.locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
initMyLocation(true);
} else {
Toast.makeText(this,"GPS Provider not enabled",Toast.LENGTH_LONG).show();
}
// create a GeoPoint with the latitude and longitude coordinates
GeoPoint geoPoint = new GeoPoint(mlatitude, mlongitude);
mapController.setCenter(geoPoint);
mapController.setZoom(16);
}
catch (Exception ex)
{
Log.e(Properties.getProgramname(), "Fehler in OpenStreetActivity->onCreate: " + ex.getLocalizedMessage());
Toast.makeText(this,"UI problem " + ex.getMessage(),Toast.LENGTH_LONG).show();
}
}
/**
* Initialize the OSM
*
*/
private void initMapView()
{
settingsLayer = new TJHookerSettingsLayer(this);
Cursor cur = settingsLayer.ladeSettings();
String filename =cur.getString(cur.getColumnIndex(TJHookerSettingsTables.MAPFILE));
cur.close();
mapView = (MapView) this.findViewById(R.id.openmapview);
this.mapView.setClickable(true);
this.mapView.setBuiltInZoomControls(true);
this.mapView.setFocusable(true);
if (!this.mapView.getMapGenerator().requiresInternetConnection() ) {
File file = new File(filename);
if (file.exists())
mapView.setMapFile(new File(filename));
else
Toast.makeText(this,"Problem: Mapfile not found. Please correct the path of your mapfile",Toast.LENGTH_LONG).show();
}
mapController = this.mapView.getController();
}
/**
* Show the current location of my position
*
*/
private void initMyLocation(boolean centerAtFirstFix)
{
try
{
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestProvider = this.locationManager.getBestProvider(criteria, true);
this.itemizedMyLocationOverlay = new ArrayItemizedOverlay(null);
this.overlayMyLocationItem = new OverlayItem();
this.overlayMyLocationItem.setMarker(ItemizedOverlay.boundCenter(getResources().getDrawable(R.drawable.my_location)));
this.itemizedMyLocationOverlay.addItem(this.overlayMyLocationItem);
this.mapView.getOverlays().add(this.itemizedMyLocationOverlay);
this.myLocationListener.setCenterAtFirstFix(centerAtFirstFix);
this.locationManager.requestLocationUpdates(bestProvider, 1000, 0, this.myLocationListener);
}
catch(Exception ex)
{
Log.e(Properties.getProgramname(), "Fehler in OpenStreetActivity->initMyLocation: " + ex.getLocalizedMessage());
Toast.makeText(OpenStreetActivity.this, "!initMyLocation: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
// neuen Thread starten
private void LoadData()
{
if(mlongitude > 0 && mlatitude > 0)
{
SystemInformation sys = new SystemInformation();
if(sys.isNetworkAvailable(this))
{
// Neuen Thread startenn der die Kontakte laden soll. Activity wir schon angezeigt
prog = ProgressDialog.show(this, res.getString(R.string.gc40_progtitle), "", true, false);
prog.setMessage(Html.fromHtml("<font color='white'>" + res.getString(R.string.gc40_progtext) + "</font>"));
pdIsShow=true;
Thread thread = new Thread(this);
thread.start();
}
}
}
#Override
public void run() {
GCApiRequests _apiRequests= new GCApiRequests();
try {
lc = _apiRequests.GetCacheByArea(Properties.getGCAccessToken(), mlongitude, mlatitude,"5000", GeocachingConstants.maxCachesPerPage);
handler.sendEmptyMessage(0);
} catch (Exception e) {
Log.e(Properties.getProgramname(), "KartenAnzeigenActivity->Fehler in run: " + e.getLocalizedMessage());
handler.sendEmptyMessage(1);
}
}
// Wenn Thread alle Kontakte geladen hat, dann in ListView anzeigen
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (pdIsShow)
prog.dismiss();
setOverlayCaches();
}
};
private void setOverlayCaches()
{
try {
CacheType typ = new CacheType();
lc.trimToSize();
Log.i(Properties.getProgramname(), "OpenStreetActivity->setOverlayCache: Anzahlgefundener Caches=" +lc.size());
/** So, jetzt gehen wir erstmal durch alle Logs von geocaching.com durch */
// create an ItemizedOverlay with the default marker
CacheOpenStreetMapItemizedOverlay myOverlay= new CacheOpenStreetMapItemizedOverlay(getResources().getDrawable(typ.getCacheType(2)), context);
for(Geocache cache: lc)
{
// create a GeoPoint with the latitude and longitude coordinates
int lat = (int) (Double.parseDouble(cache.GetLatitude()) * 1e6);
int lon = (int) (Double.parseDouble(cache.GetLongitude()) * 1e6);
GeoPoint geoPoint = new GeoPoint(lat,lon);
// create an OverlayItem with title and description
OverlayItem item = new OverlayItem(geoPoint, cache.GetCacheName(), cache.GetGCCode(),
getResources().getDrawable(typ.getCacheType(Integer.parseInt(cache.GetCacheType()))));
myOverlay.addOverlay(item);
}
myOverlay.requestRedraw();
// add the ArrayItemizedOverlay to the MapView
//if (traditionellOverlay != null)
Log.i(Properties.getProgramname(), "OpenStreetActivity->setOverlayCache: Anzahl Overlay items=" + myOverlay.size());
Log.i(Properties.getProgramname(), "OpenStreetActivity->setOverlayCache: Anzahl MapView Overlays=" + mapView.getOverlays().size());
mapView.getOverlays().add(myOverlay);
Log.i(Properties.getProgramname(), "OpenStreetActivity->setOverlayCache: Anzahl MapView Overlays=" + mapView.getOverlays().size());
} catch (Exception e) {
Log.e(Properties.getProgramname(), "KartenAnzeigenActivity->Fehler in setOverlayCaches: " + e.getLocalizedMessage());
}
}
/** Back-Button in Titlebar wurde gedrückt */
public void PressTitleBackButton_Click(View view)
{
/** Durch ein finish() wird der Back-Button Effekt ausgelöst. */
finish();
}
Solved!
You have to rewrite the code to:
int cachetyp = typ.getCacheType(Integer.parseInt(cache.GetCacheType()));
Drawable itemMarker = getResources().getDrawable(cachetyp);
// Without that the icons aren't displayed. So you NEED it
itemMarker.setBounds(0, 0, itemMarker.getIntrinsicWidth(), itemMarker.getIntrinsicHeight());
The item need the bounds.....

Resources