I'm using JavaFX for my application's GUI.
public void testUsername(KeyEvent ke) throws SQLException{
if (ke.getCode().equals(KeyCode.ENTER))
{
if(checkUsernameInDataBase(txtUsername.getText())==false)
{
Image image = new Image(getClass().getResourceAsStream("Z6if3PZ.png"));
lblImage.setGraphic(new ImageView(image));
}
}
}
public boolean checkUsernameInDataBase(String username) throws SQLException {
// verific daca username introdus este sau nu in baza de date
// daca este deja returnez true altfel returnez false
// daca e true nu se poate face signUp daca e false se poate
String usrCheckStr = String.format("select * from utilizatori where username = '" + username + "'");
ResultSet results = DBMain.getStatement().executeQuery(usrCheckStr);
if (!results.isBeforeFirst()) {
// results.isBeforeFirst verifica daca curosorul se afla inainte de
// primul rezultat
// si intoarce true daca este acolo sau false daca nu este
// daca intoarce false inseamna ca nu exista inregistrari
// deci username nu exista in baza de date
return false;
} else
return true;
}
Could someone tell me why i receive NullPointerException when i am using checkUserNameInDataBase method? This method looks in a DataBase if current Username exits. Ideea is that when i am using it in a main method, it works, but when i am trying to use it in the testUsername method, i receive error.
Thx!
Related
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
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.
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.
I did a method which add a user in storage. Below is the code and the error that I'm getting.
public string addusr(string nome, string cidade, string cpf, string email, string telefone)
{
try
{
if (nome.Length == 0)
return "f:Preencha o campo nome.";
if (cidade.Length == 0)
return "f:Preencha o campo cidade.";
if (cpf.Length == 0)
return "f:Preencha o campo cpf.";
if (!Valida(cpf))
return "f:CPF Invalido.";
if (email.Length == 0)
return "f:Preencha o campo email.";
Regex rg = new Regex(#"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$");
if (!rg.IsMatch(email))
{
return "f:Email Invalido";
}
List<UserEntity> lst = new List<UserEntity>();
var _account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Conn"));
var _context = new CRUDUserEntities(_account.TableEndpoint.ToString(), _account.Credentials);
if (_context.Select(cpf).Count() > 0)
return "dup";
var account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Conn"));
var context = new CRUDUserEntities(account.TableEndpoint.ToString(), account.Credentials);
UserClientEntity entity = new UserClientEntity() { nome = nome, cidade = cidade, cpf = cpf, email = email, telefone = telefone };
context.ADDUSociate(entity);
return "k";
}
catch (Exception exc)
{
string error = "f:" + exc.Message + "|" + exc.StackTrace;
// Trace.WriteLine("Erro no login: " + error , "Information");
return error;
}
}
When I try to add a user...I'm getting this error:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
f:An error occurred while processing this request.| at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.get_Result()
at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.ExecuteAndWait()
at Microsoft.WindowsAzure.StorageClient.CommonUtils. <LazyEnumerateSegmented>d__0`1.MoveNext()
at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)
at mobile.Service1.addusr(String nome, String cidade, String cpf, String email, String telefone)
</string>
I don't know what is wrong..
Not sure whats causing the error but you do miss a context.SaveChanges(); after
context.ADDUSociate(entity);
"I suggest you start with getting the emulator working for azure storage and debug this in visual studio."
I think you dont have the correct Azure sdk installed. Try to reinstall it and the emulator should work. You can follow this guide: http://www.windowsazure.com/en-us/develop/net/how-to-guides/blob-storage/
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.....