Android server development (1) Android and PHP connection database verification login function (with all code) _ PHP Tutorial

Source: Internet
Author: User
Tags mysql connect
Android server development (1) Android and PHP connection database verification login function (with all code ). Android server development (1) Android uses PHP to connect to the database and verify the login function (with all the code included. If you do not understand it, leave a message below. Android server development (1) Android and PHP connection database verification login function (with all code)

Let's get started with the code. If you do not understand it, leave a message below.


First look at the server: using the PHP language, deployed on the Sina sae server (built-in database)

Put all the php files in the same directory:


1. classes encapsulated by db. php for database connection


 '2017. 0.0.1 ', 'user' => 'root', 'password' => '', 'database' => 'value'); */private function _ construct () {} static public function getInstance () {// if no instance exists, create the instance and return the created instance if (! (Self: $ _ instance instanceof self) {self: $ _ instance = new self ();} return self: $ _ instance;} public function connect () {if (! Self ::$ _ connectSource) {self ::$ _ connectSource = mysql_connect (SAE_MYSQL_HOST_M. ':'. SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS); // self: $ _ connectSource = @ mysql_connect ($ this-> _ dbConfig ['host'], $ this-> _ dbConfig ['user'], $ this-> _ dbConfig ['password']); if (! Self: $ _ connectSource) {// if the database connection fails // An exception is thrown, when the connnect () function is called, catch throw new Exception ('MySQL connect error' through try catch '. mysql_error); // die ('MySQL connect error '. mysql_error);} mysql_select_db (SAE_MYSQL_DB, self: $ _ connectSource); // mysql_select_db ($ this-> _ dbConfig ['database'], self ::$ _ connectSource ); mysql_query ("set names UTF8", self: $ _ connectSource);} return self: $ _ connectSource ;}}


2. response. php is used to encapsulate communication data (json or xml)


 $ Code, 'message' => $ message, 'data' => $ data,); if ($ type = 'json') {self: json ($ code, $ message, $ data); exit;} elseif ($ type = 'array') {var_dump ($ result);} elseif ($ type = 'xml ') {self: xmlEncode ($ code, $ message, $ data); exit ;} else {// TODO}/*** output communication data in json format * @ param integer $ code Status code * @ param string $ message prompt message * @ param array $ data * return string */public static function json ($ code, $ message = '', $ Data = array () {if (! Is_numeric ($ code) {return '';} $ result = array ('code' => $ code, 'message' => $ message, 'data' => $ data); echo json_encode ($ result); exit ;} /*** output communication data in xml format * @ param integer $ code Status code * @ param string $ message prompt message * @ param array $ data * return string */public static function xmlEncode ($ code, $ message, $ data = array () {if (! Is_numeric ($ code) {return '';} $ result = array ('code' => $ code, 'message' => $ message, 'data' => $ data,); // header ("Content-Type: text/xml"); $ xml ="
 \ N "; $ xml. ="
 
  
\ N "; $ xml. = self: xmlToEncode ($ result); $ xml. ="
 "; Echo $ xml;} public static function xmlToEncode ($ data) {$ xml = $ attr =" "; foreach ($ data as $ key => $ value) {if (is_numeric ($ key) {$ attr = "id = '{$ key}'"; $ key = "item" ;}$ xml. = "<{$ key} {$ attr}>"; $ xml. = is_array ($ value )? Self: xmlToEncode ($ value): $ value; $ xml. ="
 \ N ";}return $ xml ;}}



3. checklogin. php is provided to the client, allowing the client to pass in username and passwd to verify logon using GET requests.

 Connect ();} catch (Exception $ e) {Response: show (403, 'database connection failed');} $ result = mysql_query ($ SQL, $ connect ); $ videos = array (); // The field name key of mysql_fetch_assoc () is set to value, which facilitates client parsing. Get each row. difference: mysql_fetch_array () while ($ video = mysql_fetch_assoc ($ result) {$ videos [] = $ video ;} // in this way, the data obtained from the database is saved to $ videos [], and then the data needs to be converted to interface data if ($ videos) {Response: show (200, 'homepage data obtained successfully', $ videos); // so json data is generated by default, if xml data is needed, need http://...com/list.php when accessing? Format = xml} else {Response: show (400, 'homepage data acquisition failed', $ videos );}



Certificate ------------------------------------------------------------------------------------------------------------------------------------------------------------

By now, the server code has been completed, accepting the client's hhtp get request, querying the database, and verifying that the user name and password are correct. Encapsulate the result into json or xml and output it in the browser. For the client to read.


The following is some Android client code:


The layout file is not displayed, that is, two textviews, two edittexts, and one Button.

Directly access MainActivity. java


Package com. example. bee; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import org. json. JSONArray; import org. json. JSONException; import org. json. JSONObject; import android. app. activity; import android. content. intent; import android. content. sharedPreferences; import android. content. sharedPreferences. editor; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. editText; import android. widget. toast; public class Login extends Activity {/*** logon interface */String result = "", user, passwd; Handler myhandler; EditText userview, passwdview; Button login, register; Thread t; SharedPreferences sp; int code; String realname; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. login); userview = (EditText) findViewById (R. id. login_edt_user); passwdview = (EditText) findViewById (R. id. login_edt_passwd); login = (Button) findViewById (R. id. btn_login); register = (Button) findViewById (R. id. btn_register); sp = getSharedPreferences ("login", MODE_PRIVATE); String getname = sp. getString ("username", null); if (getname = null) {Toast. makeText (Login. this, "sp null", 0 ). show ();} else {Toast. makeText (Login. this, "sp have", 0 ). show (); userview. setText (sp. getString ("username", null); passwdview. setText (sp. getString ("passwd", null);} // Click the event login. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub t = new Thread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubtry {user = userview. getText (). toString (); passwd = passwdview. getText (). toString (); URL url = new URL (" http://luo.sinaapp.com/e/checklogin.php?username= "+ User +" & passwd = "+ passwd); HttpURLConnection urlConnection = (HttpURLConnection) url. openConnection (); InputStreamReader isr = new InputStreamReader (urlConnection. getInputStream (); BufferedReader br = new BufferedReader (isr); result = br. readLine (); // Parse the obtained json data. try {JSONObject object = new JSONObject (result); code = object. getInt ("code"); JSONArray ja = object. getJSONArray ("data"); String data = ja. getString (0); JSONObject secondobject = new JSONObject (data); realname = secondobject. getString ("realname");} catch (JSONException e) {// TODO Auto-generated catch blocke. printStackTrace ();} Message m1 = myhandler. obtainMessage (); if (code = 400) // logon failed {m1.what = 1; myhandler. sendMessage (m1);} else if (code = 200) {// login successful m1.what = 2; myhandler. sendMessage (m1);} else {// other cases: network connection failure, server exception, etc. m1.what = 3; myhandler. sendMessage (m1) ;}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}); t. start () ;}}); // register click event/* register. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubIntent I = new Intent (Login. this, RegisterActivity. class); startActivity (I) ;}}); */myhandler = new Handler () {@ Override public void handleMessage (Message msg) {// TODO Auto-generated method stub super. handleMessage (msg); if (msg. what = 1) {Toast. makeText (Login. this, "incorrect user name or password", 0 ). show ();} else if (msg. what = 2) {Toast. makeText (Login. this, "welcome:" + realname, 0 ). show ();/* log on successfully and save the data locally so that the next automatic login */sp = getSharedPreferences ("login", MODE_PRIVATE); Editor editor = sp. edit (); editor. putString ("username", user); editor. putString ("passwd", passwd); editor. putString ("realname", realname); editor. commit (); Intent I = new Intent (Login. this, MainActivity. class); startActivity (I); finish ();} else {Toast. makeText (Login. this, "network connection failed", 0 ). show ();}}};}}


If you do not know the sharedpreference, let's take a look at it here:

Http://blog.csdn.net/davidluo001/article/details/42290369

If you have other questions, please leave a message and be sure to answer them as soon as possible.

Login (1) Android uses PHP to connect to the database and verify the login function (with all the code included. If you cannot understand it, leave a message with me ....

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.