button back to my app in the background and when you resume it starts again - mvvm

I am developing an app in Xamarin.Forms, before I was trying to make a master detail page to become my MainPage when I logged in to my app, this I have already achieved. Now I have the problem that when I use the button behind the phone my app is miimiza and goes to the background which is the behavior I hope, but when I return to my app does not continue showing my master detail page, but returns to my LginPage.
It is as if my app was running twice or at least there were two instances of LoginPage existing at the same time, this is because in my LoginPage I trigger some DisplayAlert according to some messages that my page is listening through the MessaginCenter and they are they shoot twice.
Can someone tell me how I can return the same to my app on the master detail page and not restart in the strange way described?
LoginView.xaml.cs:
public partial class LogonView : ContentPage
{
LogonViewModel contexto = new LogonViewModel();
public LogonView ()
{
InitializeComponent ();
BindingContext = contexto;
MessagingCenter.Subscribe<LogonViewModel>(this, "ErrorCredentials", async (sender) =>
{
await DisplayAlert("Error", "Email or password is incorrect.", "Ok");
}
);
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Unsubscribe<LogonViewModel>(this, "ErrorCredentials");
}
}
Part of my ViewModel:
if (Loged)
{
App.token = token;
Application.Current.MainPage = new RootView();
}
else
{
MessagingCenter.Send(this, "ErrorCredentials");
}
Thanks.

I hope this is in Android. All you can do is, you can override the backbuttonpressed method in MainActivity for not closing on back button pressed of the entry page. like below, you can add some conditions as well.
public override void OnBackPressed()
{
Page currentPage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();
if (currentPage != null)
{
if (currentPage.GetType().Name == "HomePage" || currentPage.GetType().Name == "LoginPage")
{
return;
}
}
base.OnBackPressed();
}

When you press the Home button, the application is paused and the
current state is saved, and finally the application is frozen in
whatever state it is. After this, when you start the app, it is
resumed from the last point it was saved with.
However, when you use the Back button, you keep traversing back in
the activity stack, closing one activity after another. in the end,
when you close the first activity that you opened, your application
exits. This is why whenever you close your application like this, it
gets restarted when you open it again.
Answer taken from this answer. The original question asks about the native Android platform, but it still applies here.

It means you have to Use Setting Plugin or save data in Application properties.
You have to add below code in App.xaml.cs file:
if (SettingClass.UserName == null)
MainPage = new LoginPage();
else
MainPage = new MasterDetailPage();
For Setting Plugin you can refer this link.

Related

Android - Custom back button (back stack)

I have implemented my own back stack but I'm not sure what is wrong or what I could improve, my scenario: I have a project with 2 activities, the first one is the "SplashActivity" - where I load some network data - the second one, the MainActivity.
Inside of my MainActivity I have a fragment and inside of this fragment a webview.
The back button should behave like:
When the user doesn't navigate inside of my webview, close the app.
When the user navigates in webview, use the back history of the browswer.
Here is my code:
#Override
public void onBackPressed() {
Log.d("lastfragment", String.valueOf(fragmentStack.lastElement().getId()));
if (fragmentStack.size() >= 2) {
// implement normal behavior?
Fragment activeFragment=fragmentStack.lastElement();
FragmentTransaction ft = getFragmentManager().beginTransaction();
activeFragment.onPause();
ft.remove(fragmentStack.pop());
Fragment returnToFragment=fragmentStack.lastElement();
String name = returnToFragment.getClass().getName();
if(name=="SplashScreen" || name=="LoginFragment"){
// close?
}
else {
// implement normal behavior?
returnToFragment.onResume();
ft.show(returnToFragment);
ft.commit();
}
}
else {
//close ??
}
}
Try to this code i hope solved this your problem.
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(FragmentTransaction.TRANSIT_FRAGMENT_OPEN, YOUR_FRAGMENT_OBJECT);
fragmentTransaction.addToBackStack(null); // Your fragment add to back stack
fragmentTransaction.commit();

TabControl avoid changing to another tab

I have a tab control with 2 tabs.. When the user clicks on the second tab, it does some validation and then if that validation returns false, the user gets a message indicating to go back. Now, here's my problem, it changes tabs anyways with the code below:
Although the user doesn't see the tab 2, it is showing as changed.
private void tabprincipal_SelectedIndexChanged(object sender, EventArgs e)
{
if (!saved_plan)
{
MessageBox.Show("You need to save a plan first.");
return;
}
How can I avoid this behavior? I want to display the message and the user to remain in the first tab
I think I'm looking for an event prior to the selectedindexchanged to detect that the user clicked tab2 and then don't let him move..
I actually found a way using the Deselecting method of the TabControl
private void tabprincipal_Deselecting(object sender, TabControlCancelEventArgs e)
{
if (!saved_plan)
{
MessageBox.Show("You need to save a plan first");
e.Cancel = true;
}
}

Preloader in Wicket Application

In a wicket application on search event it takes few secons and sometimes minutes to show the result as its a long data . I want to show a preloader while the data is fetched from the database to let the user know something is going on when they click search . I am very new to wicket application , dont understands the things very deeply but I find AjaxLazyPreloader but as I said I want to show the preloader when the search method is called ...I am sharing the SearchSubmit method ...
private void processSearchSubmit(AjaxRequestTarget ajaxRequestTarget) {
ajaxRequestTarget.add(tableHolder);
ajaxRequestTarget.add(productTableHolder);
if (zipcode == null) {
ajaxRequestTarget
.appendJavaScript("$().toastmessage('showWarningToast','Please enter a zipcode')");
} else if (!ZipCodeValidator.isValid(zipcode)) {
useZones = true;
currentZone = zipcode;
ajaxRequestTarget.add(tableHolder);
if (searchProduct != null) {
ajaxRequestTarget.add(productTableHolder);
if (lstProduct.getList().size() == 0) {
ajaxRequestTarget
.appendJavaScript("$().toastmessage('showErrorToast','Sorry! This product is not avialable .')");
}
}
} else if (lstMerchants.getList().size() == 0) {
ajaxRequestTarget
.appendJavaScript("$().toastmessage('showWarningToast','Sorry! There are currently no services')");
}
if (ZipCodeValidator.isValid(zipcode)) {
ajaxRequestTarget.add(tableHolder);
if (searchProduct != null && !searchProduct.equals("")) {
ajaxRequestTarget.add(productTableHolder);
if (lstProduct.getList().size() == 0) {
ajaxRequestTarget
.appendJavaScript("$().toastmessage('showErrorToast','Sorry! This product is not avialable in this zip code or zone.')");
}
}
}
}
I want when this method is called till the times it fetch the result data , it should show a preloader or spinner . Can anybody suggest how to do that .??
If you need to call long execution method by clicking button check this answer.
You can also use AjaxLazyLoadPanel, check this demo (it's Java part and html part)
Either use an AjaxLazyLoadPanel or an IndicatingAjaxLink/-Button. Both will work fine in either normal or Ajax calls.
To use an AjaxLazyLoadPanel: create a subclass of AjaxLazyLoadPanel which loads the panel you want to display and add it to the AjaxRequest.
IndicatingAjaxLinks just display a spinner while the request is being processed and can be used straightforward in your current application. Use this instead of the button/link you use for formsubmits now.

WP: What callback to be used when page is loaded from app launching

Inside MainpPage.xaml.cs, what callback can be used so that I know it is coming from launching the App but not coming from other page? I know that there is Application_Launching in App.xaml.cs. But if I place below code there, exception is thrown somewhere. If I put in Loaded callback, I can't distinguish if it is called from App launching from navigated from other page.
if (MediaPlayer.State == MediaState.Playing)
{
MediaPlayer.Pause();
}
I would like to stop any existing playing music after entering my app.
Thanks
In you App.xaml:
public void TryStopAllMusic()
{
if (MediaPlayer!=null && MediaPlayer.GameHasControl)
{
MediaPlayer.Stop(); //stop to clear any existing music
}
}
In the constructor, under InitializeComponent() of your MainPage.xaml.cs:
public MainPage()
{
InitializeComponent();
(Application.Current as App).TryStopAllMusic();
}
That's all.

.Net CF Prevent Overzealous, Impatient Clicking (while screen is redrawing)

.Net Compact Framework
Scenario: User is on a screen. Device can't finds a printer and asks the user if they want to try again. If they click "No", the current screen is closed and they are returned to the parent menu screen. If they click the "No" button multiple times, the first click will be used by the No button and the next click will take effect once the screen has completed redrawing. (In effect clicking a menu item which then takes the user to another screen.)
I don't see a good place to put a wait cursor...there isn't much happening when the user clicks "No" except a form closing. But the CF framework is slow to redraw the screen.
Any ideas?
you can skip pending clicks by clearing the windows message queue with
Application.DoEvents();
We use the following custom Event class to solve your problem (preventing multiple clicks and showing a wait cursor if necessary):
using System;
using System.Windows.Forms;
public sealed class Event {
bool forwarding;
public event EventHandler Action;
void Forward (object o, EventArgs a) {
if ((Action != null) && (!forwarding)) {
forwarding = true;
Cursor cursor = Cursor.Current;
try {
Cursor.Current = Cursors.WaitCursor;
Action(o, a);
} finally {
Cursor.Current = cursor;
Application.DoEvents();
forwarding = false;
}
}
}
public EventHandler Handler {
get {
return new EventHandler(Forward);
}
}
}
You can verify that it works with the following example (Console outputs click only if HandleClick has terminated):
using System;
using System.Threading;
using System.Windows.Forms;
class Program {
static void HandleClick (object o, EventArgs a) {
Console.WriteLine("Click");
Thread.Sleep(1000);
}
static void Main () {
Form f = new Form();
Button b = new Button();
//b.Click += new EventHandler(HandleClick);
Event e = new Event();
e.Action += new EventHandler(HandleClick);
b.Click += e.Handler;
f.Controls.Add(b);
Application.Run(f);
}
}
To reproduce your problem change the above code as follows (Console outputs all clicks, with a delay):
b.Click += new EventHandler(HandleClick);
//Event e = new Event();
//e.Action += new EventHandler(HandleClick);
//b.Click += e.Handler;
The Event class can be used for every control exposing EventHandler events (Button, MenuItem, ListView, ...).
Regards,
tamberg
Random thoughts:
Disable the some of the controls on the parent dialog while a modal dialog is up. I do not believe that you can disable the entire form since it is the parent of the modal dialog.
Alternatively I would suggest using a Transparent control to catch the clicks but transparency is not supported on CF.
How many controls are on the parent dialog? I have not found CF.Net that slow in updating. Is there any chance that the dialog is overloaded and could be custom drawn faster that with sub controls?
override the DialogResult property and the Dispose method of the class to handle adding/remvoing a wait cursor.