Xamarin.forms app crashes on inserting data to SQLite database - xamarin

I am trying to take information entered by the user in the AddPage.Xaml.cs and add it to a SQLite database. The code runs fine until I press the add button then it crashes, I can't really figure out what is going on and I don't really know what I'm doing.
here is the necessary code and their corresponding classes.
This is in the AddPage.xaml.cs:
private async Task AddButton_Clicked(object sender, EventArgs e)
{
App.characterDatabase.SaveCharacter(new Character()
{
Name = NameTxt.Text,
Species = SpeciesTxt.Text,
ImageUrl = ImageUrlTxt.Text
});
}
The CharacterDatabaseController.cs
public class CharacterDatabaseController
{
static object locker = new object();
SQLiteConnection database;
public CharacterDatabaseController()
{
database = DependencyService.Get<IDatabaseConnection>().DbConnection();
database.CreateTable<Character>();
}
public Character GetCharacter()
{
lock (locker)
{
if (database.Table<Character>().Count() == 0)
{
return null;
}
else
{
return database.Table<Character>().First();
}
}
}
public int SaveCharacter(Character character)
{
lock (locker)
{
if (character.Id != 0)
{
database.Update(character);
return character.Id;
}
else
{
return database.Insert(character);
}
}
}
public int DeleteCharacter(int id)
{
lock (locker)
{
return database.Delete<Character>(id);
}
}
}
and the App.cs:
public static CharacterDatabaseController characterDatabase
{
get
{
if (characterDatabase == null)
{
CharacterDatabase = new CharacterDatabaseController();
}
return CharacterDatabase;
}
}

Related

Issue with Xamarin Firebase Subscribe to a Child with no Key - Newtonsoft.Json error

I have a Firebase Child called "Parameters" that stores some data while my program runs. I populate it with "Put" and "Patch" actions. I cannot get the subscribe to work... I'm stuck on this Newtonsoft.Json.JsonSerializationException and I've tried several things but cannot figure it out. You can see in the error, I am getting the payload back... I just cannot parse it into my ViewParameterModel property variables. I would appreciate any help to get this working. Thanks, Brian
$exception {Firebase.Database.FirebaseException: Exception occured while processing the request.
Request Data: Response: {"aug":true,"fan":true,"ign":false,"mode":"Off","target":200}
---> Newtonsoft.Json.JsonSerializationException: Error converting value True to type 'Chart_sample.ViewParameterModel'. Path 'aug', line 1, position 11.
---> System.ArgumentException: Could not cast or convert from System.Boolean to Chart_sample.ViewParameterModel.
FirebaseHelper.cs
...
private readonly string ChildParams = "ControllerData/Pellet_Pirate_1/Parameters";
public ObservableCollection<Parameter> GetParameters()
{
firebase.Child(ChildParams).AsObservable<ViewParameterModel>().Subscribe(snapp =>
{
ViewParameterModel.aug = snapp.Object.aug;
ViewParameterModel.fan = snapp.Object.fan;
ViewParameterModel.ign = snapp.Object.ign;
ViewParameterModel.mode = snapp.Object.mode;
ViewParameterModel.target = snapp.Object.target;
});
return null;
}
...
ViewParameterModel.cs
public class ViewParameterModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool Fan = false;
public bool fan
{
get
{
return Fan;
}
set
{
if (Fan != value)
{
Fan = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("fan"));
}
}
}
private bool Igniter = false;
public bool ign
{
get
{
return Igniter;
}
set
{
if (Igniter != value)
{
Igniter = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ign"));
}
}
}
private bool Auger = false;
public bool aug
{
get
{
return Auger;
}
set
{
if (Auger != value)
{
Auger = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("aug"));
}
}
}
private string Mode = "Off";
public string mode
{
get
{
return Mode;
}
set
{
if (Mode != value)
{
Mode = value;
Debug.WriteLine("Mode: " + Mode);
if (SegmentBindingContext != null)
{
SegmentBindingContext.index = Mode.Equals("Off") ? 0 : Mode.Equals("Start") ? 1 : Mode.Equals("Smoke") ? 2 :
Mode.Equals("Hold") ? 3 : Mode.Equals("Ignite") ? 4 : 5;
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("mode"));
}
}
}
private int Target = 0;
public int target
{
get
{
return Target;
}
set
{
if (Target != value)
{
Target = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("target"));
}
}
}
}
}

how to implement Android In App BillingClient in Xamarin.Android Asynchronously

I am trying to implement below java code in c# referring to Android documentation
List<String> skuList = new ArrayList<> ();
skuList.add("premium_upgrade");
skuList.add("gas");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(SkuType.INAPP);
billingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult,
List<SkuDetails> skuDetailsList) {
// Process the result.
}
});
I have here 2 questions. I thought that i would run this code on a separate thread than UI thread like below to keep my ui responsive while network connection is done. is that the correct approach? QuerySkuDetailsAsync is called async but doesnt implement as async. how should this be working and how to handle in c# because it will fire and forget but Listener to handle the response.
public async Task<List<InAppBillingProduct>> GetProductsAsync(List<string> ProductIds)
{
var getSkuDetailsTask = Task.Factory.StartNew(() =>
{
var prms = SkuDetailsParams.NewBuilder();
var type = BillingClient.SkuType.Inapp;
prms.SetSkusList(ProductIds).SetType(type);
BillingClient.QuerySkuDetailsAsync(prms.Build(), new SkuDetailsResponseListener());
return InAppBillingProducts;
});
return await getSkuDetailsTask;
}
2nd question regarding how to handle with the listener as below. How do I return value from the listener. I need return list of InAppBillingProduct object.
public class SkuDetailsResponseListener : Java.Lang.Object, ISkuDetailsResponseListener
{
public void OnSkuDetailsResponse(BillingResult billingResult, IList<SkuDetails> skus)
{
if (billingResult.ResponseCode == BillingResponseCode.Ok)
{
// get list of Products here and return
}
}
}
FYI. This is how I did it. This is not a complete code but this will give you and idea.
Listener - PCL
============
private async Task EventClicked()
{
var skuList = new List<string>();
skuList.Add("[nameofsubscriptionfoundinyourgoogleplay]");
if (await _billingClientLifecycle.Initialize(skuList, DisconnectedConnection))
{
var firstProduct = _billingClientLifecycle?.ProductsInStore?.FirstOrDefault();
if (firstProduct != null)
{
//purchase here
}
}
}
private void DisconnectedConnection()
{
//Todo.alfon. handle disconnection here...
}
Interface - PCL
===========
public interface IInAppBillingMigratedNew
{
List<InAppBillingPurchase> PurchasedProducts { get; set; }
List<InAppBillingProduct> ProductsInStore { get; set; }
Task<bool> Initialize(List<String> skuList, Action onDisconnected = null);
}
Dependency - Platform Droid
===============
[assembly: XF.Dependency(typeof(InAppBillingMigratedNew))]
public class InAppBillingMigratedNew : Java.Lang.Object, IBillingClientStateListener
, ISkuDetailsResponseListener, IInAppBillingMigratedNew
{
private Activity Context => CrossCurrentActivity.Current.Activity
?? throw new NullReferenceException("Current Context/Activity is null");
private BillingClient _billingClient;
private List<string> _skuList = new List<string>();
private TaskCompletionSource<bool> _tcsInitialized;
private Action _disconnectedAction;
private Dictionary<string, SkuDetails> _skusWithSkuDetails = new Dictionary<string, SkuDetails>();
public List<InAppBillingPurchase> PurchasedProducts { get; set; }
public List<InAppBillingProduct> ProductsInStore { get; set; }
public IntPtr Handle => throw new NotImplementedException();
public Task<bool> Initialize(List<string> skuList, Action disconnectedAction = null)
{
_disconnectedAction = disconnectedAction;
_tcsInitialized = new TaskCompletionSource<bool>();
var taskInit = _tcsInitialized.Task;
_skuList = skuList;
_billingClient = BillingClient.NewBuilder(Context)
.SetListener(this)
.EnablePendingPurchases()
.Build();
if (!_billingClient.IsReady)
{
_billingClient.StartConnection(this);
}
return taskInit;
}
#region IBillingClientStateListener
public void OnBillingServiceDisconnected()
{
Console.WriteLine($"Connection disconnected.");
_tcsInitialized?.TrySetResult(false);
_disconnectedAction?.Invoke();
}
public void OnBillingSetupFinished(BillingResult billingResult)
{
var responseCode = billingResult.ResponseCode;
var debugMessage = billingResult.DebugMessage;
if (responseCode == BillingResponseCode.Ok)
{
QuerySkuDetails();
QueryPurchases();
_tcsInitialized?.TrySetResult(true);
}
else
{
Console.WriteLine($"Failed connection {debugMessage}");
_tcsInitialized?.TrySetResult(false);
}
}
#endregion
#region ISkuDetailsResponseListener
public void OnSkuDetailsResponse(BillingResult billingResult, IList<SkuDetails> skuDetailsList)
{
if (billingResult == null)
{
Console.WriteLine("onSkuDetailsResponse: null BillingResult");
return;
}
var responseCode = billingResult.ResponseCode;
var debugMessage = billingResult.DebugMessage;
switch (responseCode)
{
case BillingResponseCode.Ok:
if (skuDetailsList == null)
{
_skusWithSkuDetails.Clear();
}
else
{
if (skuDetailsList.Count > 0)
{
ProductsInStore = new List<InAppBillingProduct>();
}
foreach (var skuDetails in skuDetailsList)
{
_skusWithSkuDetails.Add(skuDetails.Sku, skuDetails);
//ToDo.alfon. make use mapper here
ProductsInStore.Add(new InAppBillingProduct
{
Name = skuDetails.Title,
Description = skuDetails.Description,
ProductId = skuDetails.Sku,
CurrencyCode = skuDetails.PriceCurrencyCode,
LocalizedIntroductoryPrice = skuDetails.IntroductoryPrice,
LocalizedPrice = skuDetails.Price,
MicrosIntroductoryPrice = skuDetails.IntroductoryPriceAmountMicros,
MicrosPrice = skuDetails.PriceAmountMicros
});
}
}
break;
case BillingResponseCode.ServiceDisconnected:
case BillingResponseCode.ServiceUnavailable:
case BillingResponseCode.BillingUnavailable:
case BillingResponseCode.ItemUnavailable:
case BillingResponseCode.DeveloperError:
case BillingResponseCode.Error:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
case BillingResponseCode.UserCancelled:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
// These response codes are not expected.
case BillingResponseCode.FeatureNotSupported:
case BillingResponseCode.ItemAlreadyOwned:
case BillingResponseCode.ItemNotOwned:
default:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
}
}
#endregion
#region Helper Methods Private
private void ProcessPurchases(List<Purchase> purchasesList)
{
if (purchasesList == null)
{
Console.WriteLine("No purchases done.");
return;
}
if (IsUnchangedPurchaseList(purchasesList))
{
Console.WriteLine("Purchases has not changed.");
return;
}
_purchases.AddRange(purchasesList);
PurchasedProducts = _purchases.Select(sku => new InAppBillingPurchase
{
PurchaseToken = sku.PurchaseToken
})?.ToList();
if (purchasesList != null)
{
LogAcknowledgementStatus(purchasesList);
}
}
private bool IsUnchangedPurchaseList(List<Purchase> purchasesList)
{
// TODO: Optimize to avoid updates with identical data.
return false;
}
private void LogAcknowledgementStatus(List<Purchase> purchasesList)
{
int ack_yes = 0;
int ack_no = 0;
foreach (var purchase in purchasesList)
{
if (purchase.IsAcknowledged)
{
ack_yes++;
}
else
{
ack_no++;
}
}
//Log.d(TAG, "logAcknowledgementStatus: acknowledged=" + ack_yes +
// " unacknowledged=" + ack_no);
}
private void QuerySkuDetails()
{
var parameters = SkuDetailsParams
.NewBuilder()
.SetType(BillingClient.SkuType.Subs)
.SetSkusList(_skuList)
.Build();
_billingClient.QuerySkuDetailsAsync(parameters, this);
}
private void QueryPurchases()
{
if (!_billingClient.IsReady)
{
Console.WriteLine("queryPurchases: BillingClient is not ready");
}
var result = _billingClient.QueryPurchases(BillingClient.SkuType.Subs);
ProcessPurchases(result?.PurchasesList?.ToList());
}
#endregion
}

Acumatica PXDefault Drop List

I'm trying to change the default value to Debit Memo when adding a new row in the Payments and Applications screen of the Accounts Receivable module. I've tried setting PXDefault(ARDocType.DebitMemo), but it doesn't appear to be working. Can anyone point me in the right direction?
The payments and applications page uses some interesting logic to determine the default value used, they define it in a call during the rowselected event for the header document.
protected virtual void ARPayment_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
{
.....
SetDocTypeList(e.Row);
.....
}
public static void SetDocTypeList(PXCache cache, string docType)
{
string defValue = ARDocType.Invoice;
List<string> values = new List<string>();
List<string> labels = new List<string>();
if (docType == ARDocType.Refund)
{
defValue = ARDocType.CreditMemo;
values.AddRange(new string[] { ARDocType.CreditMemo, ARDocType.Payment, ARDocType.Prepayment });
labels.AddRange(new string[] { Messages.CreditMemo, Messages.Payment, Messages.Prepayment });
}
else if (docType == ARDocType.Payment || docType == ARDocType.VoidPayment)
{
values.AddRange(new string[] { ARDocType.Invoice, ARDocType.DebitMemo, ARDocType.CreditMemo, ARDocType.FinCharge });
labels.AddRange(new string[] { Messages.Invoice, Messages.DebitMemo, Messages.CreditMemo, Messages.FinCharge });
}
else
{
values.AddRange(new string[] { ARDocType.Invoice, ARDocType.DebitMemo, ARDocType.FinCharge });
labels.AddRange(new string[] { Messages.Invoice, Messages.DebitMemo, Messages.FinCharge });
}
if (!PXAccess.FeatureInstalled<FeaturesSet.overdueFinCharges>() && values.Contains(ARDocType.FinCharge) && labels.Contains(Messages.FinCharge))
{
values.Remove(ARDocType.FinCharge);
labels.Remove(Messages.FinCharge);
}
PXDefaultAttribute.SetDefault<ARAdjust.adjdDocType>(cache, defValue);
PXStringListAttribute.SetList<ARAdjust.adjdDocType>(cache, null, values.ToArray(), labels.ToArray());
}
private void SetDocTypeList(object Row)
{
ARPayment row = Row as ARPayment;
if (row != null)
{
SetDocTypeList(Adjustments.Cache, row.DocType);
}
}
To obtain the default you require you may implement the following code :
public class ARPaymentEntryExtension : PXGraphExtension<ARPaymentEntry>
{
protected virtual void ARPayment_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
{
PXDefaultAttribute.SetDefault<ARAdjust.adjdDocType>(Base.Adjustments.Cache, ARDocType.DebitMemo);
}
}

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);
}

Initializing[Unavailable#]-failed to lazily initialize a collection, no session or session was closed

I have one class called fixture which has two properties description and date. Now i dont want to operate directly on thi stwo propert but i wanted to operate on Some collection object "Allattribute" in this example which i m feeling while in get and set of each property.
retrival is working fine but while persisting i m getting this error
Initializing[Unavailable#]-failed to lazily initialize a collection, no session or session was closed.
Code for Model and Mapper is as below:
public class Fixture : EntityBase
{
public Fixture() {
//PogObject = new List<PogObject>();
//ObjectFixtureDate = new List<Objectfixturedate>();
}
public virtual long IDPOGObject { get; set; }
private ObservableCollection<DictionaryEntry> m_allattributes = new ObservableCollection<DictionaryEntry>();
private IList<FixtureDate> mFixtureDate = new List<FixtureDate>();
private IList<FixtureDesc> mFixtureDesc = new List<FixtureDesc>();
private IList<FixtureFlag> mFixtureFlag = new List<FixtureFlag>();
public virtual IList<FixtureDate> FixtureDate
{
get
{
mFixtureDate.Clear();
foreach (var item in m_allattributes)
{
if (item.Value is FixtureDate)
{
mFixtureDate.Add((FixtureDate)item.Value);
}
}
return mFixtureDate;
}
set
{
//try
//{
if (value.Count != 0)
{
foreach (var item in value)
{
DictionaryEntry dEntry = new DictionaryEntry(item.Dictionary.DictionaryName, item);
if (!m_allattributes.Contains(dEntry))
{
m_allattributes.Add(dEntry);
}
}
}
//}
//catch (Exception ex)
//{
//}
mFixtureDate = value;
}
}
public virtual IList<FixtureDesc> FixtureDescription
{
get
{
mFixtureDesc.Clear();
foreach (var item in m_allattributes)
{
if (item.Value is FixtureDesc)
{
if (!mFixtureDesc.Contains((FixtureDesc)item.Value))
{
mFixtureDesc.Add((FixtureDesc)item.Value);
}
}
}
return mFixtureDesc;
}
set
{
if (value.Count != 0)
{
foreach (var item in value)
{
DictionaryEntry dEntry = new DictionaryEntry(item.Dictionary.DictionaryName, item);
// DictionaryEntry dEntry = new DictionaryEntry(item.DescNum, item);
if (!m_allattributes.Contains(dEntry))
{
m_allattributes.Add(dEntry);
}
}
}
mFixtureDesc = value;
}
}
}
Mapper Class:
public class FixtureMap : ClassMap {
public FixtureMap() {
Table("SPOG_ObjectFixture");
Not.LazyLoad();
Id(x => x.IDPOGObject).GeneratedBy.Foreign("PogObject");
HasMany(x => x.FixtureDescription).Cascade.AllDeleteOrphan().Inverse().Not.LazyLoad().KeyColumn("IDPOGObject").Fetch.Join();
HasMany(x => x.FixtureDate).Cascade.AllDeleteOrphan().Inverse().Not.LazyLoad().KeyColumn("IDPOGObject");
}
}

Resources