Publish an Open Source app on Fdroid

Fdroid is a famous software repository hosted with numerous free and open source Android apps. They have a main repository where they allow developers hosting free and ad free software after a thorough check up on the app. This blog will tell you how to get your project hosted in their repository using steps I followed to publish the PSLab Android app.

Before you get started, make sure you have the consent from your developer community to publish their app on Fdroid. Fdroid requires your app to use all kind of open resources to implement features. If there is any closed source libraries in your app and you still want to publish it on Fdroid, you may have to reimplement that feature by any other mean without using closed source resources. They will also not allow to have Google’s proprietary “play-services” in your app along with proprietary ad services. You can find the complete inclusion policy document from their official page.

When your app is fully ready, you can get started with the inclusion procedure. Unlike how we are publishing apps on Google Play, publishing an app on Fdroid is as simple as sending a pull request to their main repository. That’s exactly what we have to do. In simple terms all we have to do is:

  1. Fork the Fdroid main data repository
  2. Make changes to their files to include our app
  3. Do a pull request

First of all you need a GitLab account as the Fdroid repository is hosted in GitLab. Once you are ready with a GitLab account, fork and clone the f-droid-data repository. The next step is to install the fdroid-server. This can be simply done using apt:

$ sudo apt install fdroidserver

 
Once that is done, go into the directory where you cloned the repository and run the following command to check if the initiation is complete.

$ fdroid init

 
Then run the following command to read current meta data where it saves all the information related to existing apps on Fdroid;

$ fdroid readmeta

 
This will list out various details about the current meta files. Next step is to add our app details into this meta file. This can be done easily using following command or you can manually create folders and files. But the following is safer;

$ fdroid import --url https://github.com/fossasia/pslab-android --subdir app

 
Replace the link to repository from the –url tag in the above command. For instance the following will be the link for fossasia-phimpme android;

$ fdroid import --url https://github.com/fossasia/phimpme-android --subdir app

 
This will create a file named as “org.fossasia.pslab” in the metadata directory. Open up this text file and we have to fill in our details.

  1. Categories
  2. License
  3. Web Site
  4. Summary
  5. Description

Description needs to be terminated with a newline and a dot to avoid build failures.

Once the file is filled up, run the following command to make sure that the metadata file is complete.

$ fdroid readmeta

 
Then run the following command to clean up the file

$ fdroid rewritemeta org.fossasia.pslab

 
We can automatically add version details using the following command:

$ fdroid checkupdates org.fossasia.pslab

 
Now run the lint test to see if the app is building correctly.

$ fdroid lint org.fossasia.pslab

 
If there are any errors thrown, fix them to get to the next step where we actually build the app:

$ fdroid build -v -l org.fossasia.pslab

 
Now you are ready to make the pull request which will then get reviewed by developers in Fdroid community to get it merged into their main branch. Make a commit and then push to your fork. From there it is pretty straightforward to make a pull request to the main repository. Once that is done, they will test the app for any insecurities. If all of them are passed, the app will be available in Fdroid!

Reference:

  1. Quick Start: https://gitlab.com/fdroid/fdroiddata/blob/master/README.md#quickstart
  2. Making merge requests: https://gitlab.com/fdroid/fdroiddata/blob/master/CONTRIBUTING.md#merge-requests

Continue ReadingPublish an Open Source app on Fdroid

Implementing Clickable Images

PSLab Android application is a feature rich compact app to user interface the PSLab hardware device. Similarly the PSLab device itself is a compact device with a plenty of features to replace almost all the analytical instruments in a school science lab. When a first time user takes the device and connect it with the Android app, there are so many pins labeled with abbreviations. This creates lots of complications unless the user checks the pinout diagram separately.

As a workaround a UI is proposed to integrate a layout containing the PSLab PCB image where user can click on each pin to get a dialog box explaining him what that specific pin is and what it does. This implementation can be done it two ways;

  • Using an Image map
  • Using (x,y) coordinates

The first implementation is more practical and can be applied with any device with any dimension. The latter requires some transformation to capture the correct position when user has clicked on a pin. So the first method will be implemented.

The idea behind using an image map is to have two images with exact dimensions on top of each other. The topmost image will be the color map which we create ourselves using unique colors at unique heat points. This image will have the visibility setting invisible as the main idea is to let the  user see a meaningful image and capture the positions using a secondary in the back end.

To make things much clear, let’s have a look at a color map image I am suggesting here for a general case.

If we overlap the color map with the PSLab layout, we will be able to detect where user has clicked using Android onTouchEvent.

@Override
public boolean onTouchEvent(MotionEvent ev) {
   final int action = ev.getAction();
   final int evX = (int) ev.getX();
   final int evY = (int) ev.getY();
   switch (action) {
       case MotionEvent.ACTION_UP :
         int touchColor = getHotspotColor (R.id.backgroundMap, evX, evY);
         /* Display the relevant pin description dialog box here */
         break;
   }
   return true;
}

 
Color of the clicked position can be captured using the following code;

public int getHotspotColor (int hotspotId, int x, int y) {
   ImageView img = (ImageView) findViewById (hotspotId);
   img.setDrawingCacheEnabled(true);
   Bitmap hotspots = Bitmap.createBitmap(img.getDrawingCache());
   img.setDrawingCacheEnabled(false);
   return hotspots.getPixel(x, y);
}

 
If we go into details, from the onTouchEvent we capture the (x,y) coordinates related to user click. Then this location is looked up for a unique color by creating a temporary bitmap and then getting the pixel value at the captured coordinate.

There is an error in this method as the height parameter always have an offset. This offset is introduced by the status bar and the action bar of the application. If we use this method directly, there will be an exception thrown out saying image height is less than the height defined by y.

Solving this issue involves calculating status bar and actionbar heights separately and then subtract them from the y coordinate.

Actionbar and status bar heights can be calculated as follows;

Rect rectangle = new Rect();
Window window = getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
int statusBarHeight = rectangle.top;
int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight= contentViewTop - statusBarHeight;

 
Using them, we can modify the captured coordinates as follows;

int touchColor = getHotspotColor (R.id.imageArea, evX, evY - statusBarHeight);

 
This way the exception is handled by adjusting the cursor position. Once this is done, it is all about displaying the correct pin description dialog box.

Reference:

Calculate status bar height: https://stackoverflow.com/questions/3407256/height-of-status-bar-in-android

Continue ReadingImplementing Clickable Images

Making Shapes with PSLab Oscilloscope

Looking back to history, the first ever video game was ‘Pong’ which was played on an analog oscilloscope with a very small screen. Oscilloscopes are not made to play video games, but by just tinkering around its basic functionality which is display waveforms, we can do plenty of cool things. PSLab device also has an oscilloscope; in fact it’s a four channel oscilloscope.

This blog post will show you how the oscilloscope in PSLab is not just a cheap oscilloscope but it has lots of functionalities an industry grade oscilloscope has (except for the bandwidth limitation to a maximum of 2 MHz)

To produce shapes like above figures, we are using another instrument available in PSLab. That is ‘Waveform Generator’. PSLab Waveform Generator can generate three different waveforms namely Sine waves, Triangular waves and Square waves ranging from 5 Hz to 5 kHz.

To get started, first connect two jumper wires between SI1-CH1 and SI2-CH2 pins. We needn’t worry about ground pins as they are already internally connected. Now it’s time to open up the PSLab oscilloscope. Here we are going to utilize two channels for this activity and they will be CH1 and CH2. Check the tick boxes in front of ‘Chan 1’ and ‘Chan 2’ and set ‘Range’ to “+/-4V” to have the maximum visibility filling the whole screen with the waveform.

The shapes are drawn using a special mode called ‘X-Y Mode’ in PSLab oscilloscope. In this mode, two channels will be plotted against their amplitudes at every point in time.

As it is already mentioned that PSLab can generate many waveform types and also they can have different phase angles relative to each other. They can have different independent frequencies. With all these combinations, we can tweak the settings in Waveform Generator to produce different cool shapes in PSLab oscilloscope.

These shapes can vary from basic geometric shapes such as circle, square, rectangle to complicated shapes such as rhombus, ellipse and polynomial curves.

Circle

A circular shape can be made by generating two sine waves having the same frequency but with a phase difference of 90 degrees or 270 degrees between the two wave forms.

 

 
 

 


Square

Square shape can be made by generating two triangular waveforms again having the same frequency but with a phase difference of either 90 degrees or 270 degrees between the two.

 

 

 
 


Rectangle

Similar to creating a Square, by having the same frequency for both triangular waveforms but a different phase angle greater than or less than 90 degree will do the trick.

 

 

 
 


Rhombus

Keeping the waveform settings same for the rectangle, by changing the amplitude of the SI1 waveform using the knob we can generate a rhombic shape on the XY graph plot.

 

 

 
 


Ellipse

Generating ellipse is also similar to creating a rhombus. But here we are using sine waves instead of triangular waves. By changing the amplitude of SI1 using the knob we can change the curvature.

 

 

 


Helix

Helix or spiral shape can be generated using two sine waves having same phase but two different frequencies. Frequencies better be integer multiples of the smaller frequency to  have a steady shape.

 

 

 


Parabola

Parabolic shapes can be generated by mixing up triangular waves with sine waves with different phase angles.

 

 

 

 
 

More random shapes


References:

https://www.aps.org/publications/apsnews/200810/physicshistory.cfm

Continue ReadingMaking Shapes with PSLab Oscilloscope

How to get a cost effective PCB for Production

Designing a PCB for a DIY project involves in making up the schematics which then turned into a PCB layout. Components used in these PCBs will be mostly “Through Hole” which are commonly available in the market. Once the PCB is printed in either screen printing techniques or using photo resistive dry films, making alterations to the component mounting pads and connections will be somewhat possible.

When dealing with a professional PCB design, there are many properties we need to consider. DIY PCBs will simply be single sided in most cases. A professional printed circuit board will most likely to have more than one layer. The PCB for PSLab device has 4 layers. Adding more layers to a PCB design makes it easier to draw connections. But on the other hand, the cost will increase exponentially. The designer must try to optimize the design to have less layers as much as possible. The following table shows the estimated cost for printing for 10 PSLab devices if the device had that many layers.

One Layer Two Layers Four Layers Six Layers
$4.90 $4.90 $49.90 $305.92

Once the layer levels increase from 2, the other layers will be inner layers. The effective area of inner layers will be reduced if the designer adds more through hole components or vias which connects a connection from a one layer with a connection with another layer. The components used will then be limited to surface mount components.

Surface Mount components (SMD) are expensive compared to their Through Hole (TH) counterpart. But the smaller size of SMD makes it easier to place many components in a smaller area than to Through Hole components. Soldering and assembling Through Hole components can be done manually using hand soldering techniques. SMD components need special tools and soldering equipments to assemble and solder them. Much more precision is required when SMD components are soldered. Hence automated assembly is used in industry where robot arms are used to place components and reflow soldering techniques to solder the SMD components. This emphasizes that the number of SMD components used in the PCB will increase the assembly cost as well as the component cost but it will greatly reduce the size of the PCB.

SMD components comes in different packages. Passive components such as resistors, capacitors will come in 0.25 mm upto 7.4mm dimensions. PSLab device uses 0805/2012 sized package which is easier to find in the market and big enough to pick and assemble by hand. The packaging refers to its dimensions. 0805 reads as 0.08 inches long and 0.05 inches wide.

Finding the components in the market is the next challenging task. We can easily purchase components from an online store but the price will be pretty high. If the design can spare some space, it will be wise to have alternative pads for a Through Hole component for the SMD component as Through Hole components can be found much easier than SMD components in a local store.

The following image is taken from Sparkfun which illustrates different common IC packages. Selecting the correct footprint for the SMD IC and vise versa is very important. It is a good practice to check the stores for the availability and prices for the components before finalizing the PCB design with footprints and sending it to printing. We may find some ICs are not available for immediate purchase as the stocks ran out but a different package of the same IC is available. Then the designer can alter the foot print to the packaging and use the more common packaging type in the design.

Considering all the factors above, a cost effective PCB can be designed and manufactured once the design is optimized to have the minimum number of layers with components with the minimum cost for both assembly and components.

Resources:

Continue ReadingHow to get a cost effective PCB for Production

Creating Bill of Materials for PSLab using KiCAD

PSLab device consists of a hundreds of electronic components. Resistors, diodes, transistors, integrated circuits are to name a few. These components are of two types; Through hole and surface mounted.

Surface mount components (SMD) are smaller in size. Due to this reason, it is hard to hand solder these components onto a printed circuit board. We use wave soldering or reflow soldering to connect them with a circuit.

Through Hole components (TH) are fairly larger than their SMD counter part. They are made bigger to make it easy for hand soldering. These components can also be soldered using wave soldering.

Once a PCB has completed its design, the next step is to manufacture it with the help of a PCB manufacturer. They will require the circuit design in “gerber” format along with its Bill of Materials (BoM) for assembly. The common requirement of BoM is the file in a csv format. Some manufacturers will require the file in xml format. There are many plugins available in KiCAD which does the job.

KiCAD when first installed, doesn’t come configured with a BoM generation tool. But there are many scripts developed with python available online free of charge. KiBoM is one of the famous plugins available for the task.

Go to “Eeschema” editor in KiCAD where the schematic is present and then click on the “BoM” icon in the menu bar. This will open a dialog box to select which plugin to use to generate the bill of materials.

Initially there won’t be any plugins available in the “Plugins” section. As we are adding plugins to it, they will be listed down so that we can select which plugin we need. To add a plugin, click on the “Add Plugin” button to open the dialog box to browse to the specific plugin we have already downloaded. There are a set of available plugins in the KiCAD installation directory.

The path is most probably will be (unless you have made any changes to the installation);

usr/lib/kicad/plugins

Once a plugin is selected, click on “Generate” button to generate the bom file. “Plugin Info” will display where the file was made and it’s name.

Make sure we have made the BoM file compatible to the file required by the manufacturer. That is; removed all the extra content and added necessary details such as manufacturer’s part numbers and references replacing the auto generated part numbers.

Resources:

Continue ReadingCreating Bill of Materials for PSLab using KiCAD

KiCAD Simulation to Validate Circuitry in PSLab Device

A circuit is a combination of passive or active electronic components which are interconnected with wires and provided to power to perform a specific task. Bringing a conceptual circuit design into an actual model includes several steps. It all starts with a problem definition such as a “Power module to regulate input voltage to output 5V”. The next step is to design the schematic with the help of a designing tool. Once the schematic is complete, the PCB layout can be made which will be later printed out as the final circuit.

The importance of testing the schematic circuit for performance and functionalities is very important as once the circuit is printed out, there is no way to modify the wiring or components. That is when the SPICE simulation comes into picture.

PSLab device is consisted of hundreds of circuit components and they are interconnected using a 4 layer printed circuit board. A fault in one sub circuitry may fail the complete device. Hence each of them must be tested and simulated using proper tools to ensure functionality against a test input data set.

KiCAD requires an external SPICE engine to be installed. Ngspice is a famous SPICE tool used in the industry.

The test procedures carried out to ensure the circuitry functions in PSLab device is described in this blog. Once the circuit is complete, generate the spice netlist. This will open up a dialog box and in the “Spice” tab, select “Prefix references ‘U’ and ‘IC’ with ‘X’”.

U and IC prefixes are used with chips which cannot be simulated with SPICE. Click “Generate” to build the netlist. Note that this is not the netlist we use to build up the PCB but a netlist which can be used in SPICE simulation.

Now browse to the project folder and rename the file extension of cir to cki to make them compatible with command line SPICE commands.

cp <filename>.cir <filename>.cki

Then open the file using a text editor and modify the GND connection to have a global ground connection by replacing “GND” with “0” which is required in SPICE simulation. Once the SPICE code is complete run the following commands to get the SPICE script compiled;

export SPICE_ASCIIRAWFILE=1
ngspice -b -r <filename>.raw <filename>.cki
ngnutmeg SPIce.raw

This will open up a data analysis and manipulation program provided with ngspice to plot graphs and analyse SPICE simulations. Using this we can verify if the circuit can produce expected outputs with respect to the inputs we are providing and make adjustments if necessary.

Resource:

Continue ReadingKiCAD Simulation to Validate Circuitry in PSLab Device

Creating an Installer for PSLab Desktop App

PSLab device is made useful with applications running on two platforms. One is Android and the other one is a desktop application developed using Python frameworks. Desktop application uses half a dozen of dependent libraries and they are required to be installed prior to installing the application itself.

For someone with zero or less knowledge on how to install packages in a Linux environment, this task will be quite difficult. To ease up the process of installing the desktop application in a computer, we can use a script to run specific commands which will install the dependencies and the application.

Dependencies required by PSLab  Desktop app

  • PyQt 4.7
  • Python 2.6, 2.7 or 3.x
  • NumPy, Scipy
  • pyqt4-dev-tools
  • Pyqtgraph
  • pyopengl and qt-opengl
  • iPython-qtconsole

These dependencies can be made installed using a bash script running with root permission. A bash script will have the file extension “.sh” and a header line;

#!/bin/bash

A bash script needs to be made executable by the user himself. To do this, user needs to type a one line command in the terminal as follows and enter his password;

sudo chmod +x <Name_of_the_script>.sh

The keyword “sudo” interprets as “Super User DO” and the line follows will be executed with root permission. In other words with administrative privileges to modify system settings such as copying content to system folders.

The keyword “chmod” stands for “Change Mode” which will alter the mode of a file. In current context, the file is made executable by adding the executable property to the bash script using “+x” syntax.

Once the script is made executable, it can be executed using;

sudo ./<Name_of_the_script>.sh

An installer can be made attractive by using different colors rather than the plain old text outputs. For this purpose we can use color syntax in bash script. They are represented using ANSI escape codes and following is a list of commonly used colors;

Black        0;30     Dark Gray     1;30
Red          0;31     Light Red     1;31
Green        0;32     Light Green   1;32
Brown/Orange 0;33     Yellow        1;33
Blue         0;34     Light Blue    1;34
Purple       0;35     Light Purple  1;35
Cyan         0;36     Light Cyan    1;36
Light Gray   0;37     White         1;37

As in any programming language, rather than using the same line in many places, we can define variables in a bash script. The syntax will be the variable name followed by an equal sign with the value. There cannot be spaces around the equal sign or it will generate an error.

GREEN='\033[0;32m'

These variables can be accessed using a special syntax as follows;

${GREEN}

Finally we can output a message to the console using the “echo” command

echo -e "${GREEN}Welcome to PSLab Desktop app installer${NOCOLOR}"

Note that the keyword “-e” is used to enable interpretation of the following backslash escapes.

In order to install the packages and libraries, we use two package management tools. One is “apt” which stands for “Advanced Packaging Tool” and the second is “pip” which is used to download python related packages from “Python Package Index”. The following two lines illustrates how the two commands can be accessed.

apt-get install python-pip python-dev build-essential -y

pip install pyqtgraph

The keyword “-y” avoids the confirmation prompt in console to allow installation by pressing “Y” key every time it installs a package from “apt”.

Resources:

Continue ReadingCreating an Installer for PSLab Desktop App

Creating Custom Borders for Widgets and Layouts in PSLab Android

User Interface (UI) is one of the most important part of any software development. In PSLab Android App while developing the UI, custom borders are used for various widgets and layouts. This makes the UI look more appealing and widgets and layouts look more highlighted.

In Android, we can do a range of border customization. We can make border rounded, define its thickness and even change its color. Let’s see how to achieve this.

First, go to drawable folder in the tree view on the left size of the Android studio. Then go to new and click on Drawable resource file.

Then a New Resource File dialog box will appear. Type the filename and then click OK.

After this, a new XML file is created. Now we can write the code for creating custom borders. For this, we have to define few elements.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
....
</shape>

Shape Drawables allows defining background, borders, and gradients for the Views.

<solid android:color="#FFFFFF"/>

Here we are setting the background color of the widget/layout to which the border is applied to.

<stroke android:width="3dip" android:color="#B1BCBE" />

Now we are applying the 3dip width to the border and set its color. This shape requires the <stroke> element to define the width and color of the line.

<corners android:radius="10dip"/>

In order to make the corners of the border round, <corner> element is used to define the radius of the corners. We are taking it to be 10dip.

<padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />

The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding is used to offset the content of the view by a specific number of pixels.

After applying this border on a layout we get the following results.

Similarly making following changes in the element values help us to make border for the Text View

<solid android:color="@android:color/white" />
<stroke android:width="1dip" android:color="#ffcdd2" />
<corners android:radius="2dp"/>

Other examples

Control Activity

Logical Analyzer Activity

Resources

  1. Stack Overflow Solution to How to make a layout with rounded corners?
  2. Youtube Video on How to create a layout with rounded corner borders in Android? by Sylvain Saurel
Continue ReadingCreating Custom Borders for Widgets and Layouts in PSLab Android

User Guide for the PSLab Remote-Access Framework

The remote-lab framework of the pocket science lab has been designed to enable user to access their devices remotely via the internet. The pslab-remote repository includes an API server built with Python-Flask and a webapp that uses EmberJS. This post is a guide for users who wish to test the framework. A series of blog posts have been previously written which have explored and elaborated various aspect of the remote-lab such as designing the API server, remote execution of function strings, automatic deployment on various domains etc. In this post, we shall explore how to execute function strings, execute example scripts, and write a script ourselves.

A live demo is hosted at pslab-remote.surge.sh . The API server is hosted at pslab-stage.herokuapp.com, and an API reference which is being developed can be accessed at pslab-stage.herokuapp.com/apidocs . A screencast of the remote lab is also available

Create an account

Signing up at this point is very straightforward, and does not include any third party verification tools since the framework is under active development, and cannot be claimed to be ready for release yet.

Click on the sign-up button, and provide a username, email, and password. The e-mail will be used as the login-id, and needs to be unique.

Login to the remote lab

Use the email-id used for signing up, enter the password, and the app will redirect you to your new home-page, where you will be greeted with a similar screen.

Your home-page

On the home-page, you will find that the first section includes a text box for entering a function string, and an execute button. Here, you can enter any valid PSLab function such as `get_resistance()` , and click on the execute button in order to run the function on the PSLab device connected to the API server, and view the results. A detailed blog post on this process can be found here.

Since this is a new account, no saved scripts are present in the Your Scripts section. We will come to that shortly, but for now, there are some pre-written example scripts that will let you test them as well as view their source code in order to copy into your own collection, and modify them.

Click on the play icon next to `multimeter.py` in order to run the script. The eye icon to the right of the row enables you to view the source code, but this can also be done while the app is running. The multimeter app looks something like this, and you can click on the various buttons to try them out.

You may also click on the Source Code tab in order to view the source

Create and execute a small python script

We can now try to create a simple script of our own. Click on the `New Python Script` button in the top-bar to navigate to a page that will allow you to create and save your own scripts. We shall write a small 3-line code to print some sinusoidal coordinates, save it, and test it. Copy the following code for a sine wave with 30 points, and publish your script.

import numpy as np
x=np.linspace(0,2*np.pi,30)
print (x, np.sin(x))

Create a button widget and associate a callback to the get_voltage function

A small degree of object oriented capabilities have also been added, and the pslab-remote allows you to create button widgets and associate their targets with other widgets and labels.
The multimeter demo script uses this feature, and a single line of code suffices to demonstrate this feature.

button('Voltage on CH1 >',"get_voltage('CH1')","display_number")

You can copy the above line into a new script in order to try it out.

Associate a button’s callback to the capture routines, and set the target as a plot

The callback target for a button can be set to point to a plot. This is useful if the callback involves arrays such as those returned by the capture routines.

Example code to show a sine wave in a plot, and make button which will replace it with captured data from the oscilloscope:

import numpy as np
x=np.linspace(0,2*np.pi,30)
plt = plot(x, np.sin(x))
button('capture 1',"capture1('CH1',100,10)","update-plot",target=plt)
Figure: Demo animation from the plot_test example. Capture1 is connected to the plot shown.
Resources

Continue ReadingUser Guide for the PSLab Remote-Access Framework

Markdown Support for Experiment Docs in PSLab Android

The PSLab Android App and the PSLab Desktop App come with built-in experiments which include the experiment setups as well as the experiment docs. The experiment docs for PSLab have been written in the Markdown format. So, the markdown support had to be enabled in the PSLab Android App.

There are numerous markdown file renderers for android. The most popular among them is MarkdownView (https://github.com/falnatsheh/MarkdownView) which is an  open-source service.

This blog covers how to enable the support for markdown in apps and use to generate elegant documentation.

Enabling MarkdownView

MarkdownView can be enabled by simply adding a dependency in the build.gradle file

compile 'us.feras.mdv:markdownview:1.1.0'

 

Creating the layout file

The layout file for supporting a markdown file is fairly simple. The inclusion of the above dependency simplifies the things. The view holder for markdown is created and an id is assigned to it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

   <br.tiagohm.markdownview.MarkdownView
       android:layout_width="match_parent"
       app:escapeHtml="false"
       android:layout_height="match_parent"
       android:id="@+id/perform_experiment_md" />
</LinearLayout>

 

Loading the markdown file

In order to load the markdown file, a MarkdownView object is created. Since, in the PSLab Android app, markdown files which form the documentation part are a part of the experiments. So, the files are displayed in the documentation fragment of the experiments.

private String mdFile;
private MarkdownView mMarkdownView;

public static ExperimentDocFragment newInstance(String mdFile) {
   ExperimentDocFragment experimentDocFragment = new ExperimentDocFragment();
   experimentDocFragment.mdFile = mdFile;
   return experimentDocFragment;
}

 

The MarkdownView object created is assigned to markdown viewholder of the relevant layout file. Here, the layout file was named experiment_doc_md and the view holder was assigned the id perform_experiment_md. The markdown files were stored in the assets directory of the app and the files were loaded from the there.

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
   View view = inflater.inflate(R.layout.experiment_doc_md, container, false);
   mMarkdownView = (MarkdownView) view.findViewById(R.id.perform_experiment_md);
   mMarkdownView.loadMarkdownFromAsset("capacitance.md");
   return view;
}

 

The available methods in markdown view are

  • loadMarkdown – loads directly from the content in the string 

mMarkdownView.loadMarkdown("**MarkdownView**");

 

  • loadMarkdownFromAsset – loads markdown files located in the assets directory of the app

mMarkdownView.loadMarkdownFromAsset("markdown1.md");

 

  • loadMarkdownFromFile – loads markdown from a file stored in the app not present in the assets directory

mMarkdownView.loadMarkdownFromFile(new File());

 

  • loadMarkdownFromUrl – loads markdown from the specified URL (requires internet connection, as file is loaded from the web)

mMarkdownView.loadMarkdownFromUrl("url");

 

Important points for consideration

  • Avoid using elements of GitHub Flavoured Markdown (GFM) as it is not fully supported. It is better to stick to the traditional markdown style.
  • While adding images in the markdown files, avoid using specific dimensions as the images may not load properly in some cases due to the wide variety of screen sizes in android devices.
  • It is better to store the Markdown files to be loaded in the assets directory of the app and load it from there instead of the other methods mentioned above.

References

  1. A comprehensive markdown tutorial to learn markdown scripting https://www.markdowntutorial.com/
  2. MarkdownView repository on Github by tiagohm https://github.com/tiagohm/MarkdownView
  3. Learn more about Github Flavoured Markdown (GFM) https://guides.github.com/features/mastering-markdown/
Continue ReadingMarkdown Support for Experiment Docs in PSLab Android