Android Development Notebook (29) HTTP-based Latex Math formula Converter

Source: Internet
Author: User

This article explains how to convert a latex mathematical function expression into an image form using the API interfaces provided by Codecogs.com and Google.com. Specific ideas are as follows:

(1) Obtain the latex mathematical expression of the user input through EditText, then format the expression to make it easy to transmit the network.

(2) The formatted string is sent to codecogs.com or google.com via an HTTP request.

(3) Get the data stream returned by the website, convert it to a picture, and display it on the ImageView.

The specific process is:

1. Get and format latex math expressions

First, we enter the Latex math formula on this website and then return to the picture, namely "Http://latex.codecogs.com/gif.latex?" Follow the formula that we entered. "Http://latex.codecogs.com/gif.latex?\alpha", for example, displays a Greek letter. So we can add the formula we want to convert later. However, it is important to note that the spaces in the network URL are sometimes automatically converted to the plus sign "+". Therefore, we need to remove the space when transmitting. or convert it to "%20". The button executes when clicked.

To add Network access first:

<uses-permission android:name= "Android.permission.INTERNET"/>
String picurlcogs = "Http://latex.codecogs.com/gif.latex?"; url = new URL (picurlcogs + edittext.gettext (). toString (). Replace ("", "")); new Mydownloadtask (). Execute ();                 Executes the HTTP request while (!finishflag) {}                           //waits for the data to be received Imageview.setimagebitmap (PNGBM);                Show Picture Finishflag = false;                             Identify the return bit

2. Sending HTTP requests

      here, we send an HTTP request in a way that takes an asynchronous thread. First, get the URL address from the previous step, then establish an HTTP link, then enter the returned data into the input stream, and finally decode the input stream into a picture and display it in ImageView.

protected void Doinbackground (void ... params) {try {url picurl = URL; Get URL address httpurlconnection conn = (httpurlconnection) picurl.openconnection ();//con              N.setconnecttimeout (1000);                Establish connection//conn.setreadtimeout (1000);                              Conn.connect (); Open Connection if (conn.getresponsecode () = = 200) {//connection succeeded, return data InputStream INS = conn . getInputStream (); Enter data into the data stream PNGBM = Bitmapfactory.decodestream (Picurl.openstream ());                       Parse data stream finishflag = true;                             Data transfer complete identification ins.close ();            Close Data Flow}} catch (Exception e) {e.printstacktrace ();        } return null; }

Complete Mydownloadtask Class code (within mainactivity):

Class Mydownloadtask extends Asynctask<void, void, void> {protected void OnPreExecute () {//DISPL        Ay progress dialog.                            } protected void Doinbackground (void ... params) {try {url picurl = URL;                Get the URL address httpurlconnection conn = (httpurlconnection) picurl.openconnection ();//              Conn.setconnecttimeout (1000);                Establish connection//conn.setreadtimeout (1000);                              Conn.connect (); Open Connection if (conn.getresponsecode () = = 200) {//connection succeeded, return data InputStream INS = conn . getInputStream (); Enter data into the data stream PNGBM = Bitmapfactory.decodestream (Picurl.openstream ());                       Parse data stream finishflag = true;                             Data transfer complete identification ins.close (); Close data Stream}} catch (Exception e) {E. Printstacktrace ();        } return null; } protected void OnPostExecute (void result) {//Dismiss progress dialog and update UI}}

3. Display pictures

The network connection class that you established in the previous step, and then instantiate one of these classes within a button click event to receive data, and then display the returned data in ImageView.

 Btnpreview.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (View v) { try {url = new URL (picurlcogs + edittext.gettext (). toString (). Replace ("", ""));//Convert Word                 Character string New Mydownloadtask (). Execute (); Executes the HTTP request while (!finishflag) {}//waits for the data to be received imageview.se                Timagebitmap (PNGBM);                             Show Picture Finishflag = false;                Identifies the return bit} catch (Exception e) {e.printstacktrace (); }            }        });

So, after we enter the latex formula, we click the Preview button and the corresponding picture is displayed on the ImageView. Because this article only discusses how to convert, and does not do any optimization of the picture, it may seem small. In addition, if you take a space conversion URL method, try to ensure that the latex expression is strictly legal (for example, all units are enclosed in {}).

Full code:

Import Android.app.activity;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.asynctask;import Android.os.bundle;import Android.view.view;import Android.widget.Button;import Android.widget.edittext;import Android.widget.imageview;import Java.io.inputstream;import  Java.net.httpurlconnection;import Java.net.url;public class Mainactivity extends Activity {private String Picurlgoogle    = "Http://chart.apis.google.com/chart?cht=tx&chl=";    Private String picurlcogs = "Http://latex.codecogs.com/gif.latex?";    Private Button Btnpreview;    Private EditText EditText;    Private ImageView ImageView;    Private Bitmap PNGBM;    Private URL URL;    Private Boolean finishflag = false;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Btnpreview = (Button) Findviewbyid (R.id.btnpreview); ImageView = (ImageView) Findviewbyid (r.id.imageView);        EditText = (editText) Findviewbyid (R.id.edittext);                Btnpreview.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                     try {url = new URL (picurlcogs + edittext.gettext (). toString (). Replace ("", ""));//Convert string                 New Mydownloadtask (). Execute (); Executes the HTTP request while (!finishflag) {}//waits for the data to be received imageview.se                Timagebitmap (PNGBM);                             Show Picture Finishflag = false;                Identifies the return bit} catch (Exception e) {e.printstacktrace ();    }            }        });    } @Override public void OnDestroy () {Super.ondestroy (); } class Mydownloadtask extends Asynctask<void, void, void> {protected void OnPreExecute () {//        Display Progress dialog. } protected Void DOinbackground (Void ... params) {try {url picurl = URL; Get URL address httpurlconnection conn = (httpurlconnection) picurl.openconnection ();//Conn.setc              Onnecttimeout (1000);                Establish connection//conn.setreadtimeout (1000);                              Conn.connect (); Open Connection if (conn.getresponsecode () = = 200) {//connection succeeded, return data InputStream INS = conn . getInputStream (); Enter data into the data stream PNGBM = Bitmapfactory.decodestream (Picurl.openstream ());                       Parse data stream finishflag = true;                             Data transfer complete identification ins.close ();            Close Data Flow}} catch (Exception e) {e.printstacktrace ();        } return null;      } protected void OnPostExecute (void result) {//Dismiss progress dialog and update UI  }    }} 

Android Development Notebook (29) HTTP-based latex math formula converter

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.