| Java is a tool selected by Android Developers. Android uses its own virtual machine Dalvik, which is not the majority Program Common Java Virtual Machine Used by developers. Dalvik supports Java Programming Language But not all. Michael GALPIN, eBay software architect, wrote an article Article Gourmet Java Technology for Android applications. These features include concurrency, networking, and database access. The Chinese version of this article is published on IBM developerworks. The full text is as follows:
Start preparation
This article describes several Android SDK tools that handle complex situations. To develop an Android Application, you need the latest Android SDK. This requires a Java Development Kit (JDK ). I am using Android 2.2 and JDK 1.6.0 _ 17. Physical devices are not required.CodeIt can run well on the android simulator that comes with the SDK. This article assumes that you are familiar with Android programming, so it does not involve basic Android development. However, if you have knowledge of the Java programming language, you can also.
Concurrency and networking
One of the most common tasks of Android applications is to retrieve data or send data to a remote server over the network. The result of this operation is usually some new data that you want to display to the user. This means you need to modify the user interface. Most developers know that you will not execute a potential long-term running task, for example, accessing data through the network on the main UI thread (especially using a mobile phone with a very slow network connection ). Freeze your application until the long-term running tasks are completed. In fact, if this task exceeds 5 seconds, the Android operating system will see the notorious application not responding dialog box, as shown in 1.
Figure 1. Android's notorious application not responding dialog box
You cannot know how slow your network connection is. To avoid taking risks, you must execute tasks on different threads, or at least not on the main UI thread. Many Android applications, but not all, need to process multiple threads, resulting in concurrency. Applications often need to store data locally. The Android database is a good choice. These three scenarios (different threads, concurrency, and local data storage) have many standard methods for processing in the Java environment. However, as you will see, Android provides different options. Let's look at the advantages and disadvantages one by one.
Android Network
It is simple to use Java programming for calling through the network. The familiar java.net contains several classes that execute this operation. Most of these classes are available in Android. In fact, you can use classes like java.net. url and java.net. urlconnection, just as you do in other Java applications. However, Android includes the pache httpclient library, which is the preferred method for connecting to the network on Android. Even if you use common Java classes, the android implementation still uses httpclient. Listing 1 shows an example of using this essential library.
Listing 1. using the HTTP client library on Android
Private arraylist <stock> fetchstockdata (stock [] oldstocks) throws clientprotocolexception, ioexception {stringbuilder sb = new stringbuilder (); For (stock Stock: oldstocks) {sb. append (stock. getsymbol (); sb. append ('+');} sb. deletecharat (sb. length ()-1); string urlstr = "http://finance.yahoo.com/d/quotes.csv? F = sb2n & s = "+ sb. tostring (); httpclient client = new defaulthttpclient (); httpget request = new httpget (urlstr. tostring (); httpresponse response = client.exe cute (request); bufferedreader reader = new bufferedreader (New inputstreamreader (response. getentity (). getcontent (); string line = reader. readline (); int I = 0; arraylist <stock> newnewstocks = new arraylist <stock> (oldstocks. length); While (Lin E! = NULL) {string [] values = line. Split (","); stock Stock = new stock (oldstocks, Oldstocks. GETID (); stock. setcurrentprice (double. parsedouble (Values [1]); stock. setname (Values [2]); newstocks. add (stock); line = reader. readline (); I ++;} return newstocks;} in this Code, there is a set of stock objects. This is a basic data structure object that stores the user's stock information (such as codes and prices) and more personal information (such as how much the user has paid ). You can use the httpclient class to retrieve dynamic data from Yahoo Finance (for example, the current price of this stock ). Httpclient contains an httpurirequest. In this example, you can use httpget, a subclass of httpurirequest. Similarly, when you want to send data to a remote server, you can use the httppost class. When you get httpresponse from the client, you can access the potential inputstream of the response, buffer it, and parse it to obtain the stock information.
Now you can see how to retrieve data through the network and how to use this data to intelligently update the android UI using multithreading.
Android concurrency practices
If you run the code in Listing 1 on the main UI thread of the application, the application not responding dialog box may appear, depending on the user's network speed. Therefore, you must be sure to generate a thread to obtain data. Listing 2 shows a solution.
Listing 2. na & iuml; ve multithreading (don't do this, it won't work !)
Private void refreshstockdata () {runnable task = new runnable () {public void run () {try {arraylist <stock> newstocks = fetchstockdata (stocks. toarray (new stock [stocks. size ()]); For (INT I = 0; I <stocks. size (); I ++) {stock s = stocks. get (I); S. setcurrentprice (newstocks. get (I ). getcurrentprice (); S. setname (newstocks. get (I ). getname (); refresh () ;}} catch (exception e) {log. E ("stockportfolioviewstock S "," exception getting stock data ", e) ;}}; thread t = new thread (task); T. start () ;}the title Declaration in Listing 2 states that this is the na & iuml; ve code, indeed. In this example, you will call the fetchstockdata method in Listing 1, encapsulate it in the runnable object, and execute it in a new thread. In this new thread, you can access stocks, a member variable that encapsulates the activity (this class creates the UI. As the name suggests, this is a data structure of the stock object (in this example, java. util. arraylist ). In other words, you share data between two threads, the main UI thread and the derivative (spawned) thread (called in Listing 2 ). When you modify the shared data in the derivative thread, update the UI by calling the refresh method on the activity object.
If you have compiled a Java swing application, you may need to follow a pattern like this. However, this will not work properly in Android. The derivative thread cannot modify the UI at all. Therefore, how do you retrieve data without freezing the UI, but on the other hand, when the data is received and you are allowed to modify the UI? The android. OS. Handler class allows you to coordinate and communicate between threads. Listing 3 shows an updated refreshstockdata method using handler.
Listing 3. Working multithreading-using Handler
Private void refreshstockdata () {final arraylist <stock> localstocks = new arraylist <stock> (stocks. size (); For (stock Stock: stocks) {localstocks. add (new stock (stock, stock. GETID ();} final handler = new handler () {@ override public void handlemessage (Message MSG) {for (INT I = 0; I <stocks. size (); I ++) {stocks. set (I, localstocks. get (I) ;}refresh () ;}; runnable task = new runnable () {Publ IC void run () {try {arraylist <stock> newstocks = fetchstockdata (localstocks. toarray (new stock [localstocks. size ()]); For (INT I = 0; I <localstocks. size (); I ++) {stock NS = newstocks. get (I); stock ls = localstocks. get (I); LS. setname (NS. getname (); LS. setcurrentprice (NS. getcurrentprice ();} handler. sendemptymessage (result_ OK);} catch (exception e) {log. E ("stockportfolioviewstocks", "exception gett Ing stock data ", e) ;}}; thread datathread = new thread (task); datathread. start ();} has two major differences in the code in Listing 2 and listing 3. The obvious difference is the existence of handler. The second difference is that you cannot modify the UI in the derivative thread. On the contrary, when you send messages to handler, Handler then modifies the UI. Also note that you cannot modify stocks member variables in the thread, as you did before. Instead, you can modify the local copy of the data. Strictly speaking, this is not necessary, but it is more secure.
Listing 3 illustrates some common patterns in concurrent programming: copy data, parse the data to the thread that executes the long-term task, pass the result data back to the main UI thread, and update the main UI thread according to the data. Handlers is the main communication mechanism in Android, which makes this mode easy to implement. However, listing 3 still contains sample code. Fortunately, Android provides methods to encapsulate and eliminate most sample code. Listing 4 demonstrates this process.
Listing 4. Use asynctask to make multithreading easier
Private void refreshstockdata () {New asynctask <stock, void, arraylist <stock> () {@ override protected void onpostexecute (arraylist <stock> result) {viewstocks. this. stocks = result; refresh () ;}@ override protected arraylist <stock> doinbackground (stock... stocks) {try {return fetchstockdata (stocks);} catch (exception e) {log. E ("stockportfolioviewstocks", "exception getting stock data", e);} retu Rn NULL;} cmd.exe cute (stocks. toarray (new stock [stocks. Size ()]);} as you can see, listing 4 is much less than listing 3's sample code. You cannot create any threads or handlers. Use asynctask to encapsulate all sample code. To create an asynctask, you must implement the doinbackground method. This method is always executed in an independent thread, so you can freely call a long-term running task. Its input type comes from the type parameter of the asynctask you created. In this example, the first type parameter is stock, so doinbackground gets a set of stock objects passed to it. Similarly, it returns an arraylist <stock> because this is the third type parameter of asynctask. In this example, I also choose to override the onpostexecute method. This is an optional method. You can use this method to perform operations on the data returned from doinbackground. This method is always executed on the main UI thread, so it is a good choice to modify the UI.
With asynctask, You can simplify multi-threaded code. It can delete many concurrent traps from your development path. You can still use asynctask to find some potential problems, for example, what can happen when the direction on the device changes while the doinbackground method object is executed. For more information about how to deal with such cases, see references.
Now let's start to discuss another common task. Android obviously deviates from the common Java method-using a database for processing.
Android Database Connectivity
A very useful feature in Android is the presence of a local relational database. Ensure that you can store your data in local files, but it is usually more useful to use a relational database management system (RDBMS) for storage. Android provides you with a commonly used SQLite database for processing, because it is highly optimized for embedded systems such as Android. It is used by core applications on Android. For example, a user's address book is stored in an SQLite database. Now, for the given Android JAVA Implementation, you can use JDBC to access these databases. Unexpectedly, android even includes java. SQL and javax. SQL packages that constitute the main JDBC APIs. However, this is useless when the local Android database is used for processing. Instead, you want to use the Android. Database and Android. database. SQLite packages. Listing 5 is an example of using these classes to store and retrieve data.
Listing 5. using Android for database access
Public class stocksdb {Private Static final string db_name = "stocks. DB "; Private Static final int db_version = 1; Private Static final string table_name =" stock "; private Static final string create_table = "create table" + table_name + "(ID integer primary key, symbol text, max_price decimal (8, 2)," + "min_price decimal (8, 2 ), price_paid decimal (8, 2), "+" quantity integer) "; Private Static fin Al string insert_ SQL = "insert into" + table_name + "(symbol, max_price, min_price, price_paid, quantity)" + "values (?,?,?,?,?) "; Private Static final string read_ SQL =" select ID, symbol, max_price, "+" min_price, price_paid, quantity from "+ table_name; private final context; private final sqliteopenhelper helper; private Final sqlitestatement stmt; private final sqlitedatabase dB; Public stocksdb (context) {This. context = context; helper = new sqliteopenhelper (context, db_name, null, db_version) {@ overr IDE public void oncreate (sqlitedatabase dB) {db.exe csql (create_table) ;}@ override public void onupgrade (sqlitedatabase dB, int oldversion, int newversion) {Throw new unsupportedoperationexception () ;}}; DB = helper. getwritabledatabase (); stmt = dB. compilestatement (insert_ SQL);} public stock addstock (stock Stock) {stmt. bindstring (1, stock. getsymbol (); stmt. binddouble (2, stock. getmaxprice ()); Stmt. binddouble (3, stock. getminprice (); stmt. binddouble (4, stock. getpricepaid (); stmt. bindlong (5, stock. getquantity (); int id = (INT) stmt.exe cuteinsert (); return new stock (stock, ID);} public arraylist <stock> getstocks () {cursor Results = dB. rawquery (read_ SQL, null); arraylist <stock> stocks = new arraylist <stock> (results. getcount (); If (results. movetofirst () {int idcol = results. getcolumn Index ("ID"); int symbolcol = results. getcolumnindex ("symbol"); int maxcol = results. getcolumnindex ("max_price"); int mincol = results. getcolumnindex ("min_price"); int pricecol = results. getcolumnindex ("price_paid"); int quanitytcol = results. getcolumnindex ("quantity"); do {stock Stock = new stock (results. getstring (symbolcol), results. getdouble (pricecol), results. getint (quanitytcol), results. getin T (idcol); stock. setmaxprice (results. getdouble (maxcol); stock. setminprice (results. getdouble (mincol); stocks. add (stock);} while (results. movetonext ();} If (! Results. isclosed () {results. close ();} return stocks;} public void close () {helper. close () ;}} the class in listing 5 completely encapsulates an SQLite database for storing stock information. Because you want to use an embedded database, not only must your application use it, but also create it through the application. You need to provide code to create the database. Android provides a useful abstract help class sqliteopenhelper. To complete this operation, you need to extend this abstract class and provide the code to create your database by using the oncreate method. When you have a help program instance, you can obtain a sqlitedatabase instance, which can be used to execute any SQL statement.
Your Database Class has two convenient methods. The first is addstock, which is used to save the new stock to the database. Note that you use a sqlitestatement instance, which is similar to a java. SQL. preparedstatement. It should be noted that how to compile it in your class constructor so that it can be reused every time you call addstock. In each addstock call, the sqlitestatement variable (question mark in the insert_ SQL string) must pass the data to addstock. Again, this is similar to preparedstatement, which you can learn from JDBC.
Another method is getstocks. As its name implies, it retrieves all stocks from the database. Note that you use an SQL string again, as you used in JDBC. You can use rawquery to process data in the sqlitedatabase class. This class also has several query methods, so that you can directly query the database without using SQL. All these methods return a cursor object, which is very similar to Java. SQL. resultset. You can move the cursor to the row where the data returned from the database is located, you can use getint, getstring, and other methods to retrieve values related to each column in the database you want to query. Again, this is very similar to resultset. Similar to resultset, it is also important to disable cursor after you complete the operation. If you have not disabled cursors, it may quickly exhaust the memory and cause your application to crash.
Querying a local database is a slow process, especially if you have multiple rows of data or you need to run complex query statements between multiple tables. However, when the database is queried or inserted for more than 5 seconds and an application not responding dialog box appears, this situation is unlikely, but when your database is busy reading and writing data, it is unwise to freeze your UI. Of course, the best way to avoid this situation is to use asynctask. Listing 6 shows this example.
list 6. Insert a database to a separate thread
Button button = (button) findviewbyid (R. id. BTN); button. setonclicklistener (New onclicklistener () {public void onclick (view v) {string symbol = symbolin. gettext (). tostring (); symbolin. settext (""); double max = double. parsedouble (MAXIN. gettext (). tostring (); MAXIN. settext (""); double min = double. parsedouble (Minin. gettext (). tostring (); Minin. settext (""); double pricepaid = double. parsedouble (pricei N. gettext (). tostring (); pricein. settext (""); int quantity = integer. parseint (quantin. gettext (). tostring (); quantin. settext (""); stock Stock = new stock (symbol, pricepaid, quantity); stock. setmaxprice (max); stock. setminprice (min); New asynctask <stock, void, stock> () {@ override protected stock doinbackground (stock... newstocks) {// there can be only one! Return dB. addstock (newstocks [0]) ;}@ override protected void onpostexecute (stock s) {addstockandrefresh (s) ;}cmd.exe cute (stock );}}); you can create a practice listener for the button first. When you click the button, you can read the stock data from each widget (specifically the edittext widget) and fill in a new stock object. You can create an asynctask and call the addstock method from listing 5 using the doinbackground method. In this way, addstock will be executed on a background thread, rather than on the main UI thread. After completion, the new stock object is passed from the database to the addstockandrefresh method executed on the main UI thread.
Conclusion
This article shows that android supports only one subset of many APIs in the Java environment, but its functions are not inferior at all. In some examples, such as the network, it fully implements the familiar API and provides some more convenient methods. In other examples, such as concurrency, Android adds additional APIs and some conventions that must be followed. Finally, in the case of database access, Android provides a completely different method to access the database, but it uses a familiar concept. This is not just a subjective difference between the standard Java and Android Java technologies: they form the basic building components for Android development.
Author profile:
Michael Galpin
Michael Galpin
Michael Galpin is an architect at eBay. He often writes articles for developerworks and publishes articles in theserverside.com and Java developer journals. He also has his own blog. He has been a professional programmer since 1998 and has a bachelor's degree in mathematics at Caltech.
Link: http://www.ibm.com/developerworks/cn/xml/x-gourmetandroid/#f1
|