first time opening the app can't change page [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
The instruction this.Frame.Navigate(typeof(RegionPage)); on my mainpage doesn't work. It generates an exception:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
So I tried putting it in some function after the mainpage and all goes fine.
My objective: I want to make a control such that, if is it the first time that the user opens the app, it will display a new page with tutorial.
Question: how can I work around that problem?
public MainPage()
{
this.InitializeComponent();
Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;
this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
TextBoxRicerca.Visibility = Visibility.Collapsed;
Mappe.Loaded += Mappe_Loaded;
Regione.RegNome = "";
this.Frame.Navigate(typeof(RegionPage));
}

Due to your app is preparing some components for launching the so you need to give some time to your app to load components.
So you need to give some delay like this--
using System.Threading.Tasks;
public MainPage()
{
this.InitializeComponent();
Loaded += async (s, e) =>
{
await Task.Delay(100);
Frame.Navigate(typeof(RegionPage));
};
}
you can adjust delay accordingly.
Demo-
Alternate Way-
And Full Solution for first time launch of your so it should show some specific page or tutorial page, you can edit your App.xaml.cs in OnLaunched event
using Windows.Storage;
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
IPropertySet roamingProperties = ApplicationData.Current.RoamingSettings.Values;
if (roamingProperties.ContainsKey("FirstTimePage"))
{
// regular visit
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
else
{
// first time visit
rootFrame.Navigate(typeof(RegionPage), e.Arguments);
roamingProperties["FirstTimePage"] = bool.TrueString;
}
}
// Ensure the current window is active
Window.Current.Activate();
}

I don't like to use the delay, and editing App.xaml.cs in OnLaunched event was too difficult.
So I made a mix and put a "Loaded += Loading;" on the main and created.
public MainPage()
{
this.InitializeComponent();
Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;
this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
TextBoxRicerca.Visibility = Visibility.Collapsed;
Mappe.Loaded += Mappe_Loaded;
Regione.RegNome = "";
**Loaded += Loading;**
//this.Frame.Navigate(typeof(RegionPage));
}
I created the function:
private void Loading(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(RegionPage));
}
It's only giving me a message that I should add a "new" somewhere don't know where and don't know why, but works.

Related

Could not create a new view because the main window has not yet been created

I'm having a problem with my app during the start up. I'm getting at exception that says
A method was called at an unexpected time. Could not create a
new view because the main window has not yet been created
First I display a splash screen so I can get some data from the internet in the background. My splash screen works fine and I implemented it correctly as indicated in the documentation.
In App.xaml.ca I have some standard code for splash screen
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
...
if (e.PreviousExecutionState != ApplicationExecutionState.Running)
{
bool loadState = (e.PreviousExecutionState == ApplicationExecutionState.Terminated);
ExtendedSplash extendedSplash = new ExtendedSplash(e.SplashScreen, loadState);
Window.Current.Content = extendedSplash;
}
...
Window.Current.Activate();
}
Then in my App constructor I have this
public static Notifications notifications;
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
SomeClass.RunTasks(); //acquire data from a REST service
//initializing the object for subscribing to push notification, not sure if this is the best place to put this.
App.notifications = new Notifications("hubname", "myEndpoint");
}
The exception occurs inside my RunTasks() method which looks like this
public class SomeClass
{
GetHTTPResponse _aggregateData = new GetHTTPResponse("http://someRestService");
public async void RunTasks()
{
try
{
HttpResponseMessage aggregateData = await _aggregateData.AcquireResponse();
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
//do a bunch of stuff with the data
//NOTE: I am making updates to my ViewModel here with the data I acquired
//for example App.ViewModel.Time = somevalue
//when finished dismiss the splash screen
ExtendedSplash.Instance.DismissExtendedSplash();
}
);
}
catch (System.Exception ex)
{
}
}
}
Any ideas how I can improve this and eliminate the error?
Could it have something to do with me updating my ViewModel items (which are data bound to UI components)?
EDIT when I remove the creation of my notifications object from App.cs constructor (and move it into the RunTasks() method, the error goes away.
App.notifications = new Notifications("hubname", "myEndpoint");
The reason you get the exception is because Windows.ApplicationModel.Core.CoreApplication.MainView is not valid in your application's constructor as the main view has not been created yet.
You can access it once you have received the Application.OnLaunched/OnActivated event.
Thanks!
Stefan Wick -
Windows Developer Platform

Using C# & Xamarin Forms - How can I close one modal without setting of chain of closures

In one stage of my app (Android & iOS are the ones we care about) we've got three pages which take in details and then open a webView for the user to input their card details to take a payment - this can't be done in the app due to Apple's guidelines.
I need to format the navigation in a way that when the user has finished in the webView it closes and then closes the 3 previous modals to get back to the original page. I've got it all working with the Appearing event so each page just closes itself:
this.Appearing += async (s, e) =>
{
await Navigation.PopModalAsync();
};
The issue I'm now having is that when the user presses the back button on the phone, it closes all of the pages that they've been through already & back to the original. I thought about implementing a custom nav bar and disabling the back button on the hardware but this would cause the same problem with the Appearing event.
Is there any easy way to solve this?
EDIT: Relevant code;
async void OnButtonClicked(object sender, EventArgs eventArgs)
{
if (IsConnected)
{
ActivityIndicator.IsVisible = true;
var button = (Button) sender;
button .IsEnabled = false;
await Navigation.PushModalAsync(new Page());
this.Appearing += (s, e) =>
{
ActivityIndicator.IsVisible = false;
button.IsEnabled = true;
RefreshPage();
};
}
else
{
NoInternetLabel.IsVisible = true;
}
}
Use this:
YourButton.Clicked += OpenPage;
OpenPage looks like this:
async public void OpenPage(object sender, EventArgs args)
{
await Navigation.PushAsync(new PageToShow());
}
You don't have to do anything to handle the PageToShow() closing, that happens by itself when the user presses the back button.
Managed to solve this by using Actions. In each new Page() we passed up an async method to close it once the one after had completed;
var nextPage = new Page(async () =>
{
await Navigation.PopModalAsync();
_completedSuccessfully();
});
await Navigation.PushModalAsync(nextPage);
And in the new page class;
private readonly Action _completedSuccessfully;
public Page(Action completedSuccessfully)
{
_completedSuccessfully = completedSuccessfully;
}
This meant that when the webView closed it called the completedSuccessfully() action and then chained all of them to the original page.

call method when phone is shaken [duplicate]

This question already has answers here:
Is there an easy way to detect shake motions on Windows Phone 8?
(3 answers)
Closed 8 years ago.
I have created a windows phone app that locates a users location when a button is pressed but I want to do away with the button and make this function occur when the phone is shaken! Below is the code that I have created so far, when the application loads it will call a function called Locate_Me which initializes the Accelerometer.
private async void Locate_Me()
{
if (accelerometer == null)
{
// Instantiate the Accelerometer.
accelerometer = new Accelerometer();
accelerometer.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
accelerometer.CurrentValueChanged +=
new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(accelerometer_CurrentValueChanged);
}
try
{
statusTextBlock.Text = "starting accelerometer.";
accelerometer.Start();
}
catch (InvalidOperationException ex)
{
statusTextBlock.Text = "unable to start accelerometer.";
}
}
So how would I go about making the onShaken function?
First step: Download ShakeGestures library from microsoft site here. Add ShakeGetures.dll to your project.
Now it's a piece of cake for you to detect shake gestures. Below is the code you can use:
//constructor of page register event handler for shake
public Page1()
{
InitializeComponent();
// register shake event
ShakeGesturesHelper.Instance.ShakeGesture +=new
EventHandler<ShakeGestureEventArgs>(Instance_ShakeGesture);
// optional, set parameters
ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 2;
// start shake detection
ShakeGesturesHelper.Instance.Active = true;
}
private void Instance_ShakeGesture(object sender, ShakeGestureEventArgs e)
{
//call your method
}
This is the minimal code you would require. Worked for me.

How to set start page in windows phone 8 app programmatically?

I want to set a start page in my windows phone 8 app programmatically after checking some data in config. Which event I can use to do the same?
Thanx in advance.
I used Application_Launching for same task. Something like this:
private void Application_Launching(object sender, LaunchingEventArgs e)
{
RootFrame.Navigated += RootFrame_Navigated;
var logined = Singleton.Instance.User.Load();
var navigatingUri = logined ? "/View/PageMainPanorama.xaml" : "/View/Account/PageLoginRegister.xaml";
((App)Current).RootFrame.Navigate(new Uri(navigatingUri, UriKind.Relative));
}
The first step is to remove the default page that us set by default in the manifest file (WMAppManifest.xml) in apps created from the standard templates.
Simply remove NavigationPage="MainPage.xaml" from the code below.
<Tasks>
<DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
</Tasks>
The start page is specified in InitializePhoneApplication() by calling RootFrame.Navigate() (in App.xaml.cs) .Like example below
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Handle reset requests for clearing the backstack
RootFrame.Navigated += CheckForResetNavigation;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
Uri uri;
if (IsolatedStorageSettings.ApplicationSettings.Contains("islogin"))
{
if (!(Convert.ToString(IsolatedStorageSettings.ApplicationSettings["islogin"]).ToLower() == "yes"))
{
RootFrame.Navigate(new Uri("/LoginScreen.xaml", UriKind.RelativeOrAbsolute));
}
else
{
RootFrame.Navigate(new Uri("/HomeScreen.xaml", UriKind.RelativeOrAbsolute));
}
}
else
{
RootFrame.Navigate(new Uri("/LoginScreen.xaml", UriKind.RelativeOrAbsolute));
}
}
Here you can find a blog entry that describes the dynamic setting of a start page.
http://blogs.msdn.com/b/ptorr/archive/2010/08/28/redirecting-an-initial-navigation.aspx?wa=wsignin1.0

How to navigate to a new page from within a OnFrameNavigated handler

I am porting a Windows Phone 8 app to Windows Store 8.1 and I am having some trouble with navigating to a new page when Frame.Navigate(...) is called from within a OnFrameNavigated handler.
The long story:
The App manages different "Media" objects like Books or Films. To edit the properties (title, author, etc.) of such an element the WP uses a custom "MediaEditor" control that was inspired by the DatePicker from the WP ToolKit:
Instead of manually navigating to an Editor/Picker page the Editor/Picker is capsuled in its own class. This class hooks up to the ApplicationFrame and handles Navigation to the Editor/Picker page on its own. When the ApplicationFrame navigates back to the page/content that was visible before showing the Editor/Picker the result can be processed, e.g. fire an event with the picked date.
There is one difference in my MediaEditor compared to the DatePicker:
If the MediaItem that is currently edited is related to another MediaItem (e.g. Movie A is the film version of Book A) the editing of this item can directly been started from within the MediaEditor:
call mediaEditor.Edit(MovieA) --> MediaEditor for MovieA is displayed
Select to Edit BookA from within MediaEditor --> MediaEditor for MovieA is closed and MediaEditor for BoolB is displayed
This is done by calling Edit(BookA) from within OnFrameNavigated. Thus the complete Navigation is:
call mediaEditor.Edit(MovieA) --> Frame.Navigate(typeof(MediaEditorPage), MovieA)
Select to Edit BookA --> Frame.GoBack()
Detect that BookA should be edited in OnFrameNavigated --> Frame.Navigate(typeof(MediaEditorPage), BookA)
While this works on Windows Phone this does not work on Win 8.1. Frame.Navigate(typeof(MediaEditorPage), BookA) is simply ignored. There is no OnNavigationFailed, no console output, nothing. The App navigates back to the first page (the one that original called mediaEditor.Edit(MovieA)) and nothing else happens.
What exactly is the problem here?
MediaEditor mediaEditor = new MediaEditor();
mediaEditor.Edit(bookItem);
public class MediaEditor {
private Frame applicationFrame;
private object frameContentWhenOpened;
public void Edit(MediaItem item) {
applicationFrame = Window.Current.Content as Frame;
if (applicationFrame != null) {
frameContentWhenOpened = applicationFrame.Content;
applicationFrame.Navigated += OnFrameNavigated;
applicationFrame.NavigationFailed += OnNavigationFailed;
applicationFrame.Navigate(typeof(MediaEditorPage), item);
}
}
void OnNavigationFailed(object sender, NavigationFailedEventArgs e) {
System.Diagnostics.Debug.WriteLine(e);
}
MediaEditorPage editorPage;
void OnFrameNavigated(object sender, NavigationFailedEventArgs e) {
if (e.Content == frameContentWhenOpened) {
applicationFrame.Navigated -= OnFrameNavigated;
applicationFrame.NavigationFailed -= OnNavigationFailed;
applicationFrame = null;
frameContentWhenOpened = null;
if (editorPage != null) {
if (editorPage.EditOtherItem)
// Directly start editing another Item
Edit(editorPage.OtherItem);
else
// Finish editing, fire Events, etc
}
} else {
editorPage = e.Content as MediaEditorPage ;
}
}
}

Categories

Resources