Qt Developer Days 2014 Slides: A Solid Back End for a Solid Qt Mobile Application

My second presentation at Qt Developer Days 2014 in San Francisco was about how to build a scalable and reliable server side application with Qt Cloud Services using PaaS (Platform as a Service).

Abstract

Nowadays many mobile applications are relying more and more on server-side applications. Setting up servers and deploying a server-side application can be hard and time-consuming, but it has not to be.

Qt Cloud Services contains three different services that can be utilised to implement a robust and scalable server-side solution easily. Managed Application Runtime (MAR) is used to deploy and run applications on the cloud, Enginio Data Stroage (EDS) can be used to store data and Managed WebSocket (MWS) service makes it possible to send and receive WebSocket messages. By combining these three services it is possible to build and deploy a server-side solution without configuring any server machine.

In this presentation an example Qt mobile application demonstrates how to implement a real-time Twitter stream provided by a server-side application that is running on MAR. The server-side application stores tweets to EDS and sync new tweets to the client via WebSocket protocol.

This presentation covers:
– overview of MAR, EDS and MWS services
– basics how to create MAR, EDS and MWS instances
– example how to implement a server-side application that stores data to EDS and provides an API.
– example how to deploy the application to MAR
– example how to connect to the server-side application from Qt client application
– example how to send data to the client application with MWS.

Qt Developer Days 2014 Slides: Give a push to your Qt application with WebSockets and Qt Cloud Services

I was at Qt Developer Days 2014 in Berlin and San Francisco this year. I gave there couple of presentations about Qt Cloud Services. The first one was about WebSockets and how you can utilise them very easily with Qt Cloud Services and Qt.

Abstract

WebSockets is an advanced technology that makes it possible to establish an interactive communication session between an online client application and a server. With WebSockets you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

Qt 5.3 introduced new Qt WebSockets module that features full support for WebSocket protocol (RFC-6455). To benefit WebSocket technology with Qt, a server-side implementation is needed to control the message flow. Qt Cloud Services offer two different ways to achieve this goal:
– Managed WebSocket (MWS)
– Managed Application Runtime (MAR)

MWS is a fully managed WebSocket service that will automatically scale with users and supports build-in access control and policies.

MAR is a managed application platform-as-a-service that provides all the tools needed for server-side development.

This presentation covers:
– Overview of WebSockets and common use cases
– Overview of MWS and MAR services
– Basics how to create MWS and MAR instances
– Examples how to benefit MWS in order to send and receive WebSocket messages in a Qt client application
– Examples how to deploy a Qt WebSocket server to MAR and use it in a client application

Using Backbone.js models and collections with Qt and QML

Backbone QML TodoI have been a big fan of Backbone.js a long time. Together with Marionette.js it offers a solid toolkit to front-end web developers.

Lately I have worked with Qt and QML. With QML you can create nice user interfaces very easily, but what I have missed is that easy integration to backend applications. So I thought what if I try to use models and collections of backbone.js. I was quite a skeptical first, because backbone.js depends on jQuery with uses window and document objects that are not working in Qt. However I decided to try it.

Instead of jQuery, I grabbed Zepto.js that offers the same API as jQuery. I tuned the library slightly to get rid of errors related to window and document objects. There were not many of them.

Then I took underscore.js that backbone.js uses and finally backbone.js itself. I made slight changes to get them initialise correctly, but nothing big changes there.

After that I only needed to implement a simple application where I could test that everything is working. The result was much better than I expected. You can use directly Backbone’s collections and models with your Qt application and even listen events in your QML file, they just work.

https://github.com/nevalla/qml-backbone-todo

Define backbone models and collections
// app.js
var baseUrl = "https://api.engin.io/v1";
var Todo = Backbone.Model.extend({

});

var TodosCollection = Backbone.Collection.extend({
model: Todo,
url: baseUrl+”/objects/todos”,

parse: function(response) {
return response.results;
}
});

2. Use models and collections in QML file

//main.qml
function completeItem(index) {
var todo = App.todos.at(index)
todo.save({completed: true}, {
success: function(model) {
todoModel.setProperty(index, "itemProcessing", false);
},
error: function(){ console.log("error")}
} )
todoModel.set(index, todo);
}

3. Listen collection events in QML file

//main.qml
ListModel {
id: todoModel
}
Component.onCompleted: {
App.todos.on("add", function(todo) { todoModel.append(todo) });
App.getTodos();
}

So the first impact was very positive. I haven’t tested all functions of Backbone.js yet, so there may be some errors. However I don’t believe there are any fundamental errors that prevent using Backbone.js.

Android support ViewPager holds reference to old fragments

I was implementing a feature where I have a service that retrieves data on background and an activity receives results and updates one of the fragments with new data.

Everything went well until I rotated the screen and the application was re-created and fragments and fragments pager was initialized again. After that new data did not show up. At that point I was totally uncertain what was wrong. At first I was thinking the problem was with the service, but it turned out that nothing was wrong there. After struggling a while I noticed that the fragment that was  re-created was not attached to the view at all.

That led me to this Stack Overflow question and one answer provided a solution for me as well. The problem lies on Compatibility library v.4 ViewPager (bug report) combined with FragmentPagerAdapter. In some level ViewPager or FragmentPagerAdapter holds references to old fragments and does not refresh them correctly.

One working solution is to use FragmentStatePagerAdapter instead of FragmentPagerAdapter. However I resolved my issue with the help of this answer.

I implemented getFragmentTag() method in my FragmentPagerAdapter class

private String getFragmentTag(int pos){
    return "android:switcher:"+R.id.viewpager+":"+pos;
}

change R.id.viewpager to match with you ViewPager compnent’s id.

Then in my Activity I find reference to the Fragment like this.

...
this.mPagerAdapter  = new MyPagerAdapter(getSupportFragmentManager(), fragments, titles);
this.pager = (ViewPager)super.findViewById(R.id.viewpager);
this.pager.setAdapter(this.mPagerAdapter);
int position = 3;
this.myFragment = (MyFragment)getSupportFragmentManager().findFragmentByTag(mPagerAdapter.getFragmentTag(position));
...

And after service returned new data I simply call

...
myFragment.updateData(data);
...

Hopefully this saves someones time to figure out what is wrong instead of hours of investigation.

ExpandableListView with CheckedTextView

ExpandableListView

I was implementing a settings list activity with CheckedTextView and I found out that Android’s ExpandableListView is a handy component to display some hierarchical data. However in my case there was one weakness. You can not see which items are selected when a parent group is collapsed. I wanted to display the text of selected child items in the parent view. My biggest problem was that I couldn’t reach the parent view in reliably way when child item was clicked.

I tried to search from the internets are there any solutions ready, but I found nothing there (or I used wrong search terms). As earlier I made my own solution.

My ExpandableListView solution is based on this tutorial. 

I solved parent view issue by setting unique tag to parent view in Adapter class.

@Override
//in this method you must set the text to see the parent/group on the list
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {

if (view == null) {
view = inflater.inflate(R.layout.settings_list_item_parent, viewGroup,false);
}
// set category name as tag so view can be found view later
view.setTag(getGroup(i).toString());

….

}

Based on that tag I can find parent view later when child item is clicked.

@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {

CheckedTextView checkbox = (CheckedTextView)v.findViewById(R.id.list_item_text_child);
checkbox.toggle();

// find parent view by tag
View parentView = categoriesList.findViewWithTag(categories.get(groupPosition).name);


}

One nice feature that I have used in my ExpandableListView is autocollapse feature that I found here.

Get the full source code here: https://github.com/nevalla/expandablelistview-demo

Android libraries I have used recently

Liigavahti Android app
Liigavahti Android app

I have implemented an Android application called Liigavahti. It is only in Finnish, but basic idea is to provide Finnish ice hockey news streams to users. Application includes Twitter stream as well.

When implementing the application I found out couple of great libraries that helped me a lot and I would like to share them to you:

ActionBarSherlock [http://actionbarsherlock.com/]

ActionBarSherlock is an extension of the support library designed to facilitate the use of the action bar design pattern across all versions of Android with a single API.

Basically it provides same functionality than native ActionBar to older Android versions.

ViewPageIndicator [http://viewpagerindicator.com/]

ViewPageIndicator provides paging indicator widgets compatible with the ViewPager from the Android Support Library and ActionBarSherlock. Also here this library brings functinality of ViewPager to older Android versions

Android-PullToRefresh [https://github.com/chrisbanes/Android-PullToRefresh]

Android-PullToRefrehs project aims to provide a reusable Pull to Refresh widget for Android. You have seen this kind of functionality in several mobile apps like Twitter and Facebook. This library makes it easy to implement that kind of functionality.

GitHub Android App [https://github.com/github/android]

Actually this is not a library, but why I mention this is the reason that it helped me a lot to understand how to do things right way. So if you have some spare time I suggest you to check this out. Be careful you might learn something

When I was implementing my application I struggled a while with examples I found. So I will provide some simple tutorials how to use these libraries. So stay tuned!

How to implement CalendarView in Android

Android does not offer any calendar view in the SDK. That is a big loss from the developer’s point of view. There are lots of situations where it would be beneficial to display days of a month and provide some option for the user to choose the day.

One solution is to use a 3rd party component. The second one is to implement one by your own, like I did.

Picture 1. CalendarView

When I started to implement  the calendar view, I googled around with some search terms and found this tip.

AFAIK, there are no other way than implement your own calendar. So… what you would have to do is using a GridLayout with 7 columns and create a custom BaseAdapter to display data correctly.

That sounded reasonable and I went ahead and tried it. My aim was to implement a single calendar view where user can navigate between months and choose a date (Picture 1). You can see the result here: https://github.com/nevalla/CalendarView

Basically two classes are needed to create the implementation mentioned above. One class to display calendar grid and the other one to adapt calendar days and items into the grid.

CalendarView.java

CalendarView is  a class that encapsulates the UI of the Calendar:  a header (navigation and name of the month) and a GridView.  onCreate() method does some initializations and res/layout/calendar.xml is set for the content view. Then handler attribute is used to populate some calendar items into to the calendar. Finally some event listeners are set. GridView’s OnClickListener returns selected date as string format:

gridview.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    	TextView date = (TextView)v.findViewById(R.id.date);
        if(date instanceof TextView && !date.getText().equals("")) {

        	Intent intent = new Intent();
        	String day = date.getText().toString();
        	if(day.length()==1) {
        		day = "0"+day;
        	}
        	// return selected date as string format
        	intent.putExtra("date", android.text.format.DateFormat.format("yyyy-MM", month)+"-"+day);
        	setResult(RESULT_OK, intent);
        	finish();
        }

    }
});

refreshCalendar() method asks calendar adapter to refresh itself and changes month name.
onNewItem() method captures date parameter and sets it as current date.

CalendarAdapter.java

CalendarAdapter is a class that handles the content of the calendar – how many days to display and whether to display calendar item icon or not.

refreshDays() method formats source array for the grid. Application assumes that weeks start on Monday, thus calculation is needed on how many empty days are before the first day of the month.

getView() method creates a view for each item referenced by the adapter. Layout of the view is defined in res/layout/calendar_item.xml.

CalendarViewSampleActivity.java

CalendarViewSampleActivity is an activity class that opens CalendarView. DatePicker’s date is updated by the return  value of the CalendarView.
So this is relatively simplified example of how to display calendar month and populate some items into it. How do you like it and how would you improve it?

UPDATE 1:

Since API level 11 (Android 3.0) there has been the native implementation of the CalendarView. However it’s just the view where you can pick a date, no calendar items can be shown.