Android Server Development (1) Android Connection database verification login function with PHP (all code included) _php tutorial

Source: Internet
Author: User
Tags mysql connect try catch

Android Server Development (1) Android Connection database verification login function with PHP (all code included)


Don't say anything, directly on the code. If you do not understand the following and I leave a message.


First look at the server: using the PHP language, deployed in the Sina SAE servers (with the database)

Place all of your PHP files in the same directory:


1.db.php packaged classes for connecting to a database


 ' 127.0.0.1 ', ' user ' = ' root ', ' password ' = ', ' database ' = ' value '; */Private Function _construct () {} static public function getinstance () {///If there are no instances, create, then After returning 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 is not successful//throws an exception, when the Connnect () function is called, the throw new Exception is captured by a try catch (' MySQL Connect       Error '. 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 for encapsulating 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 as JSON * @param integer $code Status code * @param string $message message * @param array $data data * retur n 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 as XML * @param integer $code Status code * @param string $message message * @param array $data data * return string*/public STA Tic 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)) {$a TTR = "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, letting the client use GET request, incoming USERNAME,PASSWD authentication login

 
  Connect (); }catch (Exception $e) {    response::show (403, ' Database connection failed ');} $result =mysql_query ($sql, $connect); $videos =array ();//mysql_fetch_assoc () field name key is value, which facilitates client resolution. Each row gets, differs from mysql_fetch_array () while ($video =mysql_fetch_assoc ($result)) {$videos []= $video;} This gets the data from the database to $videos[], then needs to be converted to interface data if ($videos) {response::show (200, ' Home data acquisition success ', $videos);//This generates JSON data by default, If you need XML data, you need to http://...com/list.php?format=xml}else{response::show (400, ' Home data acquisition failed ' at access time, $videos);}



--------------------------------------------------------------------------------------------------------------- ---------------------------------------------

Here the server code is completed, accept the client's HHTP get request, by querying the database, verify the user name, the password is correct. Encapsulates the results into JSON or XML, and outputs them in the browser. For the client to read.


Here is the Android client part code:


The layout file does not show, that is, two TextView and two edittext, and a button

Directly on the 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 {/** * for login 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 has", 0). Show (); Userview.settext (sp.getstring ("username", null));        Passwdview.settext (sp.getstring ("passwd", null));} Login button click event Login.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-gene  Rated method Stub t=new Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubtry {User=userview.gettext (). ToString ();p asswd=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 in 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)//Login failed {M1.what=1;myhandler.sendmessage (m1);} else if (code==200) {//Login succeeded M1.what=2;myhandler.sendmessage (M1);} else{//Other situation: Networking failure, server exception, etc. m1.what=3;myhandler.sendmessage (M1);}} catch (Malformedurlexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Au To-generated catch Blocke.printstacktrace ();}}); T.Start ();}}); Register Click event/*register.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-ge Nerated method Stubintent i=new Intent (login.this,registeractivity.class); startactivity (i);}}); */Myhandler=new Handler () {@Override public void Handlemessage (Message msg) {//TODO Auto-ge        nerated method Stub super.handlemessage (msg);        if (msg.what==1) {Toast.maketext (Login.this, "username or password is incorrect", 0). Show ();        } else if (msg.what==2) {Toast.maketext (login.this, "Welcome you:" +realname, 0). Show (); /* Login successfully write data to local save, so that the next automatic landing */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 above sharedpreference, please look here:

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

If you have any other questions please leave a message, must be answered as soon as possible.

http://www.bkjia.com/PHPjc/941437.html www.bkjia.com true http://www.bkjia.com/PHPjc/941437.html techarticle Android Server Development (1) Android with PHP to connect database authentication login function (with all code) Don't say anything, just on the code. If you do not understand the following and I leave a message. ...

  • 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.