Windows phone 7: facing issue for passing parameters - windows-phone-7

Right now i am developing a Windows phone app, yes this is my first windows app. Right now i am facing an issue, don't know what's the silly mistake i made. Yes of course i have done debugging.
Now, what exactly i am doing?
Passing data from 1st page to 2nd page,
On the page, catching data inside onNavigateTo() method, yes i am receiving it correctly.
Based on the parameter/data (i.e. ID) i got, i am making web service call.
Problem:
If i move to the 3rd page from 2page and again came back to the 2nd page, its again making web call. i.e. calling DownloadStringAsync again in below code.
i.e. If 2nd page is having ListBox with 5 data, now clicking on particular item i am moving to 3rd page, if i came back to 2nd page from page 3, items get doubled i.e. 10 items (just because its making call again)
Here is the possible code for the reference:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
type = Convert.ToInt32(NavigationContext.QueryString["Type"]);
if (type != 0)
{
if (NetworkInterface.GetIsNetworkAvailable())
{
client.DownloadStringAsync(new Uri(Utils.Constant.WebService_URL));
}
else
{
MessageBox.Show("Please check internet connection!!");
}
}
}

Can't you use the following code to test if the user used the back button?
e.NavigationMode == System.Windows.Navigation.NavigationMode.Back

sometimes this method(QueryString) create problems.
In back event it create problems
its betters to store the id(parameter) in isolatedstorage application key
IsolatedStorageSettings.ApplicationSettings["id"] = "your data";

OnNavigatedTo is called whenever you navigate to the page, either by a forward navigation, or a back navigation. That's why it's retriggered when you navigate back from page #3 to page #2.
You can avoid this by only triggering the network call on a forward navigation.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (this.isInitialized) return;
type = Convert.ToInt32(NavigationContext.QueryString["Type"]);
if (type != 0)
{
if (NetworkInterface.GetIsNetworkAvailable())
{
client.DownloadStringAsync(new Uri(Utils.Constant.WebService_URL));
}
else
{
MessageBox.Show("Please check internet connection!!");
}
}
this.isInitialized = true;
}
Beware that NetworkInterface.GetIsNetworkAvailable can block (in this case the UI thread) for a long time in some scenarios, to work around this you can use network detection events.

Related

Get EditText data on swipe to next Fragment

I have three fragments in a view pager:
A -> B -> C
I would like to get the strings of my two edittexts in Fragment A on swipe to Fragment B to show them in Fragment B. The edittext data may be changed up until the swipe.
Someone has suggested listening for typing and sending data after each one, but the callbacks I know for that change state EVERY key click (which can be expensive). How do I this without using buttons, since their right next to each other, for a more delightful experience?
You can check the data of the EditText on swipe ; if it's not null, then you can send it to any other fragment using Bundle since you are dealing with fragments
With help from #I. Leonard I found a solution here.
It was deprecated so I used the newer version. I put the below code in my fragment class because I needed access to the data without complicating things. It works like a charm!
On the page listener callback, I suggest, calling an interface for inter-fragment communication to do your actions on your home activity or to call the appropriate fragment that can do the work, from the activity.
// set content to next page on scroll start
vPager = (ViewPager) getActivity().findViewById(R.id.viewpager);
vPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_SETTLING) {
// ViewPager is slowing down to settle on a page
if (vPager.getCurrentItem() == 1) {
// The page to be settled on is the second (Preview) page
if (!areFieldsNull(boxOne.getText().toString(), boxTwo.getText().toString()))
// call interface method in view pager activity using interface reference
communicator.preview(boxOne.getText().toString(), boxTwo.getText().toString());
}
}
}
});

GWT: React to a click on a SafeHTML in a cell of a CellTable?

I am using a CellTable to display results of a query and I need these results to be shown as (html) links. I would like to react to a click on these links. So far, I had implemented it like this:
// ClickHandler on CellTable
cellTable.addCellPreviewHandler(new Handler<OperationalItemMultipleSearchRowData>() {
#Override
public void onCellPreview(CellPreviewEvent<OperationalItemMultipleSearchRowData> event) {
boolean isClick = "click".equals(event.getNativeEvent().getType());
if (isClick)
AdminUtils.EVENT_BUS.fireEvent(new SimpleSearchEvent(event.getValue().getName()));
}
});
The Problem is that this reacted to a Click on the whole row instead of the link. Due to architectural restrictions, the link itself is not a real html link, but a SafeHtml link that leads nowhere. I just needed the look&feel of a Link:
Column<OperationalItemMultipleSearchRowData, SafeHtml> nameColumn = new Column<OperationalItemMultipleSearchRowData, SafeHtml>(new SafeHtmlCell()) {
#Override
public SafeHtml getValue(final OperationalItemMultipleSearchRowData object) {
return new SafeHtml() {
#Override
public String asString() {
return "" + object.getName() + "";
}
};
}
};
How can I react to a click on this link only ? (instead of the whoel row)
Is there a more elegant way to implement this ?
Cheers
As with any other use of event delegation, the basic idea is to find walk up the hierarchy starting from the target of the event up until you find the link element you're looking for, or some other element that signals the search is over and the click was targetted outside the link (e.g. you reached the cell, the row or the table).
That being said, I think you should merge your behavior inside a specific Cell implementation rather than using a CellPreviewHandler (copy/paste the ActionCell or TextButtonCell as a starting point).
As a side note, I also believe you should not use a link when you're not actually linking anywhere, or try to provide a target for the link if the behavior is the one of a link (that way, right-clicking, middle-clicking or ctrl-clicking will Just Work™). If you want the look of a link (without the "feel"), then just use an ActionCell or TextButtonCell and style it accordingly.

How do I handle double click on a GWT web application running on a touch device?

I have built a GWT (2.5) web application that, among other things, uses a DataGrid. I have used addDomHandler to add a DoubleClickEvent to select a row and perform an action, and it works great on the desktop. However, when I run the web application on a touch device, the double click zooms the screen instead. Is there are proper way to handle that? I would prefer to override the default behavior of zooming, but I have no idea where to begin. I suppose a long press might be more appropriate, but I have no idea where to begin with that either.
The code:
_dataGrid.addDomHandler(new DoubleClickHandler() {
#Override
public void onDoubleClick(DoubleClickEvent event) {
// Do something exciting here!
}
}, DoubleClickEvent.getType());
The only idea I have it that stopping the propagation of the DOM event may prevent the default zoom behavior.
Although I'd be curious is it registers as a double-click event at all on a touchscreen device. Would be worth trying just putting the handler on Root and seeing if you can even catch the event.
Also try this: just have your application catch -any- DOM event and simply write the name out somehow. That way you, should find out what event is triggering (might be one for long touch!) and can write a handler for that.
OK, I found a solution, but it's probably pretty unique to my situation. What I did was keep the double click handler and I also implemented a slow double click. In other words, if you select the same row of the DataGrid twice in sequence, no matter how fast you do it, then the application interprets that as a double click. Here is the code:
result.addDomHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Scheduler.get().scheduleDeferred(new Command() {
public void execute () {
if (result.isDoubleTap()) {
// Do the same thing a a double click.
}
}
});
}});
I had a problem with the click handler being fired before the selection change handler, so I had to defer the processing of the click event with the Scheduler. The "result" is a Composite that contains the DataGrid and some other stuff, and in each "result" I store the last selected item in a private variable. Then in IsDoubleTap() all I do is see if the current selection is the same as the last one:
public boolean isDoubleTap() {
boolean result = false;
String selected = getSelected();
if (_lastSelect != null && selected != null && selected.equals(_lastSelect))
result = true;
_lastSelect = selected;
return result;
}
So effectively if you do a normal double click or a slow double click you get the same action. I'm just glad that while I use this result object many places, it is the only place that I use a double click. And I would REALLY like to have a conversion with the committee that decided overriding standard double click behavior with a touch device was a GOOD thing.

ViewModels and IsolatedStorageSettings

Im working on a MVVM Windows phone app that displays weather info.
When the app loads up it opens MainPage.xaml. It makes a call the the service to get weather info and binds that data to the UI. Both Fahrenheit and Celcius info are returned but only one is displayed.
On the setting page, the user can select to view the temp in either Fahrenheit or Celcius.
The user can change this setting at any time and its stored in IsolatedStorageSettings.
The issue Im having is this:
when the user navigates to the Settings page and changes their preference for either Fahrenheit or Celcius, this change is not reflected on the main page.
This issue started me thinking about this in a broader context. I can see this being an issue in ANY MVVM app where the display depends on some setting in IsolatedStorage. Any time any setting in the IsoStore is updated, how does the ViewModels know this? When I navigate back in the NavigationStack from the settings page back to MainPage how can I force a rebind of the page?
The data in my model hasnt changed, only the data that I want to display has changed.
Am I missing something simple here?
Thanks in advance.
Alex
Probably you have code like this:
public double DisplayTemperature
{
get { return (IsCelsium) ? Celsium : Fahrenheit; }
}
And IsCelsium is:
public double IsCelsium
{
get { return (bool)settings["IsCelsium"]; }
set { settings["IsCelsium"] = value; }
}
So you need to add NotifyPropertyChanged event to notify UI to get new values from DisplayTemperature property:
public double IsCelsium
{
get { return (bool)settings["IsCelsium"]; }
set
{
settings["IsCelsium"] = value;
NotifyPropertyChanged("DisplayTemperature");
}
}
Take a look at Caliburn Micro. You could implement something similar or use CM itself. When using CM I don't even think about this stuff, CM makes it so simple.
When your ViewModel inherits from Screen there are life-cycle events that fire that you can override. For example, OnInitialize fires the very first time the ViewModel is Activated and OnActivate fires every time the VM is activated. There's also OnViewAttached and OnViewLoaded.
These methods are the perfect place to put logic to populate or re-populate data.
CM also has some special built in features for allowing one to easily tombstone a single property or an entire object graph into Iso or phone state.
ok, so Ive come up with a solution. Before I get to it, let me provide some background. The app that Im working on uses both MVVM Light and WP7Contrib. That being the case, I am using Funq for DI and the MVVMLight Toolkit. After I posted my initial question, I gave the question a bit more thought. I remembered a video that I watched a while back from MIX2011 called Deep Dive MVVM with Laurent Bugnion
http://channel9.msdn.com/Events/MIX/MIX11/OPN03
In it, he talks about just this problem (view models not living at the same time) on Windows Phone. The part in question starts around the 19 minute mark.
Anyway, after I remembered that and realized that the ViewModel locator is exposed in App.xaml, this became a trivial problem to solve. When the user changes the Fahrenheit/Celcius option on the setting page, I simply get a reference to the MainViewModel via the ViewModelLocator and reset the collection that is bound to the UI thus causing the bindings to update.
public bool AddOrUpdateValue(string Key, Object value)
{
bool valueChanged = false;
// If the key exists
if (settings.Contains(Key))
{
// If the value has changed
if (settings[Key] != value)
{
// Store the new value
settings[Key] = value;
valueChanged = true;
}
}
// Otherwise create the key.
else
{
settings.Add(Key, value);
valueChanged = true;
}
return valueChanged;
}
public bool ImperialSetting
{
get
{
return GetValueOrDefault<bool>(ImperialSettingKeyName, ImperialSettingDefault);
}
set
{
if (AddOrUpdateValue(ImperialSettingKeyName, value))
{
Save();
RaisePropertyChanged("ImperialSettingText");
var vml = new ViewModelLocator();
vml.MainViewModel.Cities = (App.Current as App).Cities;
}
}
}
It was a mistake on my part not to realize that I could get access to the viewModel via the ViewModelLocator. Hopefully this post saves someone else the time I burned on this issue.

WP7 Navigation - NullReferenceException

I need to navigate to a certain page the first time my app is run, to gather login details etc. I'm using IsloatedStorageSettings to save a value to determine if this is the first run of the app or not, which works fine.
My problem is actually navigating to my 'first run' page when the app is run for the first time, using NavigationService, it seems NavigationService is not created at this point so is still null. When is NavigationService created or how can I work around this?
My code (in the constructor of my main page:
if ((bool)settings["firstRun"])
{
if (NavigationService != null)
{
NavigationService.Navigate(new Uri("/FirstRun.xaml", UriKind.Relative));
}
else
{
MessageBox.Show("Navigation service must be null?"); //always prompts
}
}
else
{
InitializeComponent();
}
Peter Torr has a great blog post on the ins and outs of redirecting for the initial navigation, though for user login I'd suggest that you either use a full screen popup or have a login control on your "normal" start page and toggle visibility based on your first run condition.
Add in class
private bool m_onNavigatedToCalled = false;
In ctor
this.LayoutUpdated += new EventHandler(MainPage_LayoutUpdated);
Then in code
void MainPage_LayoutUpdated(object sender, EventArgs e)
{
if (m_onNavigatedToCalled)
{
m_onNavigatedToCalled = false;
Dispatcher.BeginInvoke(() =>
{
if (NavigationService != null)
{
MessageBox.Show("Navigation not null?"); //always prompts
}
else
{
MessageBox.Show("Navigation service must be null?");
}
//StartApp(); do all stuff here to keep the ctor lightweight
}
);
}
}

Resources