Serialisation, Deserialisation and gson in Open Event Android

JSON is a format to exchange and inter-change data. It has almost become a universal means for transferring data because of it being lightweight, human understandable, machine readable and most importantly, it’s language independence. It can be used with, and in any programming language. (Reference)

FOSSASIA’s Open Event project makes extensive use of JSON for transferring information about events, their speakers, sessions and other event information. The Open Event Android application itself loads all it’s data in JSON format. This JSON is uploaded by the user in the form of a .zip compressed file or by giving an API link. Now before we use this data in the app, we have to parse the data to get Java objects that can be used in Android. Deserialisation is the process of converting JSON to Java objects. In the same way, Serialisation refers to converting Java objects into JSON.

In most applications and frameworks, JSON is serialized and deserialized on multiple instances. The most common approach is to create objects corresponding to the JSON format and then use functions to convert them to JSON line-by-line, attribute by attribute. While this approach will work, it will mean writing unnecessary code and spending a lot more time on it. In Open-event-Android, we are using Google’s gson library to  serialise and deserialise JSON and corresponding Java objects respectively.

Why are we using gson specifically? And why do we need any library in the first place?

Yes, we can obviously make functions in Java by defining all the JSON parameters and converting the JSON into Java objects manually. It is indeed the obvious approach, but the entire process will be time-consuming, complex and definitely not error-free. Also, as projects become bigger, it is inevitable to take care of the code size and reduce it to only what is necessary.

Let’s take a look at the one of the Open Event JSON file as a sample to try and understand things in a better way. This is an example of event.json in the FBF8’2017 sample.

{

"id": 180,
"name": "F8-Facebook Developer Conference 2017",
"latitude": 37.329008,
"longitude": -121.888794,
"location_name": "San Jose Convention Center, 150 W San Carlos St  San Jose  CA USA 95113 ",
"start_time": "2017-04-18T10:00:00-07:00",
"end_time": "2017-04-19T10:00:00-07:00",
"timezone": "US / Pacific",
"description": "Join us for our annual 2-day event, where developers and businesses come together to explore the future of technology. Learn how Facebook connects the world through new products and innovation. This year's event is bigger than ever – with more than 50 sessions, interactive experiences, and the opportunity to meet one-on-one with members of the Facebook team.",
"background_image": "/images/background.jpg",
"logo": "/images/fbf8.png",
"organizer_name": "Facebook",
"organizer_description": "Join us for our annual 2-day event, where developers and businesses come together to explore the future of technology. Learn how Facebook connects the world through new products and innovation. This year's event is bigger than ever – with more than 50 sessions, interactive experiences, and the opportunity to meet one-on-one with members of the Facebook team.",
"event_url": "https://www.fbf8.com",
"social_links": [
{"id": 1,
"link": "https://www.facebook.com/FacebookForDevelopers",
"name": "Facebook"},
{"id": 2,
"link": "https://twitter.com/fbplatform",
"name": "Twitter"},
{"id": 3,
"link": "https://www.instagram.com/explore/tags/fbf8/",
"name": "Instagram"},
{"id": 4,
"link": "https://github.com/Facebook",
"name": "GitHub"}],
"ticket_url": null,
"privacy": "public",
"type": "",
"topic": "Science & Technology",
"sub_topic": "High Tech",
"code_of_conduct": "",
"copyright": {
"logo": "",
"licence_url": "https://en.wikipedia.org/wiki/All_rights_reserved",
"holder": "Facebook",
"licence": "All rights reserved",
"holder_url": null,
"year": 2017},
"call_for_papers": null,
"email": null,
"has_session_speakers": false,
"identifier": "7d16c124",
"large": null,
"licence_details": {
"logo": "",
"compact_logo": "",
"name": "All rights reserved",
"url": "https://en.wikipedia.org/wiki/All_rights_reserved",
"long_name": "All rights reserved",
"description": "The copyright holder reserves, or holds for their own use, all the rights provided by copyright law under one specific copyright treaty."},
"placeholder_url": null,
"schedule_published_on": null,
"searchable_location_name": null,
"state": "Published",
"version": {
"event_ver": 0,
"microlocations_ver": 0,
"sessions_ver": 0,
"speakers_ver": 0,
"sponsors_ver": 0,
"tracks_ver": 0}}

For a file with so many attributes, it can be very tedious to make a parser class in Java. Instead, we simply use the gson library to do the job.

To install gson in maven central, add the following dependency:

<dependencies>
   <!--  Gson: Java to Json conversion -->
   <dependency>
     <groupId>com.google.code.gson</groupId>
     <artifactId>gson</artifactId>
     <version>2.8.0</version>
     <scope>compile</scope>
   </dependency>
</dependencies>                                             

[source:https://github.com/google/gson/blob/master/UserGuide.md]

To use gson in Android, we need to add the following dependency in build.gradle of the project.

compile ‘com.google.code.gson:gson:2.6.2’

Using gson in your code is as simple as using any built-in class in java. There are two main functions – toJson()and fromJson() that will be used throughout the processes of serialisation and deserialisation.

First off, let’s declare a basic Java object. I will take an example of a Java object that represents a car to simplify things a bit. This object car contains 3 variables- Name, Model number and color of the car. For example:

class Car(){
String  name;
int model_no;
String colour;
Car(){}
}

Serialisation:

Serialising the car object now, that is converting the object into JSON format:

Car one = new Car();
Gson gson = new GSON();
String serialised_output= gson.toJson(car);//serialised_output=>JSON

Deserialisation:

Deserializing the JSON now, that is converting the JSON into java objects:

Car car = gson.fromJson(serialised_output,Car.class);

Finally, you can find the GitHub link for gson library here in case you want to know more about it or if you are facing some issues with the library, you can report them there. This is the link to the official Google group for discussions related to gson.

Continue ReadingSerialisation, Deserialisation and gson in Open Event Android

Landing Page for Phimpme Android

Landing page for any app is very important for its distribution. Its provide all the relevant informations for the app, its download/ source link and screenshot of the app for preview of its view and features. As our Phimpme app is now reached to a milestone, so we decided to bring out a landing for it.

Landing page is a simple static website which gives relevant informations and their links on a page. To develop a landing page, we can use multiple frameworks available for it. For example using Bootstrap, basic pages using html and css. As GitHub provides a free hosting service such as Github pages. I decided to work on jekyll which is easy to customize and hosted with GitHub pages.

How I did in Phimpme

  • Search for Open Source theme

There are various open source themes present for jekyll, mainly you will get for blogs. I got this awesome app landing page. It fulfils our requirements of showing a screenshot, brief description and links.

  • Create separate branch for Landing page

The GitHub pages works from a separate branch. So I firstly created a orphan branch in main Phimpme Repository. And Clear the working directory. Orphan branches are those branch which do not have any commit history. It is highly required that branch should not have any commit history, because that will irrelevant for gh-pages branch.

git checkout --orphan gh-pages
git rm --cached -r .
  • Test on Fork repo

Now rebase your branch with the gh-pages branch created on the main repository. Add the complete jekyll code here. To reflect changes on github.io page. You need to enable that in settings.

  • Enable gh-pages from settings

Go to the Settings of your repo

Scroll down to gh-pages section

Here things are clear, as we need to select the source branch from where the gh-pages is hosted. We can directly choose some open source themes built over jekyll. Also there is a option to add custom domain, such phimp.me in our case.

This all I’m writing as per the Developer perspective, where the developer have limited access to the repository and can’t access the settings of main repo. In that case push your code to by selecting the gh-pages base branch.

  • Problems I faced

The usual problem any Developer here faces is creating a orphan branch in main repo. This required removing all the files as well. Also to face less problem I recommend using some other editor such as Sublime Text, Atom etc. Or any other IDE other than Android Studio. Because in Android Studio after changing branch, it sync and rebuild again which actually takes lots of time.

Resources

 

Continue ReadingLanding Page for Phimpme Android

Using Day Night Theme in SUSI Android

SUSI is an artificial intelligence for interactive chat bots. It provides response to the user in most intuitive way. Therefore we thought why not implement the option to give theme preference to the user to make it more interactive. It will also help in increasing the user’s interest towards the application.

We tried out different themes and then finally decided to settle for the newly announced Day Night Theme for the SUSI Android App (https://github.com/fossasia/susi_android). This theme is provided by AppCompat 23.2.0 . With the help of this theme we can switch between Theme.AppCompat.Light (light) and Theme.AppCompat (dark) based on the user preference and time of day. For default the theme is set to the light theme and it can be easily changed from the settings. Thus it allows the user to change the theme according to his or her mood which looks very intuitive.

How to use this theme?

To use the Day Night theme is quite simple. We just need to extend our default theme to that of Theme.AppCompat.DayNight. The declaration is done as shown below in the screenshot.

<style name="MyTheme" parent="Theme.AppCompat.DayNight">

  <!-- Blah blah -->

</style>

Now to enable different features of the theme in our application we need to call AppCompatDelegate.setDefaultNightMode(). It takes one of the following values as the parameter.

  • MODE_NIGHT_NO. This is for the day (light) theme.
  • MODE_NIGHT_YES.This is for the night (dark) theme.
  • MODE_NIGHT_AUTO. It automatically changes between the above two themes based on the time of day.
  • MODE_NIGHT_FOLLOW_SYSTEM (default). This theme is dependent on the system settings of the user mobile phone.

We can set one of these parameters at the time of calling the function to fix the theme of the application in the following way.

static {

AppCompatDelegate.setDefaultNightMode(

          AppCompatDelegate.MODE_NIGHT_...);

}

The theme inside an activity is set at the time time of calling onCreate() method. Therefore we cannot change the theme from any other place inside our activity apart from onCreate(). If we want to set it inside our activity but outside the onCreate() method then we have to call the recreate() function to recreate the whole activity which will implement the selected theme.Let us look at the example.

public class MyActivity extends AppCompatActivity {

 public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      if (savedInstanceState == null) {

          // Set the local night mode to some value

          getDelegate().setLocalNightMode(

                  AppCompatDelegate.MODE_NIGHT_...);

          // Now recreate for it to take effect

          recreate();

      }

  }

}

To take care of the text colors in our app we can set textColor attribute as

?android:attr/textColorPrimary

Now let us look at the implementation in Susi Android

In Susi Android we are providing user the option to select either the dark or the light theme in the settings.

 
The code for the implementation is as below

@Override

protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);



  prefs = getSharedPreferences(Constant.THEME, MODE_PRIVATE);

  if(prefs.getString(Constant.THEME,"Dark").equals("Dark")) {

      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);

  }

  else {

      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

  }



  setContentView(R.layout.activity_main);

}

The result output for the light theme is

To learn more about themes in Android you can refer to this link.

Resources

Continue ReadingUsing Day Night Theme in SUSI Android

Addition of Bookmark Icon in Schedule ViewHolder in Open Event Android App

In the Open Event Android app we only had a list of sessions in the schedule page without  the ability to bookmark the session unless we went into the SessionDetailPage or visited the session list via the tracks page or the locations page. This was obviously very inconvenient. There were several iterations of UI design for the same. Taking cues from the Google I/O 17 App I thought that the addition of the Bookmark Icon in the Schedule ViewHolder would be helpful to the user. In this blog post I will be talking about how this feature was implemented.

Layout Implementation for the Bookmark Icon

<ImageButton
    android:id="@+id/slot_bookmark"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:tint="@color/black"
    android:background="?attr/selectableItemBackgroundBorderless"
    android:contentDescription="@string/session_bookmark_status"
    android:padding="@dimen/padding_small"
    app:srcCompat="@drawable/ic_bookmark_border_white_24dp" />

The bookmark Icon was modelled as an ImageButton inside the item_schedule.xml file which serves as the layout file for the DayScheduleViewHolder.

Bookmark Icon Functionality in DayScheduleAdapter

The Bookmark Icon had mainly 3 roles :

  1. Add the session to the list of bookmarks (obviously)
  2. Generate the notification giving out the bookmarked session details.
  3. Generate a Snackbar if the icon was un-clicked which allowed the user to restore the bookmarked status of the session.
  4. Update the bookmarks widget.

Now we will be seeing how was all this done. Some of this was already done previously in the SessionListAdapter. We just had to modify some of the code to get our desired result.

       Session not bookmarked                      Session bookmarked                      

First we just set a different icon to highlight the Bookmarked and the un-bookmarked status. This code snippet highlights how this is done.

if(session.isBookmarked()) {
    slot_bookmark.setImageResource(R.drawable.ic_bookmark_white_24dp);
 } else {
 slot_bookmark.setImageResource(R.drawable.ic_bookmark_border_white_24dp);
 }
 slot_bookmark.setColorFilter(storedColor,PorterDuff.Mode.SRC_ATOP);

We check if the session is bookmarked by calling a function isBookmarked() and choose one of the 2 bookmark icons depending upon the bookmark status.

If a session was found out to be bookmarked and the Bookmark Icon was we use the WidgetUpdater.updateWidget() function to remove that particular session from the  Bookmark Widget of the app. During this a  Snackbar is also generated “Bookmark Removed” with an UNDO option which is functional.

realmRepo.setBookmark(sessionId, false).subscribe();
 slot_bookmark.setImageResource(R.drawable.ic_bookmark_border_white_24dp);
 
 if ("MainActivity".equals(context.getClass().getSimpleName())) {
    Snackbar.make(slot_content, R.string.removed_bookmark, Snackbar.LENGTH_LONG)
            .setAction(R.string.undo, view -> {
 
                realmRepo.setBookmark(sessionId, true).subscribe();
                slot_bookmark.setImageResource(R.drawable.ic_bookmark_white_24dp);
 
                WidgetUpdater.updateWidget(context);
            }).show();

else {
    Snackbar.make(slot_content, R.string.removed_bookmark, Snackbar.LENGTH_SHORT).show();
 }

If a session wasn’t bookmarked earlier but the Bookmark Icon was clicked we would firstly need to update the bookmark status within our local Realm Database.

realmRepo.setBookmark(sessionId, true).subscribe();

We would also create a notification to notify the user.

NotificationUtil.createNotification(session, context).subscribe(
        () -> Snackbar.make(slot_content,
                R.string.added_bookmark,
                Snackbar.LENGTH_SHORT)
                .show(),
        throwable -> Snackbar.make(slot_content,
                R.string.error_create_notification,
                Snackbar.LENGTH_LONG).show());

The static class Notification Util is responsible for the generation of notifications. The internal working of that class is not necessary right now. What this snippet of code does is that It creates a Snackbar upon successful notification with the text “Bookmark Added” and if any error occurs a Snackbar with the text “Error Creating Notification” is generated.

slot_bookmark.setImageResource(R.drawable.ic_bookmark_white_24dp);
 slot_bookmark.setColorFilter(storedColor,PorterDuff.Mode.SRC_ATOP);

This snippet of code is responsible for the colors that are assigned to the Bookmark Icons for different tracks and this color is obtained in the following manner.

int storedColor = currentSession.getTrack().getColor()

So now we have successfully added the Bookmark Icon to the ScheduleViewHolder inside the schedule of the app.

Resources

Continue ReadingAddition of Bookmark Icon in Schedule ViewHolder in Open Event Android App

Create a Distance Sensor using PSLab

PSLab device is a small lab which supports a ton of features. Among its many features, integrating a distance measuring sensor like HC SR04 sonar sensor into it is one of them. This blog post will bring out the basic concepts behind a sonar sensor available in the current market, how it measures distance and how it is implemented in the PSLab device.

A sonar sensor uses a sound wave with a very high frequency. These waves are called ultrasonic waves. They cannot be heard by the naked ear. Human ear can only hear frequencies from 20 Hz up to 20 kHz. Generally HC SR04 sensors use a wave with frequency as high as 40 kHz so this makes sense. The basic principal behind the sensor is the reflectance property of sound. Time is calculated from the transmission time up to the time receiving the reflected sound wave. Then using general moment equation S = ut; with the use of speed of sound, the distance can be measured.

The figure shows a HC SR04 ultrasound sensor. They are quiet famous in the electronic field; especially among hobbyists in making simple robots and DIY projects. They can be easily configured to measure distance from the sensor up to 400 cm with a measuring angle of 15 degrees. This angular measurement comes into action with the fact that sound travels through a medium in a spherical nature. This sensor will not give accurate measurements when used for scenarios like measuring distance to very thin objects as they reflect sound poorly or there will not be any reflectance at all.

There are four pins in the HC SR04 sonar sensor. Corner pins in the two sides are for powering up the Sonar sensor. The two pins named ECHO and TRIG pins are the important pins in this context. When the TRIG pin (Trigger for short) is excited with a set of 8 square pulses at a rate of 40 kHz, the ECHO pin will reach to logic HIGH state which is the supply voltage (+5 V). When the transmitted sound wave is reflected back to the sensor, this high state of the ECHO pin will shift to logic LOW state. If a timer is turned on when the ECHO pin goes to logic HIGH state, we can measure how long it was taken for the sound beam to return to the sensor by turning off the timer when the ECHO pin goes to logic LOW state.

Having described the general implementation of a sonar sensor; a similar implementation is available in PSLab device. As mentioned earlier, TRIG pin requires a triggering pulse of 8 set of square waves at 40 kHz. This is achieved in PSLab using SQR pulse generating pins. The time is measured from the transmitting point until the receiving point to evaluate the distance. The real distance to the obstacle in front of the sensor can be calculated using following steps;

  1. Measure total round trip time of the sound beam. Take it as t
  2. Calculate the time taken for the beam to travel from sensor to the obstacle. It will be t/2
  3. Use motion equation S = ut to calculate the actual distance taking u = speed of sound in air. Substituting the time value calculated in step 2 to t, S will produce the distance

Resources:

Continue ReadingCreate a Distance Sensor using PSLab

Enabling Live Streaming of Sessions in the Open Event Android App

The Open Event Android App had no option for viewing session videos if the links for them were provided by the event organiser. This post walks through how viewing of session videos was made possible through use of implicit intents which launched the Youtube app if the video link was a Youtube link and what all possible cases were taken into account so as to provide the user to view the video of a session as described below:

What is the current status of the app?

The current SessionDetailActivity.java containing the detail of the sessions of the event looks like this:

Adding Live Streaming option in the app

A live streaming feature is added in the app which enables the user to view the session. Now there were certain edge cases which needed to be handled:

  • No video links provided in the sessions json file

In that case the SessionDetailActivity.java looked the way it looks above as there is no way we can enable the live streaming option as the live video links aren’t provided by the event organiser.

  • The video links are provided but are not Youtube links

In that case the SessionDetailActivity.java looks like this, where the card view has a grey background showing that the user will be directed to the required link on a click.

  • The video links are Youtube links

In that case the Youtube thumbnail is fetched through Picasso and is made as the card view background. The SessionDetailActivity.java looks like this in such a case:

First the link is checked whether it is a Youtube link or not as illustrated in the code snippet below:

if(!Utils.isEmpty(video_link)) {
    playButton.setVisibility(View.VISIBLE);

    if(video_link.contains(ConstantStrings.YOUTUBE)) {

        Picasso.with(this)
               .load(youtubeLink)
               .into(youtubeThumbnail);
    
        youtubeThumbnail.setVisibility(View.VISIBLE);
    }

}

After the link is guaranteed as a Youtube link the play icon click is handled. On clicking the play icon, the user is directed to a Youtube app for the viewing of a session through an implicit intent using this piece of code:

playButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(video_link)));

    }

});

Thus the user is given an option to view the live streaming of a session, if the video links are provided by the event organiser.

Related Links:

Continue ReadingEnabling Live Streaming of Sessions in the Open Event Android App

Documenting APIs with Yaydoc

API Documentation is a quick and concise way to tell a user about how to use a library or work with a program. It details classes, functions, parameters, return types and more. Courtesy of Sphinx, Yaydoc had build in support for Documenting APIs for Python based projects right from it’s inception. Sphinx has a built in tool autodoc which provides certain directives such as autoclass, automodule, etc which can be used to automatically extract docstrings from all specified Python packages and modules and use it to generate API documentation. As a user of Yaydoc you could add ReST sources files with appropriate directives provided by autodoc and we would handle the rest. As part of enhancing this feature we wanted to do three things.

  • Enhance support for Python
  • Extend API documentation to other languages apart from Python
  • Automate the process of generating ReST source files

For Enhancing support for python projects, we implemented a few things.

Since autodoc imports the modules it needs to document, There could be import errors if a dependency was not met. To fix this issue, Now a user can specify certain modules to be mocked. This would really come in handy with projects depending on packages with third party C extensions such as numpy, scipy, etc.

{% if mock_modules %}
mock_modules = [name.strip() for name in '{{ mock_modules }}'.split(',')]
sys.modules.update((mod_name, mock.Mock()) for mod_name in mock_modules)
{% endif %}

Apart from this, if we detect a setup.py in the repository or a requirements.txt, we automatically try to install from it to meet dependencies.

# autodoc imports the module while building source files. To avoid
# ImportError, install any packages in requirements.txt of the project
# if available
if [ -f $ROOT_DIR/setup.py ]; then
  pip install $ROOT_DIR/
elif [ -f $ROOT_DIR/requirements.txt ]; then
  pip install -q -r $ROOT_DIR/requirements.txt
fi

We also crawl the repository to detect any packages and add them to sys.path. With these changes, a user can expected generated API docs without having to extend conf.py.

{% if autoapi_python == 'true' %}
for (dirpath, dirnames, filenames) in os.walk('{{ root_dir }}'):
    # Directory contains __init__.py. It should be a python package
    if '__init__.py' in filenames:
        # appending instead of inserting at front so that user
        # cannot overwrite some of our own modules.
        sys.path.append(os.path.abspath(os.path.dirname(dirpath)))
{% endif %}

The second goal is a no brainer. We would like to support as many languages as we can. With this week’s update, Java has been added to the officially supported list of languages for which Yaydoc can generate full API documentation without any manual intervention. To extract API documentation for java source files, we used a sphinx extension named javasphinx. From the official javasphinx docs,

javasphinx is a Sphinx extension that provides a Sphinx domain for documenting Java projects and a javasphinx-apidoc command line tool for automatically generating API documentation from existing Java source code and Javadoc documentation.

javasphinx-apidoc -o source/ $ROOT_DIR/$AUTOAPI_JAVA_PATH/
sphinx-apidoc -o source/ $ROOT_DIR/$AUTOAPI_PYTHON_PATH/

For the third goal, we use the tools sphinx-apidoc and javasphinx-apidoc to generate source files.

Resources

Continue ReadingDocumenting APIs with Yaydoc

Save Server Response to File Using Python in Open Event Android App Generator

The Open Event Android project helps event organizers to generate Apps (apk format) using Open Event App generator for their events/conferences by providing API endpoint or zip generated using Open Event server.

The Open Event Android project has an assets folder which contains sample JSON files for the event, which are used to load the data when there is no Internet connection. When an organizer generates an app with the help of an API endpoint, then all the assets, e.g. images, are removed and because of it generated don’t have sample JSON files. So if the device is offline then it will not load the data from the assets (issue #1606). The app should contain sample event JSON files and should be able to load the data without the Internet connection.

One solution to this problem is to fetch all the event data (JSON files) from the server and save it to the assets folder while generating the app using Open Event App generator. So in this blog post, I explain how to make a simple request using Python and save the response in a file.

Making a simple request

To fetch the data we need to make a request to the server and the server will return the response for that request. Here’s step to make a simple request,

Import Requests module using,

import requests

The requests module has get, post, put, delete, head, options to make a request. Example:

requests.get(self.api_link + '/' + end_point)

Here all method returns requests.Response object. We can get all the information we need from this object.

So we can make response object like this,

response = requests.get(self.api_link + '/' + end_point)

Saving response in a file

For saving response in a file we need to open/create a file for writing.

Create or open file

The open() method is used for opening file. It takes two arguments one is file name and second in access mode which determines the mode in which the file has to be opened, i.e., read, write, append, etc.

file = open(path/to/the/file, "w+")

Here “w+” overwrites the existing file if the file exists. If the file does not exist, it creates a new file for reading and writing.

Write and close file

Now write the content of the response using the write() method of file object then close the file object using the close()  method. The close() method flushes any unwritten information and closes the file object.

file.write(response.text)
file.close()

Here response.text gives the content of the response in Unicode format.

Conclusion

The requests.Response object contains much more data like encoding, status_code, headers etc. For more info about request and response refer additional resources given below.

Additional Resources

Continue ReadingSave Server Response to File Using Python in Open Event Android App Generator

JSON Deserialization Using Jackson in Open Event Android App

The Open Event project uses JSON format for transferring event information like tracks, sessions, microlocations and other. The event exported in the zip format from the Open Event server also contains the data in JSON format. The Open Event Android application uses this JSON data. Before we use this data in the app, we have to parse the data to get Java objects that can be used for populating views. Deserialization is the process of converting JSON data to Java objects. In this post I explain how to deserialize JSON data using Jackson.

1. Add dependency

In order to use Jackson in your app add following dependencies in your app module’s build.gradle file.

dependencies {
	compile 'com.fasterxml.jackson.core:jackson-core:2.8.9'
	compile 'com.fasterxml.jackson.core:jackson-annotations:2.8.9'
	compile 'com.fasterxml.jackson.core:jackson-databind:2.8.9'
}

2.  Define entity model of data

In the Open Event Android we have so many models like event, session, track, microlocation, speaker etc. Here i am only defining track model because of it’s simplicity and less complexity.

public class Track {

	private int id;
	private String name;
	private String description;
	private String color;
	@JsonProperty("font-color")       
	private String fontColor;
    
	//getters and setters
}

Here if the property name is same as json attribute key then no need to add JsonProperty annotation like we have done for id, name color property. But if property name is different from json attribute key then it is necessary to add JsonProperty annotation.

3.  Create sample JSON data

Let’s create sample JSON format data we want to deserialize.

{
        "id": 273,
        "name": "Android",
        "description": "Sample track",
        "color": "#94868c",
        "font-color": "#000000"
}

4.  Deserialize using ObjectMapper

ObjectMapper is Jackson serializer/deserializer. ObjectMapper’s readValue() method is used for simple deserialization. It takes two parameters one is JSON data we want to deserialize and second is Model entity class. Create an ObjectMapper object and initialize it.

ObjectMapper objectMapper = new ObjectMapper();

Now create a Model entity object and initialize it with deserialized data from ObjectMapper’s readValue() method.

Track track = objectMapper.readValue(json, Track.class);

So we have converted JSON data into the Java object.

Jackson is very powerful library for JSON serialization and deserialization. To learn more about Jackson features follow the links given below.

Continue ReadingJSON Deserialization Using Jackson in Open Event Android App

Debugging JSON Files of Sample Events for Open Event Android using Stetho

In this blog, I will talk about data validation and debugging in Android using the Stetho-A debug bridge for Android by Facebook. Most Android applications have JSON files to populate the elements like RecyclerViews, ListViews and different types of Layouts. Stetho is a debug tool for Android which uses the well-known Chrome Developer tools as it’s User Interface. With Stetho, we can see all our incoming JSON data in spreadsheets making debugging much easier and fun. What’s more, it’s completely Open source.

Getting started with Stetho

To start with, we need to enable Stetho by adding it as one of the dependencies in the build.gradle file.

compile 'com.facebook.stetho:stetho:1.4.2'

It is already enabled in the Open Event Android app.

Now, you need to add the api endpoint for your sample in the config.json file in the project(if you are using the Android repo for debugging). The config.json file is at app/assets/

In case, you are using an Open Event generated app then there’s no need to do that.

Now connect your phone through the USB cable to your laptop and start your application.

Next, you have to browse to chrome://inspect where you will see your device in the window as shown below.

 

On clicking “Inspect”, you will be shown the Stetho debug tool interface. Something like this:

When you download the details by clicking “Yes” on the starting of the application, be sure to keep it connected to the Stetho tool in the ‘inspect’ mode.

Once the data has loaded, go to Web SQL-> default.realm. You will see tabs like:-

class_speaker, class_sponsor, class_session, class_track among others.

On clicking them, you will see well-organised tables that show all linked attributes of the class that you selected.

Sessions can be seen along with all the related information in a tabular format.

Stetho displays speakers of the event and their information in an easy-to-read tabular format.

Micro locations of the event along with related information in a tabular format.

This is how you can view all the attributes of your sample in a tabular layout and hence, debug them easily. Although, Stetho is about much more than this, this is all I will talk about in this blog.

You can read more about Stetho and it’s functionalities here.

The official repo for Stetho can be found here for the source code.

Continue ReadingDebugging JSON Files of Sample Events for Open Event Android using Stetho