Windows Phone NullReferenceException while navigating mystery - windows-phone-8

During page navigatin within my app I display a message in the system tray to the user along with the progress bar to indicate something is going on.
The problem I'm having is during debug I am randomly getting the following error:
{System.NullReferenceException: Object reference not set to an instance of an object.
at ContosoSocial.SetProgressIndicator.<>c__DisplayClass1.<runSystrayMessage>b__0(Object sender, EventArgs args)
at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)} System.Exception {System.NullReferenceException}
Stacktrace:
StackTrace " at ContosoSocial.SetProgressIndicator.<>c__DisplayClass1.<runSystrayMessage>b__0(Object sender, EventArgs args)\r\n at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)\r\n at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)" string
I'm still new to VS2013 and Windows Phone programming so really need a little help here figuring out how to trace and fix this problem?
The error seems to be random, here is an example of the class displaying the system tray message and calling method:
class SetProgressIndicator
{
public void runSystrayMessage(bool isVisible, string text, int length)
{
try
{
SystemTray.ProgressIndicator = new ProgressIndicator();
SystemTray.ProgressIndicator.IsVisible = true;
SystemTray.ProgressIndicator.Text = text;
SystemTray.ProgressIndicator.IsIndeterminate = isVisible;
}
catch (System.InvalidOperationException e)
{
Debug.WriteLine("Exception caught in runSystrayMessage(): \r\n" + e);
}
DispatcherTimer timer = new DispatcherTimer();
try
{
timer.Interval = TimeSpan.FromMilliseconds(length);
}
catch(ArgumentOutOfRangeException e)
{
Debug.WriteLine("Exception caught in runSystrayMessage(): \r\n" + e);
}
timer.Tick += (sender, args) =>
{
try
{
SystemTray.ProgressIndicator.IsVisible = false;
}
catch(System.InvalidOperationException e)
{
Debug.WriteLine("Exception caught in runSystrayMessage(): \r\n" + e);
}
timer.Stop();
};
timer.Start();
}
}
}
Example of a calling method:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
SetProgressIndicator progInd = new SetProgressIndicator();
// Check for full licnece before removing ad's
if (TrialExperienceHelper.LicenseMode == TrialExperienceHelper.LicenseModes.Full)
{
GOTPubCenter10.Visibility = Visibility.Collapsed;
}
// Dispaly message in system tray
if (hasBeenVisited)
{
progInd.runSystrayMessage(true, "Entering house selection menu...", 2500);
}
else
{
progInd.runSystrayMessage(true, "Select house library to enter...", 8000);
hasBeenVisited = true;
}
}
Ideas and suggestions on how to solve the problem appreciated.

Related

How to get a Toast Notification when app running in foreground in wp8

I want to implement the "toast" notification inside my windows phone application. I'm implementing push message's, but I want them to show always. No matter if the application is running or not. The push notification will handle it when the application is closed, but not when it is running. Also if I create a shelltoast manually it won't show. To make it more difficult I can't use any external dll's. I only want to use code. What would be the best way to do this? I already know about the ToastNotificationRecieved event. I want to know how to implement it so that it will show a "toast" like message without using a framework
My code is below
PushPlugin.cs(c# code)
public void showToastNotification(string options)
{
ShellToast toast;
if (!TryDeserializeOptions(options, out toast))
{
this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
Deployment.Current.Dispatcher.BeginInvoke(toast.Show);
}
public void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
var toast = new PushNotification
{
Type = "toast"
};
foreach (var item in e.Collection)
{
toast.JsonContent.Add(item.Key, item.Value);
}
this.ExecuteCallback(this.pushOptions.NotificationCallback, JsonConvert.SerializeObject(toast));
}
In javascript
function onNotificationWP8(data) {
var pushNotification;
pushNotification = window.plugins.pushNotification;
pushNotification.showToastNotification(successHandler, errorHandler,
{
"Title": data.jsonContent["wp:Text1"], "Content": data.jsonContent["wp:Text2"], "NavigationUri": data.jsonContent["wp:Param"]
});
}
On devices without Windows Phone 8 Update 3, toast notifications are not displayed when the target app is running in the foreground. On devices with Windows Phone 8 Update 3, toast notifications are displayed when the target app is running in the foreground, but is obscured by other activity such as a phone call or the lock screen.
The following C# code example shows the properties used to create a toast notification using local code.
// Create a toast notification.
// The toast notification will not be shown if the foreground app is running.
ShellToast toast = new ShellToast();
toast.Title = "[title]";
toast.Content = "[content]";
toast.Show();
This thread has it all you looking for
public static class Notification
{
public static string ChannelURI = string.Empty;
public static void MainNotificationCallFunction()
{
try
{
NotificationMessage("Test Notification");
}
catch (Exception e)
{ }
}
public static void NotificationMessage(string Message)
{
try
{
ToastTemplateType toastType = ToastTemplateType.ToastText02;
XmlDocument toastXmlJob = ToastNotificationManager.GetTemplateContent(toastType);
XmlNodeList toastTextElementJob = toastXmlJob.GetElementsByTagName("text");
toastTextElementJob[0].AppendChild(toastXmlJob.CreateTextNode(Message));
IXmlNode toastNodeJob = toastXmlJob.SelectSingleNode("/toast");
((XmlElement)toastNodeJob).SetAttribute("duration", "long");
ToastNotification toastJob = new ToastNotification(toastXmlJob);
ToastNotificationManager.CreateToastNotifier().Show(toastJob);
}
catch (Exception e)
{ }
}
public static void PushNotification()
{
try
{
/// Holds the push channel that is created or found.
HttpNotificationChannel pushChannel;
string channelName = "Usman's Channel";
// Try to find the push channel.
pushChannel = HttpNotificationChannel.Find(channelName);
// If the channel was not found, then create a new connection to the push service.
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
//// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
pushChannel.Open();
pushChannel.BindToShellTile();
pushChannel.BindToShellToast();
}
else
{
//// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
}
}
catch (Exception ex)
{ }
}
private static void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
MessageBox.Show(String.Format("Channel Uri is {0}", e.ChannelUri.ToString()));
});
}
catch (Exception ex)
{ }
}
private static void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
try
{
// Error handling logic for your particular application would be here.
Deployment.Current.Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}", e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)));
}
catch (Exception ex)
{ }
}
private static void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
try
{
string message;
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message = reader.ReadToEnd();
}
Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(String.Format("Received Notification {0}:\n{1}", DateTime.Now.ToShortTimeString(), message)));
}
catch (Exception ex)
{ }
}
private static void channel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(e.Message, "Error", MessageBoxButton.OK);
});
}
catch (Exception ex)
{ }
}
private static void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//ProgressBarPushNotifications.Visibility = System.Windows.Visibility.Collapsed;
MessageBox.Show(e.ChannelUri.ToString(), "Uri Recieved", MessageBoxButton.OK);
});
}
catch (Exception ex)
{ }
}
private static void channel_ShellToastNotificationReceived(object sender, HttpNotificationEventArgs e)
{
try
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message.AppendFormat(reader.ReadToEnd());
}
// Display a dialog of all the fields in the toast.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(message.ToString());
});
}
catch (Exception ex)
{ }
}
}

send message to mobile api j2me

Hello everyone I'm getting this error:
Uncaught exception: java.lang.IllegalArgumentException: Port Number formatted badly
- com.sun.midp.io.j2me.sms.Protocol.openPrimInternal(), bci=209
- com.sun.midp.io.j2me.sms.Protocol.openPrim(), bci=4
- javax.microedition.io.Connector.open(), bci=47
- javax.microedition.io.Connector.open(), bci=3
- javax.microedition.io.Connector.open(), bci=2
- travel.entities.SendMessage$1.run(SendMessage.java:31)
- java.lang.Thread.run(), bci=5
when converting those two textfields to send them
public TextField tfDestination = new TextField("Destination","", 20, TextField.PHONENUMBER);
public TextField tfPort = new TextField("Port", "50001", 6, TextField.NUMERIC);
using this method:
public static void execute(final String destination, final String port, final String message) {
Thread th = new Thread(new Runnable() {
public void run() {
MessageConnection msgConnection;
try {
msgConnection = (MessageConnection) Connector.open("sms://:"+port+":"+destination);
TextMessage textMessage = (TextMessage)msgConnection.newMessage(MessageConnection.TEXT_MESSAGE);
textMessage.setPayloadText(message);
msgConnection.send(textMessage);
msgConnection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
th.start();
}
I'm getting the error on this line:
msgConnection = (MessageConnection)Connector.open("sms://:"+destination+":"+port);
Anyone have an idea?
Your destination should come before port number.
Try this:
public static void execute(final String destination, final String port, final String message) {
Thread th = new Thread(new Runnable() {
public void run() {
MessageConnection msgConnection;
String address = "sms://:"+destination+":"+port;
try {
msgConnection = (MessageConnection) Connector.open(address);
TextMessage textMessage = (TextMessage) msgConnection.newMessage(MessageConnection.TEXT_MESSAGE);
textMessage.setAddress(address);
textMessage.setPayloadText(message);
msgConnection.send(textMessage);
msgConnection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
th.start();
}

Android ListView Volley FATAL EXCEPTION error

I'm developing an Android App and i create a slide menu. In the slide menu i have item "Search". This is a fragment that call a json (using volley) and input the result into custom list view.
Now when i call the fragment (using debug mode) the fragment start to download some data but after some record of json download the app crash and i receive this error:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.firstproject.fragment.SearchFragment.loadListView(SearchFragment.java:175)
at com.firstproject.fragment.SearchFragment.access$000(SearchFragment.java:46)
at com.firstproject.fragment.SearchFragment$1.onResponse(SearchFragment.java:105)
at com.firstproject.fragment.SearchFragment$1.onResponse(SearchFragment.java:98)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
I attach my code where i call a json file (for privacy delete the url json)
Any help please?
Thanks
public class SearchFragment extends Fragment {
public SearchFragment(){}
private static final String url = "http://<server_name>/<folder>/data.json";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_search, container, false);
}
ListView geoJSON;
String globalResponse="";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String tag_string_req = "string_req";
final ProgressDialog pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
RequestQueue mRequestQueue;
Network network = new BasicNetwork(new HurlStack());
//Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Instantiate the RequestQueue with the cache and network.
Cache cache = AppController.getInstance().getRequestQueue().getCache();
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
Cache.Entry entry = cache.get(url);
if(entry != null){
try {
String data = new String(entry.data, "UTF-8");
//loadListView(gobalResponse,0,1000);
//Toast.makeText(getActivity(), "Cache utilized!", 0).show();
// handle data, like converting it to xml, json, bitmap etc.,
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else{
// Cached response doesn't exists. Make network call here
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
globalResponse=response;
Globals.GlobalResponse=globalResponse;
Log.d("", response.toString());
loadListView(globalResponse,0,1000);
//loadListView(response,0,1000);
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(), error.getMessage()+"", 0).show();
pDialog.hide();
}
});
strReq.setShouldCache(true);
//strReq.
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
private ArrayList<GeoJsonResponse> globalResponseObject;//=new ArrayList<GeoJsonResposne>();
private void loadListView(String response,float lowerLimit,float upperLimit)
{
try {
JSONObject featureCollection=new JSONObject(response);
globalResponseObject=new ArrayList<GeoJsonResponse>();
JSONArray features=featureCollection.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject properties=features.getJSONObject(i);
float mag=Float.parseFloat(properties.getJSONObject("properties").getString("mag"));
if(!(mag>=lowerLimit&&mag<upperLimit)) continue;
Log.d("",properties.getJSONObject("properties").getString("author")
+ properties.getJSONObject("properties").getString("mag")
+ properties.getJSONObject("properties").getString("place")
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(0)
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(1)
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(2)
);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date1 = format.parse(properties.getJSONObject("properties").getString("time"));
GeoJsonResponse obj=new GeoJsonResponse(
properties.getJSONObject("properties").getString("eventId"),
properties.getJSONObject("properties").getString("author"),
properties.getJSONObject("properties").getString("place"),
Double.parseDouble(properties.getJSONObject("properties").getString("mag")),
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(2)),
properties.getJSONObject("properties").getString("time"),date1,
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(0)),
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(1))
);
globalResponseObject.add(obj);}
if(lowerLimit==0)
Globals.geoJsonResponse=globalResponseObject;
// Collections.sort(globalResponseObject, new DateSorter());
CustomListAdapter adpater=new CustomListAdapter(getActivity()
, globalResponseObject);
adpater.notifyDataSetChanged();
geoJSON.setAdapter(adpater);
geoJSON.invalidate();
geoJSON.invalidateViews();
//, author, place, magnitude, distance, date)
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

WebClient TimeOut Windows Phone 8

I would like to run a task during the waiting of a web request. If the task finishes before the request can return a response, then I would display a message "The server is taking too long". I'm using a WebClient object, how can I manage the time out?
public Class Result
{
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.TryGetValue("critere", out sCritere))
{
try
{
_datamanager = new DataManager();
_datamanager.m_evt_Client_DownloadStringCompleted += OnDownloadStringCompleted;
_datamanager.DownloadXmlData(DataManager.URL_RECHERCHE, sCritere);
//HERE I NEED TO RUN A TIMER If the response is too long i would display a message
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Erreur", MessageBoxButton.OK);
NavigationService.GoBack();
NavigationService.RemoveBackEntry();
}
}
}
}
public Class DataManager
{
public void DownloadXmlData(string uri, string critere = "")
{
try
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.Credentials = new NetworkCredential(UserSaved, PasswordSaved, domain);
client.DownloadStringAsync(new Uri(uri + critere));
}
catch(WebException )
{
throw new WebException(MyExceptionsMessages.Webexception) ;
}
catch (Exception )
{
throw new UnknowException(MyExceptionsMessages.UnknownError);
}
}
public void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//raise Downloadstringcompleted event if error==null
}
}
You can use BackgroundWorker..
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
// your task to do while webclient is downloading
};
bw.RunWorkerCompleted += (s, e) =>
{
// check whether DownloadStringCompleted is fired or not
// if not, cancel the WebClient's asynchronous call and show your message.
client.CancelAsync();
MessageBox.Show("message");
}
client.DownloadStringAsync(uri);
bw.RunWorkerAsync();

Where to catch exception in WebClient method?

I'm developing app which connects to service and consume some JSON data. Consuming works great (JSON.net rocks) but I wonder where I should catch exception error annd show simple MessageBox? Tried in few places but still my app is closing. Or maybe I should do it based on json response which contain error tag? I think that normal error handling could be easier, but have blank spot in my mind now..
Code is below:
private void LoginLoginButton_Click(object sender, System.EventArgs e)
{
((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
ProgressOverlay.Show();
GenerateLoginString();
var w = new SharpGIS.GZipWebClient();
Observable.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var settings = IsolatedStorageSettings.ApplicationSettings;
var deserializedRootObject = JsonConvert.DeserializeObject<RootObject>(r.EventArgs.Result);
UserSettings us = new UserSettings()
{
first_name = deserializedRootObject.user.first_name,
last_name = deserializedRootObject.user.last_name,
user_id = deserializedRootObject.user_id,
};
settings.Add("UserSettings", us);
settings.Save();
});
w.DownloadStringAsync(new Uri(UserUri));
w.DownloadStringCompleted += new DownloadStringCompletedEventHandler(w_DownloadStringCompleted);
}
void w_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
If you mean you want to catch an exception which occurs in your web client call then it should be in the Error property of DownloadStringCompletedEventArgs.
void w_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if(e.Error != null)
{
MessageBox.Show("An error occurred!");
}
else
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
Solved!
I used try and catch in this case. Works perfect :)