I have a problem that I can't really figure out, and I am really desperate now - I've no idea why it's happening:(
So here is the problem: I am writing a kind of Guess that Tune app. The first page is a menu page, that a user can press "Play" button, and he will navigate to a GenreSelectPage where he selects a genre and navigates to a GamePage. I wanted to handle BackButtonPress on GamePage - when a user hits BackButton, he navigates to MainPage, not GenreSelectPage. Here is the code:
private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
{
base.OnBackKeyPress(e);
this.player.Pause();
var result = MessageBox.Show(AppResources.GamePageAlert, "Warning", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
//NavigationService.RemoveBackEntry();
//App.RootFrame.Navigate(new Uri(#"/MainPage.xaml", UriKind.Relative));
}
else
{
this.player.Play();
e.Cancel = true;
}
}
However, I encoountered a big problem here I can't really solve. When I move back to MainMEnu, than go again to GenreSelectPage and choose the same genre, everything is ok - the app navigates to GamePage where there is list of 4 answers. However, if I choose another genre, the listBox at GamePage is populated with 12 or 15 items. On the other hand, when I comment navigation to MainPage and normally go back, everything works alright.
Here is my GenrePage Code:
public GenresPage()
{
InitializeComponent();
this.DataContext = App.ViewModel.GenreHelper;
}
private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
this.genresListBox.SelectedIndex = -1;
this.progressBar.Visibility = System.Windows.Visibility.Visible;
this.genresListBox.ItemsSource = await App.ViewModel.GenreHelper.GetGenres();
this.progressBar.Visibility = System.Windows.Visibility.Collapsed;
ClearCollections();
}
private static void ClearCollections()
{
if (App.ViewModel.TracksCollection.Count != 0)
{
App.ViewModel.TracksCollection.Clear();
App.ViewModel.TrackCounter = 0;
}
if (App.ViewModel.AnswerCollection.Count > 0)
{
App.ViewModel.AnswerCollection.Clear();
}
}
private async void NavigateToPlay(object sender, RoutedEventArgs e)
{
if (this.genresListBox.SelectedIndex != -1)
{
this.progressBar.Visibility = System.Windows.Visibility.Visible;
await App.ViewModel.GetSongs();
await App.ViewModel.GetAnswers();
this.progressBar.Visibility = System.Windows.Visibility.Collapsed;
NavigationService.Navigate(new Uri(#"/Views/GamePage.xaml", UriKind.Relative));
}
}
UPDATE
On my GamePage I am only assigning DataContext and duration to MediaElement:
public partial class GamePage : PhoneApplicationPage
{
public GamePage()
{
InitializeComponent();
this.DataContext = App.ViewModel;
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var trackId = App.ViewModel.TracksCollection[App.ViewModel.TrackCounter].Id;
var sampleUri = App.ViewModel.GetSampleUri(trackId);
player.Source = new Uri(sampleUri.AbsoluteUri);
player.Play();
}
private void GetTrackDuration(object sender, RoutedEventArgs e)
{
var player = (MediaElement)sender;
if (player.CurrentState == System.Windows.Media.MediaElementState.Playing)
{
playerSeekBar.Maximum = player.NaturalDuration.TimeSpan.TotalSeconds;
}
}
private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
{
base.OnBackKeyPress(e);
this.player.Pause();
var result = MessageBox.Show(AppResources.GamePageAlert, "Warning", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
//NavigationService.RemoveBackEntry();
//App.RootFrame.Navigate(new Uri(#"/MainPage.xaml", UriKind.Relative));
}
else
{
this.player.Play();
e.Cancel = true;
}
}
}
If anyone can point out what I am doing wrong, I would be really greatful - I am fighting it all day and I have no idea what's causing it.
Thank You very much in advance!!
Related
Good evening everyone
I'm trying to pass two objects at the same screen over the error to pass the second. I would like to know how to treat this receipt on my main screen.
I will try to give an example below:
first send an object parameter for the screen client
private void btTelaPedido (object sender, TappedRoutedEventArgs e) {
Customer customer = new Customer ();
customer.custid = Convert.ToInt32 (tbCodCliente.Text);
cliente.razao = tbNomeCliente.Text;
Frame.Navigate (typeof (pedidoTelaCadastro), client);
}
then go to another screen and send another object
private void listaProduto_SelectionChanged (object sender, SelectionChangedEventArgs e) {
Product produtoEscolhido = (sender the ListView) .SelectedItem the product;
Frame.Navigate (typeof (pedidoTelaCadastro), produtoEscolhido);
}
and that is, to receive code on the main screen.
protected override void OnNavigatedTo (NavigationEventArgs e) {
this.navigationHelper.OnNavigatedTo (e);
ClienteRecebido customer = (customer) e.Parameter;
tbIdCliente.Text = Convert.ToString (clienteRecebido.idCliente);
tbCliente.Text = clienteRecebido.razao;
tbDataPedido.Text = "01/01/2015";
ProdutoRecebido product = (Product) e.Parameter;
tbProduto.Text = Convert.ToString (produtoRecebido.descricao);
}
I wonder how he treats
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.navigationHelper.OnNavigatedTo(e);
Customer clienteRecebido = e.Parameter as Customer;
if(clienteRecebido !=null)
{
tbIdCliente.Text = Convert.ToString (clienteRecebido.idCliente);
tbCliente.Text = clienteRecebido.razao;
tbDataPedido.Text = "01/01/2015";
}
else
{
ProdutoRecebido product = (Product) e.Parameter;
tbProduto.Text = Convert.ToString (produtoRecebido.descricao);
}
}
Im working with windows phone 8.1 geolocation. The problem that I currently have is that my code only shows the first numbers of my coordinate. Example: If the coordinate is "41.233" the app only shows "41.00" . I need it to be as accurate as possible. In case it matters, im using windows phone 8.1 emulator to try the app, not an actual phone.
My code:
public sealed partial class MainPage : Page
{
bool shouldSend = false;
DispatcherTimer timer = new DispatcherTimer();
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
private async Task GetLocation()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High;
try
{
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromSeconds(1),
timeout: TimeSpan.FromSeconds(10)
);
LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
LatLonTxt.Text = LatitudeTxt.Text + ", " + LongitudeTxt.Text;
var speed = geoposition.Coordinate.Speed.ToString();
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
string result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
"http://proyecto-busways.rhcloud.com/colectivos?p=lta123&l=80&d=moyano&lat=" + LatitudeTxt.Text + "&lon=" + LongitudeTxt.Text + "&v=" + speed + "&Accion=Agregar");
request.ContinueTimeout = 4000;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
if (response.StatusCode == HttpStatusCode.OK)
{
//To obtain response body
using (Stream streamResponse = response.GetResponseStream())
{
using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8))
{
result = streamRead.ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
if ((uint)ex.HResult == 0x80004004)
{
// the application does not have the right capability or the location master switch is off
}
//else
{
// something else happened acquring the location
}
}
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
private async void StartSending_Click(object sender, RoutedEventArgs e)
{
await GetLocation();
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
StartSending.IsEnabled = false;
}
async void timer_Tick(object sender, object e)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Visible;
await GetLocation();
}
private void EndSending_Click(object sender, RoutedEventArgs e)
{
timer.Tick -= timer_Tick;
timer.Stop();
StartSending.IsEnabled = true;
EndSending.IsEnabled = false;
}
private void GPS_Tapped(object sender, TappedRoutedEventArgs e)
{
Frame.Navigate(typeof(ContactPage));
}
}
Thanks for your help!
Did you try out the Geolocator.DesiredAccuracyInMeters property?
geolocator.DesiredAccuracyInMeters = 3;
Reference & Sample
In this point LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
You indicated that you have 0.00 decimals, for more accuracy you should put 0.000000
I create a toggle button and its working fine . But problem is that how can i Keep previous toggle activity, I mean when application is exit and reopen, it should display the previous toggle state . Here is my code
XAML:
<toolkit:ToggleSwitch x:Name="toggle" Content="ToggleSwitch is on" Header="ToggleSwitch"/>
CS :
public partial class EnglishSub : PhoneApplicationPage
{
public BanglaSub()
{
InitializeComponent();
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
this.toggle.Content = "ToggleSwitch is off";
}
void toggle_Unchecked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "ToggleSwitch is off";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Red);
MessageBox.Show("Disable");
}
void toggle_Checked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "ToggleSwitch is on";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Green);
MessageBox.Show("Enable");
}
}
You can use IsolatedStorageSetings to store application data. and read it when your app page is loaded again. here is how
public bool GetToggleValue()
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("toggleValue"))
{
return bool.Parse(IsolatedStorageSettings.ApplicationSettings["toggleValue"].ToString());
}
else return false;
}
call above method in your page load to set the toggle value
and set checked unchecked value in the settings in your checked unchecked event handlers here is how
IsolatedStorageSettings.ApplicationSettings.Add("toggleValue", true);
IsolatedStorageSettings.Save();
This is the function I used to get the string content from the website ..the problem is when executed first I cannot get the string content (App.Data2 = userprofile.InnerText;) since it skips to the next line (App.savecontent(App.Data2);) so that I get an empty string. If I recall the function I could get the string. Is there any possibility to solve this issue I need the string value first time automatically
This is my Page.cs code :
namespace Project_Future1
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
{
string url = "http://www.astrosage.com/horoscope/daily-";
HtmlWeb.LoadAsync(url + App.Data + "-horoscope.asp", DownLoad);
}
data();
App.loadContent();
change2();
}
public void change2()
{
try
{
Util.LiveTile.UpdateLiveTile(App.Data2);
}
catch (Exception)
{
}
}
public void DownLoad(object sender, HtmlDocumentLoadCompleted e)
{
if (e.Error == null)
{
HtmlDocument doc = e.Document;
if (doc != null)
{
var userprofile = doc.DocumentNode.SelectSingleNode("//div[#class = 'ui-large-content']");
App.Data2 = userprofile.InnerText;
App.savecontent(App.Data2);
}
}
}
private void data()
{
SelectedSign.Text = App.Data;
SSContent.Text = App.Data2;
}
private void Refresh_click(object sender, EventArgs e)
{
SSContent.Text = App.Data2;
}
private void Fb_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/FB.xaml", UriKind.Relative));
}
}
}
this is my App.Xaml.cs File :
public static void savecontent(string save)
{
try
{
if (!string.IsNullOrEmpty(appFileName1))
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
oIsolatedStorage.CreateDirectory(appFolder1);
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(appFolder1 + "\\" + appFileName1, FileMode.OpenOrCreate, oIsolatedStorage));
writeFile.WriteLine(save);
writeFile.Close();
}
}
catch (Exception)
{
throw;
}
}
this is my code to load the content from the storage :
public static void loadContent()
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (oIsolatedStorage.DirectoryExists(appFolder1))
{
IsolatedStorageFileStream fileStream = oIsolatedStorage.OpenFile(appFolder1 + "\\" + appFileName1, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
App.Data2 = reader.ReadLine();
reader.Close();
}
}
}
I have a countdown timer and I want an alarm to go off when it reaches the end ... lots for Android and iOS, but nothing that I could find for WP8.
I'm using the DispatcherTimer for counting down.
I'm looking for some information or an example on how to call a sound when the timer finishes counting down. I have the counter start on a button click and reset on a long press. It all works good, just want a sound effect when it stops after counting down.
private DateTime EndTime { get; set; }
private DispatcherTimer _dispatcherTimer;
private void BtnCounter_Click(object sender, RoutedEventArgs e)
{
if (this._dispatcherTimer == null)
{
this._dispatcherTimer = new DispatcherTimer();
this._dispatcherTimer.Interval = TimeSpan.FromMilliseconds(100);
this._dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
}
if (this.EndTime == DateTime.MinValue)
{
this.EndTime = DateTime.Now + (TimeSpan)this.tsPicker.Value;
}
this._dispatcherTimer.Start();
}
void dispatcherTimer_Tick(object sender, EventArgs e)
{
var remaining = this.EndTime - DateTime.Now;
int remainingSeconds = (int)remaining.TotalSeconds;
this.tsPicker.Value = TimeSpan.FromSeconds(remainingSeconds);
if (remaining.TotalSeconds <= 0)
{
this._dispatcherTimer.Stop();
// Sound code should go here, or a method call to it.
}
}
private void BtnCounter_Hold(object sender, System.Windows.Input.GestureEventArgs e)
{
cnt = 0;
BtnCounter.Content = cnt;
this._dispatcherTimer.Stop();
this.EndTime = DateTime.MinValue;
this.tsPicker.Value = TimeSpan.FromSeconds(0);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
this.EndTime = DateTime.MinValue;
base.OnNavigatedFrom(e);
}
Have you tried using a MediaElement? There seems to be a good example using it, titled Windows Phone 8: Playing Sounds