Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does jQuery Mobile design Android address book

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

JQuery Mobile how to design Android address book, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

We will introduce screenshots of the running interface in the application, explain the flow direction and structure of the whole application, and explain some skills and knowledge points on how to interact with the back-end JAVA application through Javascript in the Webview control of Android, including various important page elements in jQuery Mobile.

Page flow structure

Let's explain the page flow structure of the application. In this application, each address book is associated with an account, that is, multiple address books can be created among users of each account, just like gmail. When the Android application is launched, it will check whether an account has been established in the application. If the account does not exist for * times, the user will be prompted to create a new account, as shown in the following figure:

Once you have set up an account, you can go to the initial page of the address book, as shown below:

As you can see, the above figure sorts the address book alphabetically. When the user clicks the "Add" button, a page that asks the user to enter a specific address book is displayed, as shown in the image on the left below.

In the address list, the user can click on the information of an existing contact to view it, and the actual effect is shown in the second picture above, where the user can edit and modify the information, then save it, and then return to the

The interface of the address list. At the same time, if the user clicks the "delete" button, the interface shown below will be displayed, asking the user if he really wants to delete the user's contact information.

Throughout the application, considering the large number of records to be processed and the processing power of the mobile device, a friendly approach is to add an icon indicating the current progress when processing the data, as shown in the following figure:

To sum up, the actual flow of the whole application is shown in the following figure:

JQuery Mobile page design

Now let's look at how to use the jQuery Mobile framework to design page elements. In HTML pages designed by the jQuery Mobile framework, there is usually one page container in one page, while there are multiple pages in the page container. The page container is marked with date-role= "page", while the normal page is marked with date-role= "content". In a page, the head and tail of the page are optional parts. In our application, there are two pages with headers and tails, and one page without headers and tails. Here's the sample code:

.........

The above code shows how to include three pages in a container page, two of which have headers and footers, identified by data-role= "header" and data-role= "footer", respectively.

In this application, creating accounts, address lists, and progress icons all appear as content pages, and there will be a page container wrapped around them in ListPage.html, and there will also be a page container in DetailPage.html, which contains three pages, namely, "empty address book", "existing address book" and "prompt to delete address book". The following figure shows the structural relationship between them:

How to integrate front-end code and Android back-end Java code

In this tutorial, we will focus on how to access back-end Java applications in Android from the front-end page HTML/JAVASCRPT designed by jQuery Mobile, and how they interact with each other. You know, jQuery Mobile only helps developers to use their familiar knowledge such as HTML/Javascript to develop applications that can run on different platforms, but it does not have a mechanism to integrate with Android, so we explain how to do it in three parts:

1. Access the Java code of Android through Javascript

2. Android Java application access frontend Javascript/HTML code

3. The problem of the type of parameters in front-end interaction

Access the Java code of Android through Javascript

First learn how to access Android's Java code through Javascript. Android provides a method for JavaScript to access the Java application, which is the addJavascriptInterface (Object object, String interfaceName) method located in the android.webkit.WebView class. This method allows access to the public method in the Java class running in WebView from the JavaScript code. It is important to note that WebView is actually a kind of android.view.View. WebView is the browser that displays HTML pages and JavaScript in Android. Where obj in the addJavascriptInterface method is the application that communicates with javascript, and interfacename is the name provided to the JavaScript call. The following figure clearly shows the calling relationship between the two:

The following code shows how an example of the class ContactsActivity can be exposed as a Javascript object with the external interface name "contactSupport" through the addJavascriptInterface method. There are many public methods in ContactsActivity, and it exposes the deleteContact () method to the outside.

Import android.webkit.WebView; import android.app.Activity;... Public class ContactsActivity extends Activity {WebView webView;... Public void onCreate (Bundle savedInstanceState) {... WebView = new WebView (this);... WebView.addJavascriptInterface (this, "contactSupport");...} public void deleteContact (String contactId, String displayPage) {...}

The following Javascript code shows how to access the deleteContact method in the ContactsActivity object instance of the back-end Java code

... Function someJavaScriptFunction () {.. ContactSupport.deleteContact (contactIdVar.val (), 'ListPage.html');}.

How Android Java code accesses front-end Javascript code

In this application, we use the loadUrl (String url) method in the WebView class to achieve two purposes:

(1) load HTML page in Webview browser (2) when you load HTML in WebView, you can load the Javascript together. We should pay attention to the following two points:

◆ in the same container page, the jump between different content pages, all use Javascript code.

◆ Transition from one container page to another is performed by Java code usingWebView.loadUrl (String url). The container page to display is passed to Java code from JavaScript as a callback parameter.

Calls to each other in different containers need to be done in WebView's Java application by using the

WebView.loadUrl (String url) to load, the following figure shows how the Java back-end code accesses the front-end Javascript code:

◆ users first visit the HTML web page, and then call Javascipt to display the page

◆ then, Javascript does some data processing and invokes the back-end Java code.

After the Java code is processed, ◆ will call back the front-end Javascript code or load the HTML page through the loadurl method.

The following code explains that after the front-end Javascript code calls the delteContact () method in the latter section, the record in the database is deleted, and then a HTML page is reloaded for display.

Import android.webkit.WebView; import android.app.Activity; import android.os.Handler;... Public class ContactsActivity extends Activity {WebView webView; private Handler handler = null;... Public void onCreate (Bundle savedInstanceState) {... WebView = new WebView (this);... Handler = new Handler ();...} public void deleteContact (String contactId, String displayPage) {ContactUtility.deleteContact (contactId,...); loadPage (displayPage);} public void loadPage (String in) {final String url = "file:///android_asset/www/" + in; loadURL (url) } private void loadURL (final String in) {handler.post (new Runnable () {public void run () {webView.loadUrl (in);}});}

Here, we use the Handler message handling mechanism in Android. This article does not intend to explain the use of the Handler mechanism in detail, please refer to the Android manual for details. Here is a brief mention of the Handler message handling mechanism, mainly in Android, the newly started thread cannot refresh or access the UI interface, so we should use the Handler mechanism. Here, the deleteContact () method cannot call WebView.loadUrl () directly for two reasons, one is that the WebView instance is created in the onCreate method, which is in the main thread, and the second reason is that when Javascript calls deleteContact (), the thread that executes it is actually different from the main thread in the onCreate () method in ContactsActivity. Therefore, it is not difficult to understand the following three steps:

In deleteContac (), we delete an address book record.

Next, we call the loadPage method, where we specify the display page to be redirected and prefix it with file:// android_asset/www/, meaning that the page we jumped to is actually stored in the android_asset/www directory.

Finally, we call the loadURL () method to have the Handler object call the WebView.***, We use the post of the Handler mechanism in the loadURL method, add the loadUrl method of WebView to the newly opened thread, and send it to the message queue.

How to call the front-end JavaScript

Now let's take a look at how to call the front-end Javascript in the back-end Java code as follows:

Public class ContactsActivity extends Activity {... Public void getAllContacts (String callback, String accountCallback) {final String accountCallbackFunction = "_ javascript:" + accountCallback + "()"; if (accountName = = null) {loadURL (accountCallbackFunction); return;} final String json = ContactUtility.getAllContactDisplaysJSON (getContentResolver ()); final String callbackFunction = "_ javascript:" + callback + "('" + json + "')"; loadURL (callbackFunction);}

In the above code, the function of the getAllContacts method is to produce an address list in JSON format, whose results are stored in the json variable. The result is then called back to the front-end javascript method to handle parsing the JSON format. Here

The callbackFunction = "_ javascript:" + callback + "(" + json + ")" is returned to the front end through _ javascript: the name of the JAVASCRIPT method processed by the front end + the result set in JSON format. * it is also through the loadURL method that the front-end Javascipt processing can be called. Let's take a look at the front-end Javscript code:

$(document) .ready (function () {... ContactSupport.getAllContacts ('setContactsList','showAccount');})

In the above code, the getAllContacts method of the Java backend is called, and after the getAllContacts method obtains the result set in JSON format, it will call the setContactsList method of the front-end Javascript to deal with it (we will describe the details of this method later), while the showAccount in the parameters, in the back-end getAllContacts method, will judge that if the current address book does not have any data, it will re-use the front-end showAccount JavaScript method to deal with it.

The problem of the type of parameters in front-end interaction

In this application, we only use the string type in the front-end interaction. Other types such as Integer will be converted to strings. Objects like compound types will communicate with each other in the form of JSON. In the Java backend, we will use the Jackson JSON processing class library to transform Java objects and JSON objects, and in Javascript, we will use the jQuery.parseJSON () method to parse the JSON returned by the backend, which will be explained in detail in the next tutorial.

Introduction to program entry

In our application, ContactsActivity is the main class of the program. The code is as follows:

Public class ContactsActivity extends Activity {WebView webView; private Handler handler = null; private String accountType = null; private String accountName = null;... Public void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); / / initialize WebView webView = new WebView (this); setContentView (webView); / / allow the use of Javscript webView.getSettings (). SetJavaScriptEnabled (true); / / check whether the account in the application has been created accountType = "com.jquerymobile.demo.contact" Account [] accounts = AccountManager.get (this) .getAccountsByType (accountType); if (accounts.length! = 0) {accountName = accounts [0] .name;} handler = new Handler (); webView.addJavascriptInterface (this, "contactSupport"); / / load index.html page loadPage ("index.html");}.}

The key points in the code are as follows:

◆ first initializes WebView and allows Webview to use Javascript.

◆ as mentioned earlier, the account must be associated with the use of the address book, so use the android.accounts.AccountManager class to check whether the account already exists in the application, and if so, assign the account name to the variable accountName.

◆ We initialize the handler field. Then use the handler mechanism to bind the object instance of ContactsActivity to the Javascript of the front end, and the interface name of the interaction is contactSupport.

The code for the index.html page is as follows, where, in the ready method of jQuery, when the page is loaded, the ListPage.html starts to load.

ListPage.html

First of all, I will explain the ListPage.html code. Recall the structure diagram mentioned earlier. You can see that the page container contains three content pages, namely, creating account, address list and progress waiting. The code is as follows:

Contacts Add Processing... Please wait.

Create Account

Please enter name of the new account for this application Contacts created with this application will be associated with the new account specified below. Other contacts can be viewed, however, cannot be deleted or modified with this application. Save......

In the above code, note the following

All three content pages in ◆ have headers, footers, and content areas. Among them, each part is defined in the way of DIV layer, and defines data-theme= "c", which uses the pre-defined color style in jQuery Mobile framework, please refer to the discussion in jQuery Mobile manual for details.

◆ jQuery Mobile has a predefined return button, but we will define it in the application, so we don't need it here, so set data-nobackbtn= "true".

◆ has an added button in the content page of "Contact List" that calls the addContact () method, which you'll learn later. In the DIV of id= "contentList", the current content is actually empty, in the program, the result set will be dynamically populated here, and please note that the listview style in jQuery Mobile is used here, indicating that this is a list style.

◆ notices the button in "Create Account", where data-incline= "true" is used, which means that the size of the button matches the size of the text "Save".

Let's move on to ListPage.html. Next, let's take a look at how to display a page in the page container at the same time. For example, when we create a new account, we only want to display the div of the new account. The method is simple. In the ready () method of jQuery, variables are initialized to hold the page in the page container, via the $("#...") in jQuery. The selector can be implemented. Then, where you need to display a layer, define the hidePage () and showPage () methods, in which you can call the layer's hide and show methods, respectively. The following is an example. Some of the same codes are omitted. For more information, please see Code download:

Var hdrListVar; var contentListVar; var ftrListVar; var hdrProgressVar; var contentProgressVar; var ftrProgressVar; var hdrAccountVar; var contentAccountVar; var ftrAccountVar; $(document) .ready (function () {/ / Initialize commonly used variables hdrListVar = $('# hdrList'); contentListVar = $('# contentList'); ftrListVar = $('# ftrList'); hdrProgressVar = $('# hdrProgress'); contentProgressVar = $('# contentProgress'); ftrProgressVar = $('# ftrProgress') HdrAccountVar = $('# hdrAccount'); contentAccountVar = $('# contentAccount'); ftrAccountVar = $('# ftrAccount');...}); Function hideList () {hdrListVar.hide (); contentListVar.hide (); ftrListVar.hide ();} function showList () {hideProgress (); hideAccount (); hdrListVar.show (); contentListVar.show (); ftrListVar.show ();} function hideProgress () {hdrProgressVar.hide (); contentProgressVar.hide (); ftrProgressVar.hide ();}...

Next, let's take a look at the getAllContacts () method, which gets the address list with the following code:

Public void getAllContacts (String callback, String accountCallback) {final String accountCallbackFunction = "_ javascript:" + accountCallback + "()"; if (accountName = = null) {loadURL (accountCallbackFunction); return;} final String json = ContactUtility.getAllContactDisplaysJSON (getContentResolver ()); final String callbackFunction = "_ javascript:" + callback + "('" + json + "')"; loadURL (callbackFunction);}

We had partially reviewed that code before. To recap: as mentioned earlier in this code, we focus on the getAllContactDisplaysJSON method, which takes out the back-end result set, converts it into a string in JSON format, and then calls back to the method in the front end Javascript to reorganize the data in JSON format. In our application, the names of contacts are grouped in alphabetical order. Let's take a look at the data set in JSON format. JSON is no longer discussed in detail in this article, please refer to the relevant documents.

{"contacts": [{"key": "A", "values": [{"contactId": "257"," displayName ":" Aach Herb "," key ":" A "},..., {" contactId ":" 256", "displayName": "Aaker David", "key": "A"}]}, {"key": "B", "values": [{"contactId": "259" "displayName": "Belanger Andre", "key": "B"},..., {"contactId": "260", "displayName": "Bohme Jacob", "key": "B"}]},...]}

As you can see, it is grouped in alphabetical order, the key attribute represents letters, and the value of values is an array in JSON format that contains the specific address book of the contacts under each letter.

Next, let's take a look at how the Javascript of the front-end page parses the JSON-formatted string passed by the back-end. The code is as follows:

...... / / Commonly used variables... Var contactSelectionsVar; $(document) .ready (function () {/ / Initialize commonly used variables... ContactSelectionsVar = $('# contactSelections');.}. Function setContactsList (jsonText) {var tmpJson = $.parseJSON (jsonText); if (tmpJson! = null & & tmpJson.contacts! = null) {var tmpContacts = tmpJson.contacts; for (I = 0; I < tmpContacts.length; iTunes +) {var tmpKey = (tmpContacts [I]) .key; var tmpKeyFragment =''+ tmpKey+''; contactSelectionsVar.append (tmpKeyFragment); var tmpValues = (tmpContacts [I]). Values If (tmpValues! = null) {var j; for (j = 0; j < tmpValues.length; jacks +) {var tmpDisplayName = tmpValues [j] .displayName; var tmpContactId = tmpValues [j] .contactId; var tmpLiFragment =''+ tmpDisplayName+''; contactSelectionsVar.append (tmpLiFragment) } contactSelectionsVar.listview ('refresh'); showList ();}...

First of all, ◆ uses the parseJSON method of jQuery to parse the JSON format code obtained by the back end, and the parsed value is assigned to the tmpJson variable.

Then, using the sentence var tmpContacts = tmpJson.contacts;, you get the contents of the CONTACTS part of the JSON format mentioned earlier, and then use a FOR loop, in the loop body, each time you pass through

Var tmpKey = (tmpContacts [I]) .key, the key part of the obtained JSON string (that is, each letter)

◆ then combines the tmpKey variable with the variable tmpKeyFragment. It is a list item splitter symbol in jQuery Mobile.

◆. Then add the tmpKeyFragment variable to the DIV area of contactSelectionsVar using the append method of jQuery.

◆ 's next step is to read the value in the values attribute in the JSON string. The variable tmpValues stores all the address book contact lists under each letter, and then uses a loop to read each contact's contactId and displayName.

Then combine tmpDisplayName and tmpContactId into tmpLiFragment variables, and notice that a link is added here, so that when the user clicks the name of the contact, another page showing details will be called up with javascript. Again, * We add it to the div layer of contactSelectionsVar.

◆ *, we use contactSelectionsVar.listview 's refresh method to update the list.

The following figure shows how this part of the code corresponds to the actual effect, and you can clearly see the structure between the two:

We introduce the general situation of the application to be designed, the page structure and some elements of the page in the jQuery Mobile framework, as well as the basic knowledge of how the back-end JAVA program in Android interacts with the front-end Javascript.

After reading the above, have you mastered how jQuery Mobile designs the Android address book? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report