How to display Math Formula and Equation in Android Application

How to display Math Formula and Equation in Android Application

I was recently working on updating my Complete Mathematics App. This is the first app I tried my hand on. Before then I have not work with android development but I knew little Java programming.

Since then I have not had chance to update the application. But the funny thing is that it has really showed me how much I have learnt about android in just two years.

One of the problem that I found myself trying to solve was how to display math formulas and equations perfectly. In my math android app, I used a software called MathType to write complex math equations and formulas and then save them as image. The problem with image is that it become pixelated and blurry when it is stretched. Due to differences in screen size. Another disadvantage is that it can increase the application size if you decides to save each image in four different sizes in order to take care of the different screen sizes in android.

If you have worked with science and math apps that require complex formulas and equations, you will understand that android had no provision or native support for this kind of thing.

There is an option to use Android built-in Html class but the problem is that it is limited to what it can do.

I also tried using a vector image that contains math equations and formulas – one good thing about vector image is that it can be scale or reduce without the quality of the image being affected. I ran into another problem with android and SVG file format. Android does not have built in method for .SVG file format. VectorDrawable was introduce in Android API 21 so it is not possible to use it in API 14 which my app supports.

Finally, I started researching for a third-party library that I can use in .html file format that will automatically render math equations and formulas. I found out there are many Java libraries but I decided to use a Javascript plugin that I will link to html file.

I wanted something small and fast. I found MathJax which is popular but it is slightly heavy. I finally ended up with jqMath.

jqMath is a JavaScript module that makes it easy to put formatted mathematical expressions in web pages.

With this information we know a lot more about what we are planning to achieve. Lets focus on how we can build a simple android application. In the application, we will use a WebView control on which we will load a html file that is linked to jqMath javascript library.

Before we start moving deep into the application development, it is important for us to see a screen-shot of what we are planning to achieve below.

Math formulas in android

Before we start, it is important for you to understand the tools and environment I used in this application development tutorial. Feel free to use any tools you are familiar with.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidMathEquation

Package: com.inducesmile.androidmathequation

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button.

If you are using Android Studio as your choice IDE, the new project will create a default MainActivity.java file and its corresponding layout file. Open the two files because we are going to make use of them.

Open the following website jqMath and download the JavaScript library. Once you have downloaded the library, copy and paste the folder in the asset folder of your application. If your application does not contain an asset folder, create one first before dropping the plugins to the folder.

Add the following code in the header section of your html file. Please remember to place the html file directly in the asset folder.

assets

<!DOCTYPE html>
<html lang="en" xmlns:m="http://www.w3.org/1998/Math/MathML">

<head>
	<meta charset="utf-8">
	
	<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=UnifrakturMaguntia">
	<link rel="stylesheet" href="mathscribe/jqmath-0.4.3.css">
	
	<script src="mathscribe/jquery-1.4.3.min.js"></script>
	<script src="mathscribe/jqmath-etc-0.4.3.min.js" charset="utf-8"></script>
	<!-- <script>M.MathPlayer = false; M.trustHtml = true;</script> →
</head>

Lets move over to our project layout file. We are going to add a Webview to our layout as shown below.

<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="elearning.chidi.com.elearning.FormulaActivity">
   
 <WebView
        android:id="@+id/formula_page"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_above="@+id/more_options"
        android:textSize="14sp"
        android:textColor="@color/primary_text"
        android:background="@color/icons"
        android:scrollbars="none" />
</RelativeLayout>

With the layout ready, we will move over to our MainActivity file. We will obtain the instance of our Webview and we will also enable Javascript since we are going to use a Javascript library. Finally, we will called the Webview method loadUrl(String url) to load the html file.

The code snippet is shown below.

import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class NumberBasicsActivity extends ActionBarActivity {
    private WebView articleContent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_number_basics);
        
        Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(topToolBar);
        topToolBar.setLogo(R.drawable.logo);
        topToolBar.setLogoDescription(getResources().getString(R.string.logo_desc));
        articleContent = (WebView) findViewById(R.id.article);
        articleContent.getSettings().setJavaScriptEnabled(true);
        articleContent.getSettings().setBuiltInZoomControls(true);
        
        try {            
            articleContent.loadUrl("file:///android_asset/testfile.html");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_number_basics, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Now, when you run your application you will see the interface that looks similar to the sample that was shown earlier on.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published.

If you like this tutorial, please kindly download my new android app in Google play store by clicking the image below

8 Comments

    • Inducesmile

Add a Comment