How to show a Toast for a specific duration in Android

In the Android SDK, an android.widget.Toast is a small message that pops up at the bottom of the screen to display an information. The toast will disappears by itself after a specified duration. Here is an example of what a toast looks like and how to display one :

CustomToastDuration

Context context = getApplicationContext();
Toast.makeText(context, "Hello world, I am a toast.", Toast.LENGTH_SHORT).show();

The duration for which a toast is displayed on screen is unfortunately defined by a flag: you can either show it for a SHORT duration, which is 2 seconds or a LONG duration which is 3,5 seconds. But what if you have a long error message that needs to be shown for longer than that? Or if you need to show a countdown that updates every second?

There are no way to directly change the duration for which the toast is shown using the show() method without reimplementing the whole Toast class in your application, but there is a workaround. You can use a android.os.CountDownTimer to count down the time for which to display a toast. The CountDownTimer class schedules a countdown for a time in milliseconds with notifications at specified intervals until the countdown is finished.

In this example, the countdown is used to display a toast message for a specific duration when a button is pressed:

private Toast mToastToShow;
public void showToast(View view) {
   // Set the toast and duration
   int toastDurationInMilliSeconds = 10000;
   mToastToShow = Toast.makeText(this, "Hello world, I am a toast.", Toast.LENGTH_LONG);

   // Set the countdown to display the toast
   CountDownTimer toastCountDown;
   toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) {
      public void onTick(long millisUntilFinished) {
         mToastToShow.show();
      }
      public void onFinish() {
         mToastToShow.cancel();
         }
   };

   // Show the toast and starts the countdown
   mToastToShow.show();
   toastCountDown.start();
}

Here is how it works: the countdown has a notification time shorter than the duration for which the toast is displayed according to the flag, so the toast can be shown again if the countdown is not finished. If the toast is shown again while it is still on screen, it will stay there for the whole duration without blinking. When the countdown is finished, the toast is cancelled to hide it even if its display duration is not over.

This works even if the toast must be shown for a duration shorter than the default duration: the first toast displayed will simply be cancelled when the countdown is finished.

Sign up now to get my newest articles about making applications and my ongoing side project delivered straight to your inbox.

Choosing a JavaScript framework for my side project

I started looking at JavaScript frameworks to see if I could find something interesting for my event scheduling project. I’m looking to use them to help me show the schedule itself: when a session of an event is modified, it must be updated in two places on the page since the list of sessions for a room is collapsible. I already took a look at SignalR and I will most likely use it to notify the other clients that the schedule has changed, but I wanted to see if there are other tools that could help me update the display of the schedule.

First, I looked at Angular.js, since it’s one of the most popular framework. I ended up not testing this one at all: there is a version 2.0 coming up that is not going to be compatible with the current version, which made a lot of noise in the Angular community. Since the time I have to work on this is limited, I don’t want to write everything in a version that will most likely be dropped in a year or two. I don’t see the advantage in learning how to use it now only to have to start over in a year or two. So, for maintainability reasons, Angular.js is out.

After this, I turned to Backbone.js, another framework that enjoys a great deal of popularity. That one was also ruled out pretty fast, since it enforces a RESTful API, which is not what I’m looking for in a JavaScript framework. I would rather rely on the server knowing what is the right business logic and not the JavaScript: for example, if I want to offer a command to move a session 15 minutes earlier, I’d rather just tell my server via a WebAPI to MoveLater or MoveEarlier, let it enforce all the business logic and just show the results. I’m not looking to redeclare on the client all the model logic that lives on the server, and it cannot be on the client only since you never know what can happen on the client. This is too much of a commitment to the Backbone.js architecture to synchronize a few refreshes only, so it is out too.

I was beginning to feel like the Grinch after rejecting the goodness of all those frameworks, but I decided to give it one last try and find a framework that I could at least test in my prototype. I settled on trying Knockout.js, a small framework with no dependencies. It’s really more of a toolbox to create dynamic UI in JavaScript than a full framework, and it doesn’t need to take over the whole page. Also, older browsers are supported, the documentation is great and the features are pretty stable with no plan for a rewrite on the horizon.

I did the whole interactive tutorial on the Knockout.js site and it convinced me that this library is something I could use. I can create a ViewModel representing the parts of the page I want to update only, and keep the rest of the code simpler for the parts that don’t need to be refreshed. It also integrates nicely with existing markup: I only need to tag the markup that needs to be updated with Knockout.js with a data-bind attribute describing what the library needs to do. So, for more complex views that need to be refreshed like the schedule, I’ll use SignalR to get notifications that the data has been refreshed and Knockout.js to handle refreshing the UI.

Also, I won’t be using it those two libraries everywhere: for simple page like forms to create an event or a session, I’ll use only jQuery, a library for standard controls and some small libraries to solve focused problems. For example, I’m going to use Moment.js to handle times in my application since it’s an important part of the schedule and times are such a mess in JavaScript.

What is SignalR and why should I use it?

When I first heard about SignalR, I was not sure what was the point of it. The official description says that SignalR is a library that can be used with any ASP.NET application to add real-time communication. But since what they meant by real-time was not totally clear to me, and the only example was a chat room, I pushed it aside for a while.

When I started to work on my side project, I also started thinking about SignalR again. One of the things I want to was refresh the schedule as soon as a change was made: if a user makes a modification, it should be visible to all other users. The classic way to do something like that would be to call the server at regular intervals to get the status of the schedule, but to have pseudo real-time update your must call the server pretty often.

With SignalR, the server can call a JavaScript methods on all the clients by itself when updates are required. The library will handle the connection needed to achieve this: by default WebSocket is used, but it will fallback automatically to older connections types if WebSocket is not available in the browser. The JavaScript can also call the server: this can already be done with AJAX, but if two-way communication is needed it may be easier and cleaner to do it all with SignalR.

So, using a real-time library is the way to go if you want to build an application that requires collaboration between users. Common uses cases includes editors, social networks, chats or a schedule like my project.

Getting started wtih SignalR is pretty simple. Here is an example with my side project: sessions for an event can be modified by any user, and when a session is modified the change is visible for all the user currently logged in the application.

On the server
First, you must add the Microsoft ASP.NET SignalR package to your ASP.NET application using NuGet, along with the jQuery package if you don’t already have it.

After this, you must create a class that derives from the Hub class. All the methods of the hub can be called from JavaScript. Also, those methods can call JavaScript methods on the client.

namespace EventScheduling
{
public class SessionsHub : Hub
   {
   public void SessionModified(ScheduledSession scheduledSession)
      {
      // Call the JavaScript method sendSessionChanged on all the clients
      Clients.All.sendSessionChanged(scheduledSession);
      }
   }
}

To enable communications between the hub and the JavaScript, you must also enable SignalR in the Configuration method in the Startup class of your application.

namespace EventScheduling
{
public class Startup
   {
   public void Configuration(IAppBuilder app)
      {
      app.MapSignalR();
      }
   }
}

On the client
On the client, you must include the jquery.signalR-2.2.0.js file containing the JavaScript for the SignalR library and the package ~/signalr/hubs. This package is automatically generated from your Hub classes and contains all the JavaScript required to call the server and receive message from the server.

<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery.signalR-2.2.0.js"></script>
<script src="~/signalr/hubs"></script>

After this, when the page is loaded and ready, you must declare the JavaScript function called by the server-side code. Since the Hub class is called SessionsHub and the SessionModified method of the hub class calls the sendSessionChanged method, this function must be declared in the $.connection.sessionsHub.client.sendSessionChanged variable.

Once this function is created, you must also connect to the hubs using the $.connection.hub.start method. You can also add initialization code in the done() callback which will be called when the connection is started.

$(document).ready(function () {
   // Create a function that the hub can call to broadcast messages.
   $.connection.sessionsHub.client.sendSessionChanged = function (session) {
      // Display the session again using the new data received from the server
      });
   };

   // Start the connection and create a function that the hub will call when loaded
   $.connection.hub.start().done($("#Sessions").on("click", ".Session", function (event) {
      var that = $(this);
      var currentSession = that.data("session");
      currentSession.Title = currentSession.Title + "Clicked";
      // Call the server, which will notify all clients of the change in the title
      $.connection.sessionsHub.server.sessionModified(currentSession);
   }));
});

In the example, when the hubs are done starting, a click handler is added to each session on the page. When the users clicks a session, the word Clicked is added to the title of that session, and all browsers showing the page are notified. Since the SessionModified method was declared in the SessionsHub class of the server, it can be called from JavaScript using using the $.connection.sessionsHub.server.sessionModified method.

With only this small bit of code, you now have two-way communications between the client and the server, which you can use to update data in real-time for your users. I will use SignalR in future projects that’s for sure!