null reference exception when i delete item from sync realm database in xamarin - xamarin

I got a null reference exception after I delete any item from the sync realm database .
the item is deleted from the database but it throws the exception and craches
I don't know why it throws this exception or where is the null object .
but when I delete this line the exception disappears :
listView.ItemsSource = Employees;
PS : this exception appeared when I tried to sync the realm database online.
public MainPage()
{
InitializeComponent();
Initialize();
listView.ItemsSource = Employees;
}
private async Task Initialize()
{
_realm = await OpenRealm();
Employees = _realm.All<Employee>();
Entertainments= _realm.All<Entertainment>();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Employees)));
}
void OnDeleteClicked(object sender, EventArgs e)
{
try {
var o = _realm.All<Employee>().FirstOrDefault(c => c.EmpId == 4);
if (o != null)
_realm.Write(() => { _realm.Remove(o); });
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Employees)));
}
catch (Exception exp)
{
string msg = exp.Message;
}
}
here is a screenshot of the exception

THIS SOLVED THE EXCEPTION ! Thank youu . but the listview is not auto updated now !
According to your code and description, you want to delete item form realm database, and update Listview. I find you use PropertyChanged to want to update Employees, but it doesn't work, because you delete item from realm database, don't change Employees, so it is not fired PropertyChanged event.
List<Employee> Employees = new List<Employee>();
private async Task Initialize()
{
_realm = await OpenRealm();
Employees = _realm.All<Employee>().ToList(); ;
Entertainments = _realm.All<Entertainment>();
}
void OnDeleteClicked(object sender, EventArgs e)
{
try
{
var o = _realm.All<Employee>().FirstOrDefault(c => c.EmpId == 4);
if (o != null)
_realm.Write(() => { _realm.Remove(o); });
Employees = _realm.All<Employee>().ToList();
listView.ItemsSource = Employees;
}
catch (Exception exp)
{
string msg = exp.Message;
}
}
Helpful article for you:
https://dzone.com/articles/xamarinforms-working-with-realm-database

Related

Exception of type 'System.Collections.Generic.KeyNotFoundException' was thrown ? in Xamarin.Forms

i wanna use simple database in Xamarin Forms. So i used this code;
public partial class DBExample : ContentPage
{
string _dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),"myDB.db3");
public DBExample ()
{
InitializeComponent ();
}
private async void InsertButton(object sender, EventArgs e)
{
SQLiteConnection db=null;
try
{
db = new SQLiteConnection(_dbPath);
}
catch (Exception ex)
{
await DisplayAlert(null, ex.Message, "OK");
}
db.CreateTable<Users>();
var maxPk = db.Table<Users>().OrderByDescending(c => c.Id).FirstOrDefault();
Users users = new Users()
{
Id = (maxPk == null ? 1 : maxPk.Id + 1),
Name = userName.Text
};
db.Insert(users);
await DisplayAlert(null,userName.Text + "saved","OK");
await Navigation.PopAsync();
}
}
and i have problem. You can see it in Headtitle.
"Exception of type 'System.Collections.Generic.KeyNotFoundException' was thrown"
im waiting your support. Thanks for feedback.

Linq update Trouble

I want to update my Azure database using linq in my xamarin.forms project
below is the initalise and sync methods that connect to the database. These work successfully. My problem is that I want to update a record is the database. Any suggestions are welcome.
MobileServiceClient client = null;
IMobileServiceSyncTable<Shop> ShopTable2;
bool isInitialised;
public async Task Initialize()
{
if (isInitialised)
{
return;
}
this.client = new MobileServiceClient("link to database");
MobileServiceClient client = new MobileServiceClient("link to databse");
const string path = "user.db";
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<Shop>();
await this.client.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
ShopTable2= this.client.GetSyncTable<Shop>();
isInitialised = true;
}
sync method
public async Task Sync()
{
try
{
await shopTable2.PullAsync("allusers3", shopTable2.CreateQuery());
await client.SyncContext.PushAsync();
}
catch (Exception ex)
{
Debug.WriteLine("Unable to sync " + ex);
}
}
where I want to update the records here:
public async void BuyProducts(string Pname)
{
string productname = Pname;
await Initialize();
await SyncBookings();
List<Shop_TBL> item = await BookingsTable2
.Where(todoItem => todoItem.ProductName == productname)
.ToListAsync();
}
Assuming you are using Entity Framework as your ORM:
Select the entity you want to update.
var book = db.Books.First(b => b.Id == _id);
Change the property:
book.Name = "Something else";
Save the changes:
await db.SaveChangesAsync();
or
db.SaveChanges();
That's how you do an update.

get outlook single occurrence of recurring calendar event from double click on calendar

I am creating an outlook plugin that opens a SharePoint Calendar event for editing. The SharePoint Calendar is added to outlook as an overlay.
When clicking on the series event and editing a series everything works fine. But when I select just this one (occurrence). I am unable to get any of the properties for the AppointmentItem object.
I have tried both the ReadComplete and the Open events and still get an exception:
Exception from HRESULT: 0x80040108" and I am unable to access the
Parent. It appears all of the properties are null except Class = 26
and MessageClass = "IPM.Appointment"
private void Application_ItemLoad(object item)
{
_item = item;
try
{
if (!(item is AppointmentItem) || !_exp.CurrentFolder.Name.Contains("Test - Conference Room ")) return;
_warnUser = true;
_apptItem = (AppointmentItem) item;
_apptItem.ReadComplete += test;
_apptItem.Open += McAI_Open;
}
catch (Exception ex)
{
var expMessage = ex.Message;
MessageBox.Show(expMessage);
}
}
private static void ThisAddIn_Shutdown(object sender, EventArgs e)
{
// Note: Outlook no longer raises this event. If you have code that
// must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
}
private void McAI_Open(ref bool cancel)
{
_warnUser = false;
var conferenceRoom = _exp.CurrentFolder.Name;
conferenceRoom = conferenceRoom.Replace("Test - ", "");
if (!(_item is AppointmentItem)){return;}
try
{
var g = _apptItem.IsRecurring;
if (_apptItem != null && _exp.CurrentFolder.Name.Contains("Test") && _apptItem.Location != null)
{
var location = _apptItem.Location;
var result = location.Substring(location.LastIndexOf(':') + 1);
cancel = true;
var sharePointItemId = int.Parse(result);
var frm = new FrmCalendarSelection(
"<SharePointURL>" + conferenceRoom,
sharePointItemId);
frm.Show();
frm.Closed += Frm_Closed;
}
else if (_apptItem != null && _exp.CurrentFolder.Name.Contains("Test") && _apptItem.Location == null)
{
cancel = true;
var frm = new FrmCalendarSelection(
"<SharePointURL>" + conferenceRoom);
frm.Show();
frm.Closed += Frm_Closed;
}
}
catch (Exception e)
{
throw e;
}
}

Code to execute if a navigation fails

Hello I have no idea where I should start looking. I add few prop (before that my code run fine), then I get
System.Diagnostics.Debugger.Break();
so then I comment that changes, but that didn't help.
Could you suggest me where I should start looking for solution?
MyCode:
namespace SkydriveContent
{
public partial class MainPage : PhoneApplicationPage
{
private LiveConnectClient client;
FilesManager fileManager = new FilesManager();
// Constructor
public MainPage()
{
InitializeComponent();
}
private void signInButton1_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
infoTextBlock.Text = "Signed in.";
client.GetCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetAsync("/me/skydrive/files/");
fileManager.CurrentFolderId = "/me/skydrive/files/";
}
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}
void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
//Gdy uda nam się podłaczyc do konta skydrive
if (e.Error == null)
{
signInButton1.Visibility = System.Windows.Visibility.Collapsed;
infoTextBlock.Text = "Hello, signed-in user!";
List<object> data = (List<object>)e.Result["data"];
fileManager.FilesNames.Clear();
filemanager.filesnames.add("..");
foreach (IDictionary<string,object> item in data)
{
File file = new File();
file.fName = item["name"].ToString();
file.Type = item["type"].ToString();
file.Url = item["link"].ToString();
file.ParentId = item["parent_id"].ToString();
file.Id = item["id"].ToString();
fileManager.Files.Add(file);
fileManager.FilesNames.Add(file.fName);
}
FileList.ItemsSource = fileManager.FilesNames;
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
}
private void FileList_Tap(object sender, GestureEventArgs e)
{
foreach (File item in fileManager.Files)
{
if (item.fName == FileList.SelectedItem.ToString() )
{
switch (item.Type)
{
case "file":
MessageBox.Show("Still in progress");
break;
case "folder":
fileManager.CurrentFolderId = item.ParentId.ToString();
client.GetAsync(item.Id.ToString() + "/files");
break;
default:
MessageBox.Show("Coś nie działa");
break;
}
}
else if (FileList.SelectedItem.ToString() == "..")
{
client.GetAsync(fileManager.CurrentFolderId + "/files");
}
}
}
}
}
Running stop at that line.
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
You should check all of the URLs you have both in the XAML and code. When you get to the NavigationFailed function, it means that the phone tried to navigate to some page that did not existed. We would be able to help more if you could tell what were you doing when the app threw the exception.
System.Diagnostics.Debugger.Break();
usually happens because of an Uncaught Exception.
Either post the code which started giving problems, or the stack trace when you encounter this problem.
No one can tell anything without actually seeing what you are doing.

Unable to show the selected item in the Wp7 Listpicker control

Basically i am trying to pull the contacts from the phone and showing them in the Listpicker control for a feature in my app. I have two Listpickers, one for name of contacts list and the other showing the list of phonenumbers for the chosen contact.
Here is my code:
//Declarations
ContactsSearchEventArgs e1;
String SelectedName;
String SelectedNumber;
List<string> contacts = new List<string>();
List<string> phnum = new List<string>();
public AddressBook() // Constructor
{
InitializeComponent();
Contacts contacts = new Contacts();
contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(contacts_SearchCompleted);
contacts.SearchAsync(string.Empty,FilterKind.None,null);
}
void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
e1 = e;
foreach (var result in e.Results)
{
if (result.PhoneNumbers.Count() != 0)
{
contacts.Add(result.DisplayName.ToString());
}
}
Namelist.ItemsSource = contacts;
}
private void Namelist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedName = (sender as ListPicker).SelectedItem.ToString();
phnum.Clear();
foreach (var result in e1.Results)
{
if (SelectedName == result.DisplayName)
{
phnum.Add(result.PhoneNumbers.FirstOrDefault().ToString());
}
}
Numbers.ItemsSource = phnum;
}
private void Numbers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedNumber = (sender as ListPicker).SelectedItem.ToString();
}
Am able to populate the Numberlist with phonenumbers for the chosen name at the Listpicker background, but the number is not showing up in the front. I think Numbers_SelectionChanged() event is called only one time when the page loads and am not seeing it triggerd when i change the contact list. Anyone has an idea of where am going wrong ?
If you change
List<string>
To
ObservableCollection<string>
this should work.
Also then you only need to set the ItemSource once, in Xaml or you constructor.
But you may run into another issue with the November 2011 Toolkit and ListPicker.
See more in thread.
private void Namelist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedName = (sender as ListPicker).SelectedItem.ToString();
phnum = new List<string>(); // Changed instead of phnum.Clear()
foreach (var result in e1.Results)
{
if (SelectedName == result.DisplayName)
{
phnum.Add(result.PhoneNumbers.FirstOrDefault().ToString());
}
}
Numbers.ItemsSource = phnum;
}
This works !!. While debugging i found its phnum.Clear() giving a problem. So i thought to create a new instance of phnum list for selected contact.

Resources