Ví dụ về một trang login trong Android. (PHP, MySQL, Android)

Thảo luận trong 'Điện thoại, viễn thông' bắt đầu bởi g08ct, 8/9/12.

  1. g08ct New Member

    g08ct

    Tham gia ngày:
    15/8/12
    Bài viết:
    1,116
    Đã được thích:
    55
    Điểm thành tích:
    0
    Giới tính:
    Nam
    Ứng dụng gồm 2 activity: Main, Login. Activity Login sẽ bao gồm giao diện đăng nhập gồm 2 textbox, 2 button: cancel, login. Activity Main dùng để hiển thị một chuỗi.
    Phía server, mình dùng ngôn ngữ PHP, và cơ sở dữ liệu là MySQL.

    main.xml

    Mã:
    <?xml version="1.0" encoding="utf-8"?>
    <AbsoluteLayout
    android:id="@+id/widget57"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <TextView
    android:id="@+id/widget51"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Username"
    android:layout_x="0px"
    android:layout_y="0px"
    >
    </TextView>
    <EditText
    android:id="@+id/username"
    android:layout_width="fill_parent"
    android:layout_height="42px"
    android:layout_x="0px"
    android:layout_y="19px"
    >
    </EditText>
    <TextView
    android:id="@+id/widget53"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Password"
    android:layout_x="0px"
    android:layout_y="70px"
    >
    </TextView>
    <EditText
    android:id="@+id/password"
    android:layout_width="fill_parent"
    android:layout_height="42px"
    android:password="true"
    android:layout_x="0px"
    android:layout_y="89px"
    >
    </EditText>
    <Button
    android:id="@+id/okbutton"
    android:layout_width="127px"
    android:layout_height="wrap_content"
    android:text="Login"
    android:layout_x="20px"
    android:layout_y="162px"
    >
    </Button>
    <Button
    android:id="@+id/cancelbutton"
    android:layout_width="122px"
    android:layout_height="wrap_content"
    android:text="Cancel"
    android:layout_x="180px"
    android:layout_y="162px"
    >
    </Button>
    </AbsoluteLayout>
    Main Activity

    Mã:
    package com.android.internet;
    
    import android.app.Activity; 
    import android.content.Intent; 
    import android.os.Bundle; 
    import android.widget.TextView; 
    import com.android.internet.Login; 
    
    public class Main extends Activity { 
        private TextView tv; 
        
        public void onCreate(Bundle icicle) { 
            super.onCreate(icicle); 
    
            startActivityForResult(new Intent(Main.this, Login.class), 1); 
            
            tv = new TextView(this); 
            setContentView(tv); 
        } 
        
        private void startup(Intent i) { 
            int user = i.getIntExtra("userid",-1); 
            tv.setText("UserID: "+String.valueOf(user)+" logged in"); 
        } 
        
        protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
            if(requestCode == 1 && resultCode == RESULT_CANCELED) 
                finish(); 
            else 
                startup(data); 
        } 
    }
    Login Activity

    PHP:
    package com.android.internet;

    import java.io.IOException
    import java.io.InputStream
    import java.security.MessageDigest
    import java.security.NoSuchAlgorithmException
    import java.util.ArrayList
    import java.util.List; 

    import javax.xml.parsers.ParserConfigurationException
    import javax.xml.parsers.SAXParser
    import javax.xml.parsers.SAXParserFactory

    import org.apache.http.HttpEntity
    import org.apache.http.HttpResponse
    import org.apache.http.NameValuePair
    import org.apache.http.client.entity.UrlEncodedFormEntity
    import org.apache.http.client.methods.HttpPost
    import org.apache.http.impl.client.DefaultHttpClient
    import org.apache.http.message.BasicNameValuePair
    import org.apache.http.params.HttpConnectionParams
    import org.apache.http.protocol.HTTP
    import org.xml.sax.Attributes
    import org.xml.sax.InputSource
    import org.xml.sax.SAXException
    import org.xml.sax.XMLReader
    import org.xml.sax.helpers.DefaultHandler

    import android.app.Activity
    import android.app.AlertDialog
    import android.app.ProgressDialog
    import android.content.Intent
    import android.os.Bundle
    import android.os.Looper
    import android.view.View
    import android.widget.Button
    import android.widget.EditText
    import com.android.internet.R

    public class 
    Login extends Activity 
        private static final 
    String UPDATE_URL "http://192.168.1.100/login/login.php"
        
    // Chú ý: chỗ địa chỉ 192.168.1.100 mình thay bằng localhost, hoặc là 127.0.0.1 thì đều không thể kết nối được. Nếu bạn nào kết nối được thì reply lại cho mình với nhá.
        
    public ProgressDialog progressDialog
        private 
    EditText UserEditText
        private 
    EditText PassEditText
        
        public 
    void onCreate(Bundle savedInstanceState) { 
            
    super.onCreate(savedInstanceState); 
            
    setContentView(R.layout.main); 

            
    progressDialog = new ProgressDialog(this); 
            
    progressDialog.setMessage("Please wait..."); 
            
    progressDialog.setIndeterminate(true); 
            
    progressDialog.setCancelable(false); 
            
            
    UserEditText = (EditTextfindViewById(R.id.username); 
            
    PassEditText = (EditTextfindViewById(R.id.password); 
            
            
    Button button = (ButtonfindViewById(R.id.okbutton); 
            
    button.setOnClickListener(new View.OnClickListener() { 
                public 
    void onClick(View v) { 
                    
    int usersize UserEditText.getText().length(); 
                    
    int passsize PassEditText.getText().length(); 
                    if(
    usersize && passsize 0) { 
                        
    progressDialog.show(); 
                        
    String user UserEditText.getText().toString(); 
                        
    String pass PassEditText.getText().toString(); 
                        
    doLogin(userpass); 
                    } else 
    createDialog("Error","Please enter Username and Password"); 
                } 
            }); 
            
            
    button = (ButtonfindViewById(R.id.cancelbutton); 
            
    button.setOnClickListener(new View.OnClickListener() { 
                public 
    void onClick(View v) { quit(falsenull); } 
            }); 
        } 

        private 
    void quit(boolean successIntent i) { 
            
    setResult( (success) ? -1:0i); 
            
    finish(); 
        } 
        
        private 
    void createDialog(String titleString text) { 
            
    AlertDialog ad = new AlertDialog.Builder(this
            .
    setPositiveButton("Ok"null
            .
    setTitle(title
            .
    setMessage(text
            .
    create(); 
            
    ad.show(); 
        } 
        
        private 
    void doLogin(final String login, final String pass) { 
            
    Thread t = new Thread() { 
                public 
    void run() { 
                    
    Looper.prepare(); 
                    
    DefaultHttpClient client = new DefaultHttpClient(); 
                    
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);                 
                    
    HttpResponse response
                    
    HttpEntity entity;         
                    try { 
                        
    HttpPost post = new HttpPost(UPDATE_URL); 
                        List <
    NameValuePairnvps = new ArrayList <NameValuePair>(); 
                        
    nvps.add(new BasicNameValuePair("username"login)); 
                        
    nvps.add(new BasicNameValuePair("password"pass)); 
                        
    post.setHeader("Content-Type""application/x-www-form-urlencoded"); 
                        
    post.setEntity(new UrlEncodedFormEntity(nvpsHTTP.UTF_8)); 
                        
    response client.execute(post); 
                        
    entity response.getEntity(); 
                        
    InputStream is entity.getContent(); 
                        
    read(is); 
                        
    is.close(); 
                        if (
    entity != nullentity.consumeContent(); 
                    } catch (
    Exception e) { 
                        
    progressDialog.dismiss(); 
                        
    createDialog("Error""Couldn't establish a connection"); 
                    } 
                    
    Looper.loop();                 
                } 
            }; 
            
    t.start(); 
        } 
        
        private 
    void read(InputStream in) { 
            
    SAXParserFactory spf SAXParserFactory.newInstance(); 
            
    SAXParser sp
            try { 
                
    sp spf.newSAXParser(); 
                
    XMLReader xr sp.getXMLReader(); 
                
    LoginContentHandler uch = new LoginContentHandler(); 
                
    xr.setContentHandler(uch); 
                
    xr.parse(new InputSource(in)); 
            } catch (
    ParserConfigurationException e) { 
            } catch (
    SAXException e) { 
            } catch (
    IOException e) {} 
        }     
        
        
        private class 
    LoginContentHandler extends DefaultHandler 
            private 
    boolean in_loginTag false
            private 
    int userID
            private 
    boolean error_occured false

            public 
    void startElement(String nString lString qAttributes a
                
    throws SAXException 
            

                if(
    == "login"in_loginTag true;   
                if(
    == "error") { 
                    
    progressDialog.dismiss(); 
                    if(
    Integer.parseInt(a.getValue("value")) == 1
                        
    createDialog("Error""Couldn't connect to Database"); 
                    if(
    Integer.parseInt(a.getValue("value")) == 2
                        
    createDialog("Error""Error in Database: Table missing"); 
                    if(
    Integer.parseInt(a.getValue("value")) == 3
                        
    createDialog("Error""Invalid username and/or password"); 
                    
    error_occured true
                } 
                if(
    == "user" && in_loginTag && a.getValue("id") != "")             
                    
    userID Integer.parseInt(a.getValue("id")); 
            } 
              
            public 
    void endElement(String nString lString qthrows SAXException 
                if(
    == "login") { 
                    
    in_loginTag false
                    if(!
    error_occured) { 
                        
    progressDialog.dismiss(); 
                        
    Intent i = new Intent(); 
                        
    i.putExtra("userid"userID); 
                        
    quit(true,i); 
                    } 
                } 
            } 
              
            public 
    void characters(char ch[], int startint length) { } 
            public 
    void startDocument() throws SAXException { } 
            public 
    void endDocument() throws SAXException { } 
        }     
    }
    AndroidManifest.xml

    Mã:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.android.internet"
          android:versionCode="1"
          android:versionName="1.0">
        <application android:icon="@drawable/icon" android:label="@string/app_name">
            <activity android:name=".Main"
                      android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    		<activity android:name=".Login"
                      android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </activity>
        </application>
        <uses-sdk android:minSdkVersion="7" />
    	<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    
    </manifest>
    Cơ sở dữ liệu

    Mã:
    CREATE TABLE IF NOT EXISTS 'auth_table' ( 
      'user_id' int(10) unsigned NOT NULL auto_increment, 
      'username' varchar(20) NOT NULL default '', 
      'password' varchar(32) NOT NULL default '', 
      PRIMARY KEY  ('user_id'), 
      UNIQUE KEY 'username' ('username') 
    ) TYPE=MyISAM AUTO_INCREMENT=2 AUTO_INCREMENT=2 ;
    Login.php

    PHP:
    <?php 
        
    unset($_GET); 
        
        if( isset(
    $_POST['username']) && isset($_POST['password']) ) { 
        
            echo 
    '<?xml version="1.0"?>'."\n"
            echo 
    "<login>\n"
        
            if (!@
    mysql_connect('localhost','root','')) { error(1); } 
            if (!
    mysql_select_db('login')) { error(2); } 
        
            if(
    get_magic_quotes_gpc()) { 
                
    $login stripslashes($_POST['username']); 
                
    $pass  stripslashes($_POST['password']); 
            } else { 
                
    $login $_POST['username']; 
                
    $pass  $_POST['password']; 
            } 
        
            unset(
    $_POST); 
            
            
    $kid login($login$pass); 
            if(
    $kid == -1) { 
                
    error(3); 
            } else { 
                
    printf('    <user id="%d"/>'."\n",$kid); 
            } 
                    
            echo 
    "</login>"
        } 

        function 
    error($ec) { 
            
    printf('    <error value="%d"/>'."\n".'</login>',$ec); 
            die(); 
        } 

        function 
    login($login$pass) { 
            
    $select "SELECT user_id FROM auth_table "
            
    $where "WHERE username = '%s' AND password = '%s'"
            
    $fixedlogin mysql_real_escape_string($login); 
            
    $fixedpass  mysql_real_escape_string($pass); 
            
    $query sprintf($select.$where$fixedlogin$fixedpass); 
            
    $result mysql_query($query); 
            if(
    mysql_num_rows($result) != 1) { return -1; }    
            
    $row mysql_fetch_row($result); 
            return 
    $row[0]; 
        } 
    ?>


    kakalot
     
    Đang tải...
  2. LeoSkill New Member

    LeoSkill

    Tham gia ngày:
    27/5/13
    Bài viết:
    3
    Đã được thích:
    0
    Điểm thành tích:
    0
    Giới tính:
    Nam
    vậy .net thì sao bạn? Như web service đấy?
     

Chia sẻ trang này