Android freemarker template engine application

Android freemarker template engine application

What is freemarker?

Before we talk about this, we all know that the battle between web and native controls is just that. Performance, loading speed, traffic, data interaction…

If I use webView to load a url page, I have to parse the css through the network, parse the html code, and then render the generated page

What is freemarker? To put it simply, put the above HTML file into the application in advance, and just pass in the data when using it.

Freemarker advantages and applications

Save traffic and speed up web page loading

For example, some chart functions are more convenient to implement with js library, just put in html template in advance and pass in data. This greatly saves traffic and loading speed

Or if you already have a web page, you don't need to create an Android interface.

This feature is universal on iOS, so you only need one template to use it on both iOS and Android, which greatly saves development time.

Implementation principle

WebView loads local template engine process

main.tpl ——–> main.ftl+data ————> main.html ————> webView.load(main.html)

1. Import the freemarker library

  1. compile 'org.freemarker:freemarker-gae:2.3.25-incubating'  

2. Put the main.tpl file into the assets directory

  1. <! --main.tpl file-->  
  2. <html>
  3. <head>
  4. <title>Welcome!</title>
  5. </head>
  6. <body>
  7. <h1>Welcome ${ user }!</h1>
  8. <p>Our latest product:
  9. </body>
  10. </html>

3. Convert main.tpl to main.ftl

  1. private void prepareTemplate() throws IOException {
  2. //Get the app directory data/data/package/file/
  3. String destPath = getFilesDir().getAbsolutePath();
  4. File dir = new File(destPath);
  5. // Check if the folder exists and create it
  6. if (!dir.exists()) {
  7. dir.mkdir();
  8. }
  9. //The .ftl template file name and path to be generated
  10. String tempFile = destPath + "/" + "main.ftl" ;
  11. if (!(new File(tempFile).exists())) {
  12. //Get the .tpl template file in assets
  13. InputStream is = getResources().getAssets(). open ( "main.tpl" );
  14. //Generate .ftl template file
  15. FileOutputStream fos = new FileOutputStream(tempFile);
  16. byte[] buffer = new byte[7168];
  17. int   count = 0;
  18. while (( count = is . read (buffer)) > 0) {
  19. fos.write(buffer, 0, count );
  20. }
  21. fos.flush();
  22. fos.close ();
  23. is . close ();
  24. }
  25. }

4. Generate main.html file from main.ftl and data

  1. private void genHTML(Product object) {
  2. String destPath = getFilesDir().getAbsolutePath();
  3. FileWriter out = null ;
  4. //Data source
  5. Map root = new HashMap();
  6. root.put( "user" , "user" ); // pass in string
  7. //root.put( "product" , object.url()); //Input object (will report an error)
  8. try {
  9. Configuration cfg = new Configuration(new Version(2,3,0));
  10. cfg.setDefaultEncoding( "UTF-8" );
  11. //Set error message
  12. cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  13. //Set error message
  14. cfg.setLogTemplateExceptions( true );
  15. out = new FileWriter(new File(destPath + "main.html" ));
  16. //Set the .ftl template file path
  17. cfg.setDirectoryForTemplateLoading(new File(destPath));
  18. //Set the name of the .ftl template file loaded by template
  19. Template temp = cfg.getTemplate( "main.ftl" );
  20. //Talk about data source and template generation.html file
  21. temp .process(root, out );
  22. out .flush();
  23. } catch (MalformedTemplateNameException e) {
  24.  
  25. } catch (IOException e) {
  26.  
  27. } catch (Exception e) {
  28.  
  29. }finally {
  30. try {
  31. if ( out != null )
  32. out . close ();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }

5. WebView loads main.html

  1. webview.post(new Runnable() {
  2. @Override
  3. public void run() {
  4. String templateDirRoot = getFilesDir().getAbsolutePath();
  5. String url = "file://" + templateDirRoot + "main.html" ;
  6. webview.loadUrl(url);
  7. }
  8. });

Problem points

1. Why do we need to convert mian.tpl into main.ftl file first, instead of putting the mian.ftl file directly into assets, and then directly load the main.ftl file in the template?

Because the files in assets cannot be read directly, you need to put the files in data/data/package/… before operating

2. Suddenly found that the 2016 version of freemarker cannot pass objects.

For example, in the main.ftl file, ${model.name} can no longer be converted to main.html, and the following error is prompted

  1. Unresolved exception class when finding catch block: java.beans.IntrospectionException

The official statement says it is possible, but I have tested it countless times and still cannot compile object transfer.

The name can be obtained as follows

  1. //activity.java
  2. User   user = new User ();
  3. user .setName= "Zhang San"  
  4. Map map = HashMap();
  5. map.put( "name" , user .getName());
  6.  
  7. //main.tpl
  8. <html>
  9. <body>
  10. ${ name }
  11. <body>
  12. <html>

The following method cannot obtain the name

  1. //activity.java
  2. User   user = new User ();
  3. user .setName= "Zhang San"  
  4. Map map = HashMap();
  5. map.put( "user" , user );
  6.  
  7. //main.tpl
  8. <html>
  9. <body>
  10. ${ user . name }
  11. <body>
  12. <html>

Summarize

***I didn't find that the webView page loading was much faster, maybe because the data volume was small. After all, it had to operate the SD card. The traffic was indeed saved, and there was less direct data interaction code between Java and HTML.

<<:  The six easiest programming languages ​​to learn for beginners

>>:  Regarding Android adaptation, it is enough to read this article

Recommend

Why do deep space probes circle before reaching their destination?

According to foreign media reports, the BepiColom...

Can Tik Tok Assistant help you become popular? What's the use?

The Douyin Assistant is in the Douyin APP. The wa...

Why do conspiracy theories persist? Mathematics has a profound answer

Many conspiracy theories start like this: as long...

Baidu Promotion Optimization Center Usage Suggestions

Today I will tell you what simple and reliable fu...

When using JSONObject, you need to be careful to avoid a problem

[[177050]] Bao Xiehao, Xiaomi MIUI department, he...

Event review: How to run a successful event?

This activity was based on the WeChat service acc...

Analysis of community group buying operation logic!

Preface: At present, with the entry of giants suc...

BAT is struggling to survive. Who says shopping guides have no vitality?

On May 15, Taobao made a new move. Alimama issued...