NullPointerException on set label text - xamarin

Whenever I try to set the text of a label from a different ViewController on a storyboard, i get a NullPointerException:
System.NullReferenceException: Object reference not set to an instance of an object in the line UIApplication.Main(args, null, "AppDelegate");
Both of the view controllers are using the same class.
This is my code:
async partial void LoginBtn_TouchUpInside(UIButton sender)
{
loadingIndicator.StartAnimating();
var uname = username.Text;
var pwd = password.Text;
Uri loginUri = new Uri($"http://<loginapi>:8080/api/login?user={uname}&pwd={pwd}");
WebClient c = new WebClient();
string[] userinfo = parseJsonToArray(await c.DownloadStringTaskAsync(loginUri));
welcomeLabel.Text = "Welcome, " + userinfo[0]; //index 0 of userinfo contains the user's full name.
loadingIndicator.StopAnimating();
PerformSegue("loggedInSegue", this);
}
I have verified that it is getting the correct information by logging it to the console, and everything else works perfectly fine if I comment out the welcomeLabel.Text part.

You can enable all exception in your Visual Studio or Xamarin Studio so that you can break at line contain the null reference. Check this to enable all exceptions
http://www.stefandevo.com/2015/12/20/xamarin-studio-tip-break-on-all-exceptions/

Related

Parameters are empty when submitting request for adapter authentication on Android

I use adapter authentication in my Xamarin.Forms app with the IBM MFP SDK. The adapter requires a username and a password.
In my iOS app (with the exact same shared code) everything works as it should.
In my Android app the parameters are empty (found that out using Charles / Fiddler).
I debugged the process and my Identity variable with username and password is not null and correctly filled in.
public override AdapterAuthenticationInfo GetAdapterAuthenticationParameters()
{
var parameters = new string[] { Identity.Email, Identity.Password };
var invocationData = new WorklightProcedureInvocationData("AuthAdapter", "submitAuthentication", parameters);
var authInfo = new AdapterAuthenticationInfo();
authInfo.InvocationData = invocationData;
return authInfo;
}
Can you try running your app using object array instead of string array and see if that works?
var parameters = new object[] { Identity.Email, Identity.Password };

MVVMCross Manual Bind in MvxFragment with MvxViewPagerFragmentAdapter

I'm using an implementation of Cheesebaron's MvxViewPagerFragmentAdapter example that can be found here http://blog.ostebaronen.dk/2013/07/fragments-and-viewpager-with-mvx.html
var fragments = new List<MvxViewPagerFragmentAdapter.FragmentInfo>
{
new MvxViewPagerFragmentAdapter.FragmentInfo
{
FragmentType = typeof(JobDetailsView),
Title = "Detail",
ViewModel = ViewModel
},
new MvxViewPagerFragmentAdapter.FragmentInfo
{
FragmentType = typeof(JobFeaturesView),
Title = "Info",
ViewModel = ViewModel
}
}
Within my JobDetailsView's OnCreateView, I can inflate my layout specified using BindingInflate and any bindings that I have specified in the XML layout work correctly.
I now have a requirement to bind some elements programmatically, which i have tried to do using CreateBindingSet, but the bindings do not work. I've tried a simple text property and a button click. Both of these work when specified in the XML.
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Android.OS.Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
this.EnsureBindingContextIsSet(savedInstanceState);
_view = this.BindingInflate(Resource.Layout.jobview_details, null);//jobview_withtabs_details
var signatureCard = _view.FindViewById<CardFeature>(Resource.Id.signature_cardview);
signatureCard.FindViewById<TextView>(Resource.Id.tv_basecard_header_title).Text = "Signature";
var signatureButton = signatureCard.FindViewById<Button>(Resource.Id.btn_basecard_footer).Text = "Capture";
var set = this.CreateBindingSet<JobDetailsView, JobWithTabsViewModel>();
set.Bind(signatureButton).To(vm => vm.SignatureClickCommand);
set.Apply();
return _view;
}
in my output window, i can see this, but i don't know what to do to fix it:
04-16 17:40:43.721 I/mono-stdout(27727): MvxBind:Error: 23.79 Empty binding target passed to MvxTargetBindingFactoryRegistry
MvxBind:Warning: 23.80 Failed to create target binding for binding for SignatureClickCommand
[0:] MvxBind:Warning: 23.80 Failed to create target binding for binding for SignatureClickCommand
04-16 17:40:43.731 I/mono-stdout(27727): MvxBind:Warning: 23.80 Failed to create target binding for binding for SignatureClickCommand
Anyone have any ideas?
UPDATE
In typical fashion, left it for an hour and realised my mistake.
I was being lazy by typing:
var signatureButton = signatureCard.FindViewById<Button>(Resource.Id.btn_basecard_footer).Text = "Capture"
Which was confusing the binding. Switched to:
var signatureButton = signatureCard.FindViewById<Button>(Resource.Id.btn_basecard_footer);
signatureButton.Text = "Capture";
And it works perfectly
An updated example using TabView and ViewPager is available here: https://github.com/MvvmCross/MvvmCross-AndroidSupport/tree/master/Samples
It uses the latest stuff from the Android design libraries.

Xamarin Social post without interface prompt - ShareItemAsync

I'm trying to post directly to facebook/twitter without prompting the user with a UIViewController using the following code:
// 1. Create the service
var facebook = new FacebookService {
ClientId = "<App ID from developers.facebook.com/apps>",
RedirectUrl = new System.Uri ("<Redirect URL from developers.facebook.com/apps>")
};
// 2. Create an item to share
var item = new Item { Text = "Xamarin.Social is the bomb.com." };
item.Links.Add (new Uri ("http://github.com/xamarin/xamarin.social"));
// 3. Present the UI on iOS
var shareController = facebook.GetShareUI (item, result => {
// result lets you know if the user shared the item or canceled
DismissViewController (true, null);
});
PresentViewController (shareController, true, null);
BUT the Xamarin.Social instructions say:
As an alternative to presenting the share UI, you can share items directly using the **ShareItemAsync** method of the service.
https://github.com/xamarin/Xamarin.Social
I can't find any examples or explicit tutorials on how to use this. Can anyone help me on this please?
If you look at the source of Xamarin.Social, internally ShareItemAsync is used anyways to carry out the requests. GetShareUI is just a wrapper around ShareItemAsync.
From the source of ShareViewController (which gets the UI), you can see how they are using ShareItemAsync to carry out the requests. Here's the snippet for you.
try {
service.ShareItemAsync (item, account).ContinueWith (shareTask => {
StopSharing ();
.
.
.
.
.
}, TaskScheduler.FromCurrentSynchronizationContext ());
}
So all you need to do is create the item, get hold of the account and call the method on the service, something like this
var item = new Item { Text = "Xamarin.Social is the bomb.com." };
item.Links.Add (new Uri ("http://github.com/xamarin/xamarin.social"));
var account = facebook.GetAccountsAsync().FirstOrDefault();
facebook.ShareItemAsync(item, account);

Visit a URL with a variable altering the url, windows phone

I have a URL that is shown below:
URL is taken out due to contract reasons
WebClient webClient = new WebClient();
Uri uri = new Uri("http://www.URLhere.aspx?stopid=4556");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler
(webClient_OpenReadCompleted);
webClient.OpenReadAsync(uri);
I need to find a way to alter the end part, so change 4556 from a text block, into another text so that when the application send the request it finds the whole lot.
I thought you could do this:
WebClient webClient = new WebClient();
Uri uri = new Uri("http://www.URLhere.aspx?stopid=" + stopId);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler
(webClient_OpenReadCompleted);
webClient.OpenReadAsync(uri);
How does one do this?
Edit:
When i do the code above it returns as a null reference, so i am asuming it's not getting the text in the textbox.
It sounds like you're missing the encoding of your variable.
var myvar = "the simpsons";
Uri myUri = new Uri("http://www.URLhere.aspx?stopid=" + HttpUtility.UrlEncode(myvar));
See HttpUtility.UrlEncode Method - MSDN
there is no difference between
Uri uri = new Uri("http://www.URLhere.aspx?stopid=4556");
and
Uri uri = new Uri("http://www.URLhere.aspx?stopid=" + stopId);
so i really don't know whats your problem
Henry,
If I understand you question correctly, I think you want to append the value in a TextBox (not a TextBlock) to the URI. If that is correct and you're employing MVVM, you could bind your TextBox to a public property on the ViewModel (lets call it TextBoxProp)
private string _textBoxProp;
public string TextBoxProp
{
get{return _textBoxProp;}
set
{
_textBoxProp = value;
RaisePropertyChanged("TextBoxProp");
}
}
and then create your URI as follows:
Uri uri = new Uri(String.Format("http://www.URLhere.aspx?stopid={0}", TextBoxProp));
Be sure when you bind to the property in XAML that you set the mode to TwoWay.
I hope that helps

Create Event C# SDK Failes - Getting (OAuthException) (#324) Missing or invalid image file

I am trying to create an event using the C# SDK. I am using the code from the following blog:
http://facebooksdk.blogspot.co.uk/2011/05/facebook-create-event.html
And I am using an image that I copied from an existing event on Facebook.
I am getting however the following error:
(OAuthException) (#324) Missing or invalid image file
Does anyone have an idea how to make it work?
Many thanks!
The code is as follows:
public string CreateEvent()
{
var fb = new FacebookWebClient();
Dictionary<string, object> createEventParameters = new Dictionary<string, object>();
createEventParameters.Add("name", "My birthday party )");
createEventParameters.Add("start_time", DateTime.Now.AddDays(2).ToUniversalTime().ToString(new CultureInfo("en-US")));
createEventParameters.Add("end_time", DateTime.Now.AddDays(2).AddHours(4).ToUniversalTime().ToString(new CultureInfo("en-US")));
createEventParameters.Add("owner", "Balaji Birajdar");
createEventParameters.Add("description", " ( a long description can be used here..)");
//Add the "venue" details for the event
JsonObject venueParameters = new JsonObject();
venueParameters.Add("street", "dggdfgg");
venueParameters.Add("city", "gdfgf");
venueParameters.Add("state", "gfgdfgfg");
venueParameters.Add("zip", "gfdgdfg");
venueParameters.Add("country", "gfdgfg");
venueParameters.Add("latitude", "100.0");
venueParameters.Add("longitude", "100.0");
createEventParameters.Add("venue", venueParameters);
createEventParameters.Add("privacy", "OPEN");
createEventParameters.Add("location", "fhdhdfghgh");
//Add the event logo image
//You can add the event logo too
FacebookMediaObject logo = new FacebookMediaObject()
{
ContentType = "image/jpeg",
FileName = #"C:\DevProjects\O2\o2PriorityFB\o2PriorityFB.Web\Images\logo.jpg"
};
logo.SetValue(System.IO.File.ReadAllBytes(logo.FileName));
createEventParameters["#file.jpg"] = logo;
JsonObject resul = fb.Post("/me/events", createEventParameters) as JsonObject;
return resul["id"].ToString();
}
You need to include a valid access token in the request. Also, I would recommend upgrading to V6 of the Facebook C# SDK. For the version you are using though you need to pass the access token into the constructor of FacebookWebClient as follows:
var fb = new FacebookWebClient("valid_facebook_access_token");

Resources