While navigating to Register Player details screen, throws object reference error in Xamarin.Forms - xamarin

On click on the Register_OnClicked button in the Xamarin.Forms app, system throws System.NullReferenceException: Object reference not set to an instance of an object This button will allow app to navigate to Player Register details screen from where the system save data. Could someone please advise about the cause of the error? I couldn't figure out the reason for that error yet, have restarted the app, perform the clean buildoperation, but still the same.
Database library using : sqlite-net-pcl
//MainPage.xaml.cs details
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
public async void NavigateButton_OnClicked(object sender, EventArgs e)
{
var tabbedPage = new TabbedPage();
tabbedPage.Children.Add(new Home("Welcome"+' '+emailEntry.Text+' '+",have a nice day!"));
tabbedPage.Children.Add(new Map());
tabbedPage.Children.Add(new Settings());
await Navigation.PushAsync(tabbedPage);
}
public async void Register_OnClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new Register());
}
}
Register.xaml.cs details where the saving of Player details:
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Linq;
namespace soccerapp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Register : ContentPage
{
public SQLiteConnection conn;
public Register()
{
InitializeComponent();
conn = DependencyService.Get<Isqlite>().GetConnection();
conn.CreateTable<PlayerDetails>();
}
public void RegisterSave_OnClicked(object sender, EventArgs e)
{
PlayerDetails playerDetails = new PlayerDetails();
playerDetails.FullName = fullNameEntry.Text;
playerDetails.Mobile = mobileEntry.Text;
playerDetails.SoccerPosition = soccerpostionEntry.Text;
playerDetails.Email = emailRegister.Text;
playerDetails.Password = passwordEntry.Text;
int x = 0;
try
{
x = conn.Insert(playerDetails);
}
catch (Exception ex)
{
throw ex;
}
if (x == 1)
{
DisplayAlert("Registration", "Player Registered Successfully", "Cancel");
}
else
{
DisplayAlert("Registration Failled!!!", "Please try again", "ERROR");
}
}
}
}
SQlite Connection class created and return connection:
public class SQliteDroid : Isqlite
{
public SQLiteConnection GetConnection()
{
var dbase = "soccerpep";
var dbpath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
var path = Path.Combine(dbpath, dbase);
var connection = new SQLiteConnection(path);
return connection;
}
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/nZ8GZ.png
Error details from Debug > Windows > Call Stack add below;
0xFFFFFFFFFFFFFFFF in System.Diagnostics.Debugger.Mono_UnhandledException_internal C#
0x1 in System.Diagnostics.Debugger.Mono_UnhandledException C#
0x20 in Android.Runtime.DynamicMethodNameCounter.43 C#
0x12 in System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw C#
0x6 in System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_0 C#
0xC in Android.App.SyncContext. C#
0xE in Java.Lang.Thread.RunnableImplementor.Run C#
0xA in Java.Lang.IRunnableInvoker.n_Run C#
0x11 in Android.Runtime.DynamicMethodNameCounter.43 C#

Debug through the Constructor for your Register page, and the GetConnection method of your SqliteDroid class.
I've seen hard-to-find errors like this when the Dependency Injection fails. This could be either because of an error in GetConnection, or because SqliteDroid has not been registered in your DependencyService.

Related

Binding text label on a home page to a timer

We have a really simple app, the idea is the timer will update a label on the home screen depending on different configuration within the mobile app. I have created the binding and can update the homepage from it's self but not from the timer. I think what is missing is a OnChange within the home page to detect if the string has changed.
Display layout code, bind the label to the name "LabelText"
<Label
Text = "{Binding LabelText, Mode=TwoWay}"
x:Name="MainPageStatusText"
HorizontalOptions="CenterAndExpand"
Grid.Row="2"
Grid.Column="0"
Grid.ColumnSpan="6"
VerticalOptions="CenterAndExpand"
TextColor="White"
FontSize="Medium"/>
This is the class file to link the text string to the label, I can see it been called from the different places but when it's called from the app.cs it does not work
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Xamarin.Forms;
namespace Binding_Demo
{
public class MyClass : INotifyPropertyChanged
{
protected void OnPropertyChanged(PropertyChangedEventArgs e)
{ PropertyChanged?.Invoke(this, e); }
protected void OnPropertyChanged(string propertyName)
{ OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); }
public event PropertyChangedEventHandler PropertyChanged;
private string labelText;
public string LabelText
{
get {
return labelText;
}
set
{
labelText = value;
OnPropertyChanged("LabelText");
}
}
}
}
This is the code inside the homepage, this works and I can see it sending data to the text label
public static MyClass _myClass = new MyClass();
public Homepage()
{
BindingContext = _myClass;
_myClass.LabelText = "Inside the home page";
}
This is the App.cs code, we start the timer and then want to set the text on the Homepage label. I can see the class been called, but it does not set the text.
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Binding_Demo
{
public partial class App : Application
{
public static MyClass _myClass = new MyClass();
public App()
{
//InitializeComponent();
Device.StartTimer(TimeSpan.FromSeconds(10), () =>
{
Task.Run(() =>
{
Debug.WriteLine("Timer has been triggered");
// !!!!! This is not setting the text in the label !!!!!
BindingContext = _myClass;
_myClass.LabelText = "Inside the timer app";
});
return true; //use this to run continuously
});
MainPage = new NavigationPage(new MainPage());
}
protected override void OnStart()
{
//
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
// force app to mainpage and clear the token
}
}
}
I have created the binding and can update the homepage from it's self but not from the timer.
As Jason said, please make sure the binding model is unique. You could create a global static instance of MyClass in App class, then bind this instance to HomePage.
Check the code:
App.xaml.cs
public partial class App : Application
{
public static MyClass _myClass = new MyClass();
public App()
{
InitializeComponent();
Device.StartTimer(TimeSpan.FromSeconds(5), () =>
{
Task.Run(() =>
{
_myClass.LabelText = "Inside the timer app";
});
return true;
});
MainPage = new NavigationPage(new Homepage());
}
}
Homepage.xaml.cs:
public Homepage()
{
InitializeComponent();
BindingContext = App._myClass;
}

Xamarin white screen in local machine

enter image description here
Hello,
I have a problem with Xamarin, when i run program i see only white screen, just like on picture.
MainPage.xaml.cs have this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
namespace Hello
{
public class App : Application
{
public App()
{ // The root page of your application
MainPage = new ContentPage
{
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
HorizontalTextAlignment = TextAlignment.Center,
Text = "Welcome to Xamarin Forms!"
}
}
}
};
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
I take this code from "Creating Mobile Apps with Xamarin Forms", somebody know what is wrong with this program?
Write your code in Shared project's App.xaml.cs class which is partial class. The code above you are showing is not partial class. Probably, as your screenshot showing you have written App class code in Main.axml.cs file
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace App
{
public partial class App : Application
{
public App()
{
InitializeComponent();
//MainPage = new MainPage();
MainPage = new ContentPage
{
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children =
{
new Label
{
HorizontalTextAlignment=TextAlignment.Center,
Text="Welcome to xamarin forms"
}
}
}
};
}
}
}

How to make back button return to the system Windows Phone

I have a small app there is 3 seconds intro page, then the content page. When I push back button I go back to the intro screen, but I think I should go back to the system. How to do it?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.ServiceModel.Syndication;
using System.Xml;
using Microsoft.Phone.Tasks;
namespace RSS {
public partial class FeedPage : PhoneApplicationPage {
public FeedPage() {
InitializeComponent();
this.Loaded += new RoutedEventHandler(PhonePage1_Loaded);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
clearBackStack();
base.OnNavigatedTo(e);
}
void clearBackStack() {
while (this.NavigationService.BackStack.Any()) {
this.NavigationService.RemoveBackEntry();
}
}
void PhonePage1_Loaded(object sender, RoutedEventArgs e) {
// clearBackStack();
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri("http://www.carmagazine.co.uk/Shared/Handlers/RssHandler.ashx?&N=190&Ns=P_Publication_Date|1&?"));
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
SyndicationFeed feed;
try {
using (XmlReader reader = XmlReader.Create(e.Result)) {
feed = SyndicationFeed.Load(reader);
lista.ItemsSource = feed.Items;
}
} catch (WebException we) { MessageBox.Show("Internet connection is down.");}
}
private void Button_Click(object sender, System.Windows.RoutedEventArgs e) {
WebBrowserTask webBrowserTask = new WebBrowserTask();
String url = (String)((Button)sender).Tag;
webBrowserTask.Uri = new Uri(url);
webBrowserTask.Show();
}
}
}
You should clear the BackStack in the OnNavigateTo method of your content page
while (this.NavigationService.BackStack.Any())
{
this.NavigationService.RemoveBackEntry();
}
The following code is the best practice for the back button key press.
protected override void OnBackKeyPress(CancelEventArgs e)
{
while (NavigationService.CanGoBack)
NavigationService.RemoveBackEntry();
base.OnBackKeyPress(e);
}
This ensures that your application will exit and return to the main screen on pressing the BackKey.

Taking screenshot of windows phone 7.5 and sending over through TCP

i am stuck on how to take a screenshot of my windows phone 7.5 and sending it over TCP. i have no experience in doing socket program and I/O and am doing what i can through tutorials over the internet. This is what i have done.
From the codes below i am stuck in how i can send the writeableBitMap over TCP encoded as a Jpeg periodically running in the WP7.5 background, whereby a program on a desktop will receive it as a jpeg image so it can be displayed creating a windows phone to desktop streaming effect.
my mainPage of my windows phone 7.5 application using a library i have created from a tutorial for taking care of the sockets connection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone;
using System.Windows.Media;
using System.IO;
namespace helloworld
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
SocketLibrary.socketLib sl = new SocketLibrary.socketLib();
private string hostIP = "127.0.0.1";
public MainPage()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, RoutedEventArgs e)
{
bool retVal;
retVal = sl.EstablishTCPConnection(hostIP);
WriteableBitmap bmpCurrentScreenImage = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
var ms = new MemoryStream();
// Send the picture.
bmpCurrentScreenImage.SaveJpeg(ms, bmpCurrentScreenImage.PixelWidth, bmpCurrentScreenImage.PixelHeight, 0, 90);
ms.Seek(0, SeekOrigin.Begin);
retVal = sl.Send(ms);
sl.CloseSocket();
}
}
}
the socket library
namespace SocketLibrary
{
public class socketLib
{
Socket s = null;
static ManualResetEvent done = new ManualResetEvent(false);
private Int16 portNo = 3334;
public socketLib()
{
}
public bool EstablishTCPConnection(string host)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = new DnsEndPoint(host, portNo);
socketEventArg.Completed += new
EventHandler<SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
{
done.Set();
});
done.Reset();
s.ConnectAsync(socketEventArg);
return done.WaitOne(10000);
}
public bool Send(MemoryStream data)
{
byte[] msData = data.ToArray();
if (s != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = s.RemoteEndPoint;
socketEventArg.UserToken = null;
socketEventArg.Completed += new
EventHandler<SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
{
done.Set();
});
socketEventArg.SetBuffer(msData, 0, msData.Length);
done.Reset();
s.SendAsync(socketEventArg);
return done.WaitOne(10000);
}
return false;
}
public void CloseSocket()
{
if (s != null)
{
s.Close();
}
}
}
}
check this
http://www.charlespetzold.com/blog/2011/05/Windows-Phone-Screen-Shots.html
http://blog.galasoft.ch/archive/2010/12/28/taking-a-screenshot-from-within-a-silverlight-wp7-application.aspx

Detect Autoscrollposition value change in panel

How to detect if the Autoscrollposition value changes in the panel1?
For example,
textbox1 and textbox2.
which added in panel1. The autoscroll property is set to true.
I am only interested in detecting when the value of panel autoscrollposition changes.
The above for dynamic textboxes which are incremented.
Software in use: C#, Visual Studio 2005.
The Component required for it. is:
ListBox1
ListBox2
Panel
Button.
The Namespace for Class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
Here is the Complete Solution Code:
namespace detectpanelvalue
{
public partial class Form1 : Form
{
private Point tbpoint = new Point(10, 14);
private Point tbbpoint = new Point(300, 14);
private ArrayList arylst;
private ArrayList arylst1;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
panel1.Paint += new PaintEventHandler(panel1_Paint);
}
void panel1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Point pnlpt;
pnlpt = panel1.AutoScrollPosition;
if (tbpoint !=null || pnlpt != null )
{
pnlpt = tbpoint;
}
arylst1 = new ArrayList();
arylst1.Add(pnlpt);
}
private void runtime()
{
foreach (Point pt in arylst)
{
listBox1.Items.Add(pt);
}
foreach (Point ptt in arylst1)
{
listBox2.Items.Add(ptt);
}
}
private void button1_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.Location = tbpoint;
this.panel1.Controls.Add(tb);
tbpoint.Y += 30;
TextBox bb = new TextBox();
bb.Location = tbbpoint;
this.panel1.Controls.Add(bb);
tbbpoint.Y += 30;
arylst = new ArrayList();
arylst.Add(tbpoint);
runtime();
}
}
}
It is helpful for adjust the panel autoscrollposition.

Resources