Use cloud (BAE) for remote access to Android Application Data (MySQL)

Source: Internet
Author: User

Source: http://xevan.net/bae-for-android/

When using Android applications, we inevitably need to access data, and more often we use local MySQL servers, however, Baidu Bae can achieve remote data access, that is, access through the Internet. This article describes how to use apsaradb using an instance.

1. What is Bae?

The Baidu cloud environment, namely, BAE (Baidu application engine), provides a multi-language and elastic server running environment to help developers quickly develop and deploy applications. The cloud environment has a rich set of built-in distributed computing APIs and supports a full range of Baidu "Cloud" services, which can bring powerful power to your applications, from "local" to "distributed ", simple and reliable. For more information, see the link on the above official website.

Here we use Baidu's cloud storage.

2. Deploy the cloud environment

Register a Baidu account and clickManagement Center, Fill in the relevant personal information. And activate the mailbox.

ClickCreate an application, SelectWeb Applications, Enter the application name, and selectPC IFRAME.

Select the cloud environment, perform mobile phone verification, perform hosting settings, select the domain name at will, and set the environment type to Java. OK, a message is displayed, indicating that the application is successfully created.

Return to the basic information, and the application already hasAppid (BAE hosting).

ClickCloud Environment---->Apsaradb---->Create a databaseOf course, it is free of charge.

The cloud environment is successfully deployed,

3. Write test data to the cloud database.

ClickOperationUnderPhpMyAdmin(This is a visual application written in PHP for MySQL database management.) (Note: safari cannot be opened. If you cannot open it, try to use another browser)

Open the interface as follows:

Create a new table and enter its name at will. Here is evantest. The number of fields refers to several variables. Here are three variables. And clickRun, Enter the variable name, type, and length, and clickSave

ClickInsertOption, let's write a group of data, and clickRun

At this point, a group of data is added to the data table.

4. Build a local web application and deploy it on the BAE cloud

Click here to install the plug-in, or click here (one-click installation) to download the integrated development environment.

First, we can see the Baidu logo on installed plug-ins or downloaded eclipse, click and select new bae Project (Java)

My project was named Evan. After the project was created, we found that it was basically the same as the general Web server, and it saved us a lot of steps to build various environments, which was very convenient!

We directly modify the helloworldservlet. Java code (this class is actually servlet) and process the android client requests here.

The file code is as follows:

Package test; import Java. io. dataoutputstream; import Java. io. ioexception; import Java. SQL. connection; import Java. SQL. drivermanager; import Java. SQL. resultset; import Java. SQL. sqlexception; import Java. SQL. statement; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import COM. baidu. bae. API. Util. baeenv; public class helloworldservlet extends httpservlet {/***/Private Static final long serialversionuid = 1l; @ overrideprotected void doget (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {// todo auto-generated method stubstring host = baeenv. getbaeheader (baeenv. bae_env_addr_ SQL _ip); string port = baeenv. getbaeheader (baeenv. bae_env_addr_ SQL _port); ST Ring username = baeenv. getbaeheader (baeenv. bae_env_ak); string Password = baeenv. getbaeheader (baeenv. bae_env_sk); string drivername = "com. mySQL. JDBC. driver "; string dburl =" JDBC: mysql: // "; string servername = Host +": "+ port + "/"; // query the database name to be used by the application from the platform: String databasename = "hdxhgitknqwdecjzxubx"; string connname = dburl + servername + databasename; string SQL = "select * From evantest"; string Info; conn Ection connection = NULL; statement stmt = NULL; resultset rs = NULL; try {class. forname (drivername); // The specific database operation logic connection = drivermanager. getconnection (connname, username, password); stmt = connection. createstatement (); RS = stmt.exe cutequery (SQL); string m_name = "", m_school = "", m_city = ""; dataoutputstream output = new dataoutputstream (resp. getoutputstream (); While (RS. next () {m_name = Rs. getst Ring ("name"); m_school = Rs. getstring ("school"); m_city = Rs. getstring ("city"); resp. setcontenttype ("text/plain"); Info = m_name + "_" + m_school + "_" + m_city; output. writeutf (Info);} output. close ();} catch (classnotfoundexception ex) {// Exception Handling logic} catch (sqlexception e) {// Exception Handling logic} finally {try {If (connection! = NULL) {connection. Close () ;}} catch (sqlexception e ){}}}}

 

Change row 36th to the name of your own database. The database name is provided when you create the database.

Change the name of the table after the first row from to the name of the table.

Click Baidu icon ----> deploy to Bae, and click Project Properties

Fill in the following Table. applicationid is the appid (BAE hosting), access key (API Key), and secure key that we used for mobile phone verification. It is also easy to find on our Baidu application page.

After entering the information, click OK, click deploy, and enter your account and password. After the deployment is successful, the information will be displayed. You can select any one.

Enter the domain name we first entered in the browser, and enter zyfevan.duapp.com in the browser. Enter 1.zyfevan.duapp.com in the browser.

This page is displayed in index. jsp of the project.

Now the server has been built.

5. Obtain server data on the android Client

Create an android project. First, layout the page. The activity_main.xml code is as follows:

<Relativelayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns: Tools = "http://schemas.android.com/tools" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: paddingbottom = "@ dimen/activity_vertical_margin" Android: paddingleft = "@ dimen/plugin" Android: paddingright = "@ dimen/plugin" Android: paddingtop = "@ dimen/plugin" tools: context = ". mainactivity "> <button Android: Id =" @ + ID/m_button "Android: layout_width =" wrap_content "Android: layout_height =" wrap_content "Android: layout_below = "@ + ID/m_textview" Android: layout_centerhorizontal = "true" Android: layout_margintop = "22dp" Android: text = "get something from database"/> <textview Android: id = "@ + ID/m_textview" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_alignparenttop = "true" Android: layout_centerhorizontal = "true" Android: layout_margintop = "62dp" Android: text = "this is the original thing"/> </relativelayout>

 

Then rewrite the main file. The mainactivity. Java code is as follows:

Package COM. example. testtaxi; import Java. io. bytearrayinputstream; import Java. io. datainputstream; import Java. io. ioexception; import java.net. uri; import java.net. urisyntaxexception; import Java. util. stringtokenizer; import Org. apache. HTTP. httpentity; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. parseexception; import Org. apache. HTTP. client. clientprotocolexception; import Org. apache. HTTP. clien T. httpclient; import Org. apache. HTTP. client. methods. httpget; import Org. apache. HTTP. client. methods. httppost; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. util. entityutils; import android. OS. bundle; import android. OS. handler; import android. app. activity; import android. util. log; import android. view. menu; import android. view. view; import android. view. view. onclicklistener; import Android. widget. button; import android. widget. textview; public class mainactivity extends activity {private button m_button; private textview m_textview; private string url = "http://1.zyfevan.duapp.com/hello"; private stringtokenizer Info; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); m_button = (button) findviewbyi D (R. id. m_button); m_textview = (textview) findviewbyid (R. id. m_textview); m_button.setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubnew thread (New runnable () {public void run () {try {httpget httprequest = new httpget (URL); httpresponse = new defaulthttpclient(cmd.exe cute (httprequest); // determine whether the request is successful if (httpresponse. getstatusline (). Getstatuscode () = 200) {httpentity entity = httpresponse. getentity (); If (entity! = NULL) {info = new stringtokenizer (entityutils. tostring (entity, "UTF-8"), "_"); If (info. counttokens () % 3! = 0) {log. V ("error", "not 3 segments");} m_textview.post (New runnable () {public void run () {m_textview.settext ("name:" + info. nexttoken () + "School:" + info. nexttoken () + "City:" + info. nexttoken () ;}}}}}catch (parseexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}). start () ;}}) ;}@ overridepublic Boolean oncreateoptionsmenu (menu) {// inflate the menu; this adds items to the action bar if it is present. getmenuinflater (). inflate (R. menu. main, menu); Return true ;}}

 

Among them, 33rd of the behavior is the link of our servlet.

Code for retrieving data through the network

 

Note the following two points:

  • Network Access is not allowed in the main thread from android4.0, so we can access the network in the 46th thread.
  • Operations on the view cannot be performed in the thread. Therefore, we used the POST method introduced on the official website in line 1 and used runnable to modify the content of the textview.

 

Running effect, just opened the program:

Click the button:

This means we can get data from the cloud database.

 

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.