Simple Login for Android (G1)

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Simple Login for Android (G1)

Postby JonnySnip3r » Wed Apr 08, 2009 2:44 pm

Hey guys im new to java and could anyone show me how to make a simple login system? where the username and passwords are store in variables ? or if its not to much trouble using a database i have no idea how to do this .

the reason why i have asked for this is because it would show me how an "if" statement also could you maybe have it where when the user logs in it shows a message "Hello and welcome user" then goes to the next window (where you put the rest of the app) else "you have failed to login")

if this seems weird lol its because im a VB coder and getting grips with a new code is strange haha

thankyou guys :) i will really appreciate this
JonnySnip3r
Developer
Developer
 
Posts: 30
Joined: Wed Apr 08, 2009 1:23 pm

Top

Postby padde » Mon Apr 13, 2009 4:49 am

Okay.. lets start with the main app which calls the login screen..

The Main activity basically starts the Login activity and waits for the result.
If the Login activity returns and the login was correct startup() is called and
the textview shows which user logged in.

Main Activity
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package de.demo.main;
  3.  
  4.  
  5.  
  6. import android.app.Activity;
  7.  
  8. import android.content.Intent;
  9.  
  10. import android.os.Bundle;
  11.  
  12. import android.widget.TextView;
  13.  
  14. import de.demo.login.Login;
  15.  
  16.  
  17.  
  18. public class Main extends Activity {
  19.  
  20.     private TextView tv;
  21.  
  22.    
  23.  
  24.     public void onCreate(Bundle icicle) {
  25.  
  26.         super.onCreate(icicle);
  27.  
  28.  
  29.  
  30.         startActivityForResult(new Intent(Main.this, Login.class), 1);
  31.  
  32.        
  33.  
  34.         tv = new TextView(this);
  35.  
  36.         setContentView(tv);
  37.  
  38.     }
  39.  
  40.    
  41.  
  42.     private void startup(Intent i) {
  43.  
  44.         int user = i.getIntExtra("userid",-1);
  45.  
  46.         tv.setText("UserID: "+String.valueOf(user)+" logged in");
  47.  
  48.     }
  49.  
  50.    
  51.  
  52.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  53.  
  54.         if(requestCode == 1 && resultCode == RESULT_CANCELED)
  55.  
  56.             finish();
  57.  
  58.         else
  59.  
  60.             startup(data);
  61.  
  62.     }
  63.  
  64. }
  65.  
  66.  
Parsed in 0.036 seconds, using GeSHi 1.0.8.4




Now the Login Activity..

Login Activity
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package de.demo.login;
  3.  
  4.  
  5.  
  6. import java.io.IOException;
  7.  
  8. import java.io.InputStream;
  9.  
  10. import java.security.MessageDigest;
  11.  
  12. import java.security.NoSuchAlgorithmException;
  13.  
  14. import java.util.ArrayList;
  15.  
  16. import java.util.List;
  17.  
  18.  
  19.  
  20. import javax.xml.parsers.ParserConfigurationException;
  21.  
  22. import javax.xml.parsers.SAXParser;
  23.  
  24. import javax.xml.parsers.SAXParserFactory;
  25.  
  26.  
  27.  
  28. import org.apache.http.HttpEntity;
  29.  
  30. import org.apache.http.HttpResponse;
  31.  
  32. import org.apache.http.NameValuePair;
  33.  
  34. import org.apache.http.client.entity.UrlEncodedFormEntity;
  35.  
  36. import org.apache.http.client.methods.HttpPost;
  37.  
  38. import org.apache.http.impl.client.DefaultHttpClient;
  39.  
  40. import org.apache.http.message.BasicNameValuePair;
  41.  
  42. import org.apache.http.params.HttpConnectionParams;
  43.  
  44. import org.apache.http.protocol.HTTP;
  45.  
  46. import org.xml.sax.Attributes;
  47.  
  48. import org.xml.sax.InputSource;
  49.  
  50. import org.xml.sax.SAXException;
  51.  
  52. import org.xml.sax.XMLReader;
  53.  
  54. import org.xml.sax.helpers.DefaultHandler;
  55.  
  56.  
  57.  
  58. import android.app.Activity;
  59.  
  60. import android.app.AlertDialog;
  61.  
  62. import android.app.ProgressDialog;
  63.  
  64. import android.content.Intent;
  65.  
  66. import android.os.Bundle;
  67.  
  68. import android.os.Looper;
  69.  
  70. import android.view.View;
  71.  
  72. import android.widget.Button;
  73.  
  74. import android.widget.EditText;
  75.  
  76. import de.demo.main.R;
  77.  
  78.  
  79.  
  80. public class Login extends Activity {
  81.  
  82.     private static final String UPDATE_URL = "http://paddesite.pa.ohost.de/login.php";
  83.  
  84.     public ProgressDialog progressDialog;
  85.  
  86.     private EditText UserEditText;
  87.  
  88.     private EditText PassEditText;
  89.  
  90.    
  91.  
  92.     public void onCreate(Bundle savedInstanceState) {
  93.  
  94.         super.onCreate(savedInstanceState);
  95.  
  96.         setContentView(R.layout.main);
  97.  
  98.  
  99.  
  100.         progressDialog = new ProgressDialog(this);
  101.  
  102.         progressDialog.setMessage("Please wait...");
  103.  
  104.         progressDialog.setIndeterminate(true);
  105.  
  106.         progressDialog.setCancelable(false);
  107.  
  108.        
  109.  
  110.         UserEditText = (EditText) findViewById(R.id.username);
  111.  
  112.         PassEditText = (EditText) findViewById(R.id.password);
  113.  
  114.        
  115.  
  116.         Button button = (Button) findViewById(R.id.okbutton);
  117.  
  118.         button.setOnClickListener(new View.OnClickListener() {
  119.  
  120.             public void onClick(View v) {
  121.  
  122.                 int usersize = UserEditText.getText().length();
  123.  
  124.                 int passsize = PassEditText.getText().length();
  125.  
  126.                 if(usersize > 0 && passsize > 0) {
  127.  
  128.                     progressDialog.show();
  129.  
  130.                     String user = UserEditText.getText().toString();
  131.  
  132.                     String pass = PassEditText.getText().toString();
  133.  
  134.                     doLogin(user, pass);
  135.  
  136.                 } else createDialog("Error","Please enter Username and Password");
  137.  
  138.             }
  139.  
  140.         });
  141.  
  142.        
  143.  
  144.         button = (Button) findViewById(R.id.cancelbutton);
  145.  
  146.         button.setOnClickListener(new View.OnClickListener() {
  147.  
  148.             public void onClick(View v) { quit(false, null); }
  149.  
  150.         });
  151.  
  152.     }
  153.  
  154.  
  155.  
  156.     private void quit(boolean success, Intent i) {
  157.  
  158.         setResult( (success) ? -1:0, i);
  159.  
  160.         finish();
  161.  
  162.     }
  163.  
  164.    
  165.  
  166.     private void createDialog(String title, String text) {
  167.  
  168.         AlertDialog ad = new AlertDialog.Builder(this)
  169.  
  170.         .setPositiveButton("Ok", null)
  171.  
  172.         .setTitle(title)
  173.  
  174.         .setMessage(text)
  175.  
  176.         .create();
  177.  
  178.         ad.show();
  179.  
  180.     }
  181.  
  182.    
  183.  
  184.     private void doLogin(final String login, final String pass) {
  185.  
  186.         final String pw = md5(pass);
  187.  
  188.         Thread t = new Thread() {
  189.  
  190.             public void run() {
  191.  
  192.                 Looper.prepare();
  193.  
  194.                 DefaultHttpClient client = new DefaultHttpClient();
  195.  
  196.                 HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);                
  197.  
  198.                 HttpResponse response;
  199.  
  200.                 HttpEntity entity;        
  201.  
  202.                 try {
  203.  
  204.                     HttpPost post = new HttpPost(UPDATE_URL);
  205.  
  206.                     List <NameValuePair> nvps = new ArrayList <NameValuePair>();
  207.  
  208.                     nvps.add(new BasicNameValuePair("username", login));
  209.  
  210.                     nvps.add(new BasicNameValuePair("password", pw));
  211.  
  212.                     post.setHeader("Content-Type", "application/x-www-form-urlencoded");
  213.  
  214.                     post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
  215.  
  216.                     response = client.execute(post);
  217.  
  218.                     entity = response.getEntity();
  219.  
  220.                     InputStream is = entity.getContent();
  221.  
  222.                     read(is);
  223.  
  224.                     is.close();
  225.  
  226.                     if (entity != null) entity.consumeContent();
  227.  
  228.                 } catch (Exception e) {
  229.  
  230.                     progressDialog.dismiss();
  231.  
  232.                     createDialog("Error", "Couldn't establish a connection");
  233.  
  234.                 }
  235.  
  236.                 Looper.loop();                
  237.  
  238.             }
  239.  
  240.         };
  241.  
  242.         t.start();
  243.  
  244.     }
  245.  
  246.    
  247.  
  248.     private void read(InputStream in) {
  249.  
  250.         SAXParserFactory spf = SAXParserFactory.newInstance();
  251.  
  252.         SAXParser sp;
  253.  
  254.         try {
  255.  
  256.             sp = spf.newSAXParser();
  257.  
  258.             XMLReader xr = sp.getXMLReader();
  259.  
  260.             LoginContentHandler uch = new LoginContentHandler();
  261.  
  262.             xr.setContentHandler(uch);
  263.  
  264.             xr.parse(new InputSource(in));
  265.  
  266.         } catch (ParserConfigurationException e) {
  267.  
  268.         } catch (SAXException e) {
  269.  
  270.         } catch (IOException e) {}
  271.  
  272.     }    
  273.  
  274.    
  275.  
  276.     private String md5(String in) {
  277.  
  278.         MessageDigest digest;
  279.  
  280.         try {
  281.  
  282.             digest = MessageDigest.getInstance("MD5");
  283.  
  284.             digest.reset();        
  285.  
  286.             digest.update(in.getBytes());
  287.  
  288.             byte[] a = digest.digest();
  289.  
  290.             int len = a.length;
  291.  
  292.             StringBuilder sb = new StringBuilder(len << 1);
  293.  
  294.             for (int i = 0; i < len; i++) {
  295.  
  296.                 sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
  297.  
  298.                 sb.append(Character.forDigit(a[i] & 0x0f, 16));
  299.  
  300.             }
  301.  
  302.             return sb.toString();
  303.  
  304.         } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
  305.  
  306.         return null;
  307.  
  308.     }
  309.  
  310.    
  311.  
  312.     private class LoginContentHandler extends DefaultHandler {
  313.  
  314.         private boolean in_loginTag = false;
  315.  
  316.         private int userID;
  317.  
  318.         private boolean error_occured = false;
  319.  
  320.  
  321.  
  322.         public void startElement(String n, String l, String q, Attributes a)
  323.  
  324.             throws SAXException
  325.  
  326.         {
  327.  
  328.             if(l == "login") in_loginTag = true;  
  329.  
  330.             if(l == "error") {
  331.  
  332.                 progressDialog.dismiss();
  333.  
  334.                 if(Integer.parseInt(a.getValue("value")) == 1)
  335.  
  336.                     createDialog("Error", "Couldn't connect to Database");
  337.  
  338.                 if(Integer.parseInt(a.getValue("value")) == 2)
  339.  
  340.                     createDialog("Error", "Error in Database: Table missing");
  341.  
  342.                 if(Integer.parseInt(a.getValue("value")) == 3)
  343.  
  344.                     createDialog("Error", "Invalid username and/or password");
  345.  
  346.                 error_occured = true;
  347.  
  348.             }
  349.  
  350.             if(l == "user" && in_loginTag && a.getValue("id") != "")            
  351.  
  352.                 userID = Integer.parseInt(a.getValue("id"));
  353.  
  354.         }
  355.  
  356.          
  357.  
  358.         public void endElement(String n, String l, String q) throws SAXException {
  359.  
  360.             if(l == "login") {
  361.  
  362.                 in_loginTag = false;
  363.  
  364.                 if(!error_occured) {
  365.  
  366.                     progressDialog.dismiss();
  367.  
  368.                     Intent i = new Intent();
  369.  
  370.                     i.putExtra("userid", userID);
  371.  
  372.                     quit(true,i);
  373.  
  374.                 }
  375.  
  376.             }
  377.  
  378.         }
  379.  
  380.          
  381.  
  382.         public void characters(char ch[], int start, int length) { }
  383.  
  384.         public void startDocument() throws SAXException { }
  385.  
  386.         public void endDocument() throws SAXException { }
  387.  
  388.     }    
  389.  
  390. }
  391.  
  392.  
Parsed in 0.071 seconds, using GeSHi 1.0.8.4


here is the main layout..

main.xml
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.  
  2. <?xml version="1.0" encoding="utf-8"?>
  3.  
  4. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  5.  
  6.    android:orientation="vertical"
  7.  
  8.    android:layout_width="fill_parent"
  9.  
  10.    android:layout_height="fill_parent"
  11.  
  12.    android:gravity="center">
  13.  
  14.    
  15.  
  16.         <TextView  
  17.  
  18.             android:layout_width="fill_parent"
  19.  
  20.             android:layout_height="wrap_content"
  21.  
  22.             android:text="Username"
  23.  
  24.         />
  25.  
  26.         <EditText
  27.  
  28.             android:id="@+id/username"
  29.  
  30.             android:layout_width="fill_parent"
  31.  
  32.             android:layout_height="wrap_content"
  33.  
  34.        android:singleLine="true"
  35.  
  36.        android:fadingEdge="horizontal"
  37.  
  38.        android:layout_marginBottom="20dip"/>
  39.  
  40.         <TextView
  41.  
  42.        android:layout_width="fill_parent"
  43.  
  44.        android:layout_height="wrap_content"
  45.  
  46.        android:text="Password"
  47.  
  48.         />
  49.  
  50.         <EditText
  51.  
  52.        android:id="@+id/password"
  53.  
  54.        android:layout_width="fill_parent"
  55.  
  56.        android:layout_height="wrap_content"
  57.  
  58.        android:password="true"
  59.  
  60.        android:singleLine="true"
  61.  
  62.         android:fadingEdge="horizontal"
  63.  
  64.         />
  65.  
  66.         <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  67.  
  68.        android:orientation="vertical"
  69.  
  70.        android:layout_width="fill_parent"
  71.  
  72.        android:layout_height="fill_parent"
  73.  
  74.        android:gravity="bottom">
  75.  
  76.  
  77.  
  78.         <Button
  79.  
  80.            android:id="@+id/okbutton"
  81.  
  82.            android:layout_width="fill_parent"
  83.  
  84.            android:layout_height="wrap_content"
  85.  
  86.            android:text="Login"
  87.  
  88.        />    
  89.  
  90.         <Button
  91.  
  92.            android:id="@+id/cancelbutton"
  93.  
  94.            android:layout_width="fill_parent"
  95.  
  96.            android:layout_height="wrap_content"
  97.  
  98.            android:text="Cancel"
  99.  
  100.        />
  101.  
  102.     </LinearLayout>      
  103.  
  104. </LinearLayout>
  105.  
  106.  
Parsed in 0.006 seconds, using GeSHi 1.0.8.4


the manifest file...

AndroidManifest.xml
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. <?xml version="1.0" encoding="utf-8"?>
  3.  
  4. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  5.  
  6.       package="de.demo.main"
  7.  
  8.       android:versionCode="1"
  9.  
  10.       android:versionName="1.0.0">
  11.  
  12.     <application android:icon="@drawable/icon" android:label="LoginDemo">
  13.  
  14.         <activity android:name="de.demo.main.Main" android:label="LoginDemo">
  15.  
  16.             <intent-filter>
  17.  
  18.                 <action android:name="android.intent.action.MAIN" />
  19.  
  20.                 <category android:name="android.intent.category.LAUNCHER" />
  21.  
  22.             </intent-filter>
  23.  
  24.         </activity>
  25.  
  26.         <activity android:name="de.demo.login.Login" android:label="LoginDemo">
  27.  
  28.             <intent-filter>
  29.  
  30.                 <action android:name="android.intent.action.VIEW" />
  31.  
  32.                 <category android:name="android.intent.category.DEFAULT" />
  33.  
  34.             </intent-filter>
  35.  
  36.         </activity>        
  37.  
  38.     </application>
  39.  
  40. <uses-permission android:name="android.permission.INTERNET"></uses-permission>    
  41.  
  42. </manifest>
  43.  
  44.  
Parsed in 0.038 seconds, using GeSHi 1.0.8.4



and last but not least the php script on the server....

login.php
Code: Select all
<?php
    unset($_GET);
   
    if( isset($_POST['username']) && isset($_POST['password']) ) {
   
        echo '<?xml version="1.0"?>'."\n";
        echo "<login>\n";
   
        if (!@mysql_connect('host', 'user', 'pass')) { error(1); }
        if (!mysql_select_db('database')) { 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];
    }
?>


Try Username: test and Password: test

Greets
Padde

--- Edited ---
Reason: added missing quote in php code

Thx @ myshoes for pointing that out
Last edited by padde on Sun May 24, 2009 11:49 pm, edited 2 times in total.
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Postby padde » Tue Apr 14, 2009 9:14 pm

Sorry forgot the MySQL dump

Code: Select all
-- phpMyAdmin SQL Dump
-- version 2.6.4-pl4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Erstellungszeit: 14. April 2009 um 22:12
-- Server Version: 4.1.22
-- PHP-Version: 5.2.9
--
-- Datenbank: `paddesite`
--

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

--
-- Tabellenstruktur für Tabelle `auth_table`
--

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 ;

--
-- Daten für Tabelle `auth_table`
--

INSERT INTO `auth_table` VALUES (1, 'test', '098f6bcd4621d373cade4e832627b4f6');


Greets
Padde
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Postby JonnySnip3r » Thu Apr 16, 2009 2:46 am

Thankyou dude this has helped allot thanks :D:D:D
JonnySnip3r
Developer
Developer
 
Posts: 30
Joined: Wed Apr 08, 2009 1:23 pm

Postby JonnySnip3r » Thu Apr 16, 2009 3:26 am

hey dude ya know your PHP script where do i enter the details :S sorry php n00b :) thanks tho dude
JonnySnip3r
Developer
Developer
 
Posts: 30
Joined: Wed Apr 08, 2009 1:23 pm

java servlet (Login.java) instead of login.php

Postby rakesh1908 » Fri Apr 17, 2009 12:08 pm

Hi padde,

This code is very helpful :) .
But, How should I proceed, If I put the java servlet(Login.java) or JSP(login.jsp) instead of login.php?

Thanks in advance..

:)
rakesh1908
Freshman
Freshman
 
Posts: 2
Joined: Wed Apr 08, 2009 3:14 pm

Top

Postby padde » Thu Apr 23, 2009 2:24 pm

Here on request a simple Login that uses your Google Account

Main.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package de.demo.main;
  3.  
  4.  
  5.  
  6. import android.app.Activity;
  7.  
  8. import android.content.Intent;
  9.  
  10. import android.os.Bundle;
  11.  
  12. import android.widget.TextView;
  13.  
  14. import de.demo.login.Login;
  15.  
  16.  
  17.  
  18. public class Main extends Activity {
  19.  
  20.     private TextView tv;
  21.  
  22.    
  23.  
  24.     public void onCreate(Bundle icicle) {
  25.  
  26.         super.onCreate(icicle);
  27.  
  28.  
  29.  
  30.         startActivityForResult(new Intent(Main.this, Login.class), 1);
  31.  
  32.        
  33.  
  34.         tv = new TextView(this);
  35.  
  36.         setContentView(tv);
  37.  
  38.     }
  39.  
  40.    
  41.  
  42.     private void startup(Intent i) {
  43.  
  44.         boolean success = i.getBooleanExtra("success",false);
  45.  
  46.         if(success)
  47.  
  48.             tv.setText("Login accepted");
  49.  
  50.     }
  51.  
  52.    
  53.  
  54.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  55.  
  56.         if(requestCode == 1 && resultCode == RESULT_CANCELED)
  57.  
  58.             finish();
  59.  
  60.         else
  61.  
  62.             startup(data);
  63.  
  64.     }
  65.  
  66. }
  67.  
  68.  
Parsed in 0.040 seconds, using GeSHi 1.0.8.4


Login.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package de.demo.login;
  3.  
  4.  
  5.  
  6. import java.io.IOException;
  7.  
  8. import java.io.InputStream;
  9.  
  10.  
  11.  
  12. import javax.xml.parsers.ParserConfigurationException;
  13.  
  14. import javax.xml.parsers.SAXParser;
  15.  
  16. import javax.xml.parsers.SAXParserFactory;
  17.  
  18.  
  19.  
  20. import org.apache.http.HttpEntity;
  21.  
  22. import org.apache.http.HttpResponse;
  23.  
  24. import org.apache.http.client.methods.HttpGet;
  25.  
  26. import org.apache.http.impl.client.DefaultHttpClient;
  27.  
  28. import org.apache.http.params.HttpConnectionParams;
  29.  
  30. import org.xml.sax.Attributes;
  31.  
  32. import org.xml.sax.InputSource;
  33.  
  34. import org.xml.sax.SAXException;
  35.  
  36. import org.xml.sax.XMLReader;
  37.  
  38. import org.xml.sax.helpers.DefaultHandler;
  39.  
  40.  
  41.  
  42. import android.app.Activity;
  43.  
  44. import android.app.AlertDialog;
  45.  
  46. import android.app.ProgressDialog;
  47.  
  48. import android.content.Intent;
  49.  
  50. import android.os.Bundle;
  51.  
  52. import android.os.Looper;
  53.  
  54. import android.view.View;
  55.  
  56. import android.widget.Button;
  57.  
  58. import android.widget.EditText;
  59.  
  60. import de.demo.main.R;
  61.  
  62.  
  63.  
  64. public class Login extends Activity {
  65.  
  66.     private static final String UPDATE_URL = "https://www.google.com/accounts/LoginAuth";
  67.  
  68.     public ProgressDialog progressDialog;
  69.  
  70.     private EditText UserEditText;
  71.  
  72.     private EditText PassEditText;
  73.  
  74.    
  75.  
  76.     public void onCreate(Bundle savedInstanceState) {
  77.  
  78.         super.onCreate(savedInstanceState);
  79.  
  80.         setContentView(R.layout.main);
  81.  
  82.  
  83.  
  84.         progressDialog = new ProgressDialog(this);
  85.  
  86.         progressDialog.setMessage("Please wait...");
  87.  
  88.         progressDialog.setIndeterminate(true);
  89.  
  90.         progressDialog.setCancelable(false);
  91.  
  92.        
  93.  
  94.         UserEditText = (EditText) findViewById(R.id.username);
  95.  
  96.         PassEditText = (EditText) findViewById(R.id.password);
  97.  
  98.        
  99.  
  100.         Button button = (Button) findViewById(R.id.okbutton);
  101.  
  102.         button.setOnClickListener(new View.OnClickListener() {
  103.  
  104.             public void onClick(View v) {
  105.  
  106.                 int usersize = UserEditText.getText().length();
  107.  
  108.                 int passsize = PassEditText.getText().length();
  109.  
  110.                 if(usersize > 0 && passsize > 0) {
  111.  
  112.                     progressDialog.show();
  113.  
  114.                     String user = UserEditText.getText().toString();
  115.  
  116.                     String pass = PassEditText.getText().toString();
  117.  
  118.                     doLogin(user, pass);
  119.  
  120.                 } else createDialog("Error","Please enter Username and Password");
  121.  
  122.             }
  123.  
  124.         });
  125.  
  126.        
  127.  
  128.         button = (Button) findViewById(R.id.cancelbutton);
  129.  
  130.         button.setOnClickListener(new View.OnClickListener() {
  131.  
  132.             public void onClick(View v) { quit(false, null); }
  133.  
  134.         });
  135.  
  136.     }
  137.  
  138.  
  139.  
  140.     private void quit(boolean success, Intent i) {
  141.  
  142.         setResult( (success) ? -1:0, i);
  143.  
  144.         finish();
  145.  
  146.     }
  147.  
  148.    
  149.  
  150.     private void createDialog(String title, String text) {
  151.  
  152.         AlertDialog ad = new AlertDialog.Builder(this)
  153.  
  154.         .setPositiveButton("Ok", null)
  155.  
  156.         .setTitle(title)
  157.  
  158.         .setMessage(text)
  159.  
  160.         .create();
  161.  
  162.         ad.show();
  163.  
  164.     }
  165.  
  166.    
  167.  
  168.     private void doLogin(final String login, final String pass) {
  169.  
  170.         Thread t = new Thread() {
  171.  
  172.             public void run() {
  173.  
  174.                 Looper.prepare();
  175.  
  176.                 DefaultHttpClient client = new DefaultHttpClient();
  177.  
  178.                 HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);                
  179.  
  180.                 HttpResponse response;
  181.  
  182.                 HttpEntity entity;        
  183.  
  184.                 try {
  185.  
  186.                     HttpGet get = new HttpGet(UPDATE_URL+"?Email="+login+"&Passwd="+pass);
  187.  
  188.                     response = client.execute(get);
  189.  
  190.                     entity = response.getEntity();
  191.  
  192.                     InputStream is = entity.getContent();
  193.  
  194.                     read(is);
  195.  
  196.                     is.close();
  197.  
  198.                     if (entity != null) entity.consumeContent();
  199.  
  200.                 } catch (Exception e) {
  201.  
  202.                     progressDialog.dismiss();
  203.  
  204.                     createDialog("Error", "Couldn't establish a connection");
  205.  
  206.                 }
  207.  
  208.                 Looper.loop();                
  209.  
  210.             }
  211.  
  212.         };
  213.  
  214.         t.start();
  215.  
  216.     }
  217.  
  218.    
  219.  
  220.     private void read(InputStream in) {
  221.  
  222.         SAXParserFactory spf = SAXParserFactory.newInstance();
  223.  
  224.         SAXParser sp;
  225.  
  226.         try {
  227.  
  228.             sp = spf.newSAXParser();
  229.  
  230.             XMLReader xr = sp.getXMLReader();
  231.  
  232.             LoginContentHandler uch = new LoginContentHandler();
  233.  
  234.             xr.setContentHandler(uch);
  235.  
  236.             xr.parse(new InputSource(in));
  237.  
  238.         } catch (ParserConfigurationException e) {
  239.  
  240.         } catch (SAXException e) {
  241.  
  242.         } catch (IOException e) {}
  243.  
  244.     }    
  245.  
  246.    
  247.  
  248.     private class LoginContentHandler extends DefaultHandler {
  249.  
  250.         private boolean in_title = false;
  251.  
  252.         private boolean success;
  253.  
  254.  
  255.  
  256.         public void startElement(String n, String l, String q, Attributes a)
  257.  
  258.             throws SAXException
  259.  
  260.         {
  261.  
  262.             if(l == "title") in_title = true;
  263.  
  264.         }
  265.  
  266.          
  267.  
  268.         public void endElement(String n, String l, String q) throws SAXException {
  269.  
  270.             if(l == "title") {
  271.  
  272.                 in_title = false;
  273.  
  274.                 progressDialog.dismiss();                
  275.  
  276.                 if(success) {
  277.  
  278.                     Intent i = new Intent();
  279.  
  280.                     i.putExtra("success", success);
  281.  
  282.                     quit(success,i);
  283.  
  284.                 } else {
  285.  
  286.                     createDialog("Error", "Invalid username and/or password");
  287.  
  288.                     success = false;
  289.  
  290.                 }
  291.  
  292.             }
  293.  
  294.         }
  295.  
  296.          
  297.  
  298.         public void characters(char ch[], int start, int length) {
  299.  
  300.             if(in_title) {
  301.  
  302.                 String erg = new String(ch, start, length);
  303.  
  304.                 success = (erg.equals("Redirecting")) ? true : false;
  305.  
  306.             }
  307.  
  308.         }
  309.  
  310.        
  311.  
  312.         public void startDocument() throws SAXException { }
  313.  
  314.         public void endDocument() throws SAXException { }
  315.  
  316.     }    
  317.  
  318. }
  319.  
  320.  
Parsed in 0.063 seconds, using GeSHi 1.0.8.4


main.xml
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.  
  2. <?xml version="1.0" encoding="utf-8"?>
  3.  
  4. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  5.  
  6.    android:orientation="vertical"
  7.  
  8.    android:layout_width="fill_parent"
  9.  
  10.    android:layout_height="fill_parent"
  11.  
  12.    android:gravity="center">
  13.  
  14.    
  15.  
  16.         <TextView  
  17.  
  18.             android:layout_width="fill_parent"
  19.  
  20.             android:layout_height="wrap_content"
  21.  
  22.             android:text="Username"
  23.  
  24.         />
  25.  
  26.         <EditText
  27.  
  28.             android:id="@+id/username"
  29.  
  30.             android:layout_width="fill_parent"
  31.  
  32.             android:layout_height="wrap_content"
  33.  
  34.        android:singleLine="true"
  35.  
  36.        android:fadingEdge="horizontal"
  37.  
  38.        android:layout_marginBottom="20dip"/>
  39.  
  40.         <TextView
  41.  
  42.        android:layout_width="fill_parent"
  43.  
  44.        android:layout_height="wrap_content"
  45.  
  46.        android:text="Password"
  47.  
  48.         />
  49.  
  50.         <EditText
  51.  
  52.        android:id="@+id/password"
  53.  
  54.        android:layout_width="fill_parent"
  55.  
  56.        android:layout_height="wrap_content"
  57.  
  58.        android:password="true"
  59.  
  60.        android:singleLine="true"
  61.  
  62.         android:fadingEdge="horizontal"
  63.  
  64.         />
  65.  
  66.         <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  67.  
  68.        android:orientation="vertical"
  69.  
  70.        android:layout_width="fill_parent"
  71.  
  72.        android:layout_height="fill_parent"
  73.  
  74.        android:gravity="bottom">
  75.  
  76.  
  77.  
  78.         <Button
  79.  
  80.            android:id="@+id/okbutton"
  81.  
  82.            android:layout_width="fill_parent"
  83.  
  84.            android:layout_height="wrap_content"
  85.  
  86.            android:text="Login"
  87.  
  88.        />    
  89.  
  90.         <Button
  91.  
  92.            android:id="@+id/cancelbutton"
  93.  
  94.            android:layout_width="fill_parent"
  95.  
  96.            android:layout_height="wrap_content"
  97.  
  98.            android:text="Cancel"
  99.  
  100.        />
  101.  
  102.     </LinearLayout>      
  103.  
  104. </LinearLayout>
  105.  
  106.  
Parsed in 0.006 seconds, using GeSHi 1.0.8.4


AndroidManifest.xml
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.  
  2. <?xml version="1.0" encoding="utf-8"?>
  3.  
  4. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  5.  
  6.      package="de.demo.main"
  7.  
  8.      android:versionCode="1"
  9.  
  10.      android:versionName="1.0.0">
  11.  
  12.     <application android:icon="@drawable/icon" android:label="LoginDemo">
  13.  
  14.         <activity android:name="de.demo.main.Main" android:label="LoginDemo">
  15.  
  16.             <intent-filter>
  17.  
  18.                 <action android:name="android.intent.action.MAIN" />
  19.  
  20.                 <category android:name="android.intent.category.LAUNCHER" />
  21.  
  22.             </intent-filter>
  23.  
  24.         </activity>
  25.  
  26.         <activity android:name="de.demo.login.Login" android:label="LoginDemo">
  27.  
  28.             <intent-filter>
  29.  
  30.                 <action android:name="android.intent.action.VIEW" />
  31.  
  32.                 <category android:name="android.intent.category.DEFAULT" />
  33.  
  34.             </intent-filter>
  35.  
  36.         </activity>        
  37.  
  38.     </application>
  39.  
  40. <uses-permission android:name="android.permission.INTERNET"></uses-permission>    
  41.  
  42. </manifest>
  43.  
  44.  
Parsed in 0.004 seconds, using GeSHi 1.0.8.4



No mysql db or php script needed.. just use your google account login.
I hope i understand the request correct and this is the right solution :)

I should mention that this is not a rock stable login method.. if google
change their login site this no longer works.

And by the way.. in case you wonder.. google sends wrong content-length thats
the reason for this hack like method instead of a clean check etc.

Greets
Padde
Last edited by padde on Thu Aug 06, 2009 4:55 pm, edited 2 times in total.
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Postby songotho » Fri Apr 24, 2009 3:31 am

Great, thanks for your tutorial.
songotho
Experienced Developer
Experienced Developer
 
Posts: 55
Joined: Tue Mar 03, 2009 1:59 am

Postby JonnySnip3r » Fri Apr 24, 2009 2:17 pm

Thanks for the update dude really helped :)
JonnySnip3r
Developer
Developer
 
Posts: 30
Joined: Wed Apr 08, 2009 1:23 pm

Postby aziziti » Wed Apr 29, 2009 11:34 am

Very great tutorial, thanks a lot padde. :D
aziziti
Freshman
Freshman
 
Posts: 8
Joined: Mon Apr 27, 2009 4:30 pm

Postby myshoes » Sun May 24, 2009 10:23 pm

padde wrote:Okay.. lets start with the main app which calls the login screen..

The Main activity basically starts the Login activity and waits for the result.
If the Login activity returns and the login was correct startup() is called and
the textview shows which user logged in.

Main Activity
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.demo.main;
  2.  
  3. import android.app.Activity;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.widget.TextView;
  7. import de.demo.login.Login;
  8.  
  9. public class Main extends Activity {
  10.     private TextView tv;
  11.    
  12.     public void onCreate(Bundle icicle) {
  13.         super.onCreate(icicle);
  14.  
  15.         startActivityForResult(new Intent(Main.this, Login.class), 1);
  16.        
  17.         tv = new TextView(this);
  18.         setContentView(tv);
  19.     }
  20.    
  21.     private void startup(Intent i) {
  22.         int user = i.getIntExtra("userid",-1);
  23.         tv.setText("UserID: "+String.valueOf(user)+" logged in");
  24.     }
  25.    
  26.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  27.         if(requestCode == 1 && resultCode == RESULT_CANCELED)
  28.             finish();
  29.         else
  30.             startup(data);
  31.     }
  32. }
  33.  
Parsed in 0.040 seconds, using GeSHi 1.0.8.4




Now the Login Activity..

Login Activity
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.demo.login;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.security.MessageDigest;
  6. import java.security.NoSuchAlgorithmException;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9.  
  10. import javax.xml.parsers.ParserConfigurationException;
  11. import javax.xml.parsers.SAXParser;
  12. import javax.xml.parsers.SAXParserFactory;
  13.  
  14. import org.apache.http.HttpEntity;
  15. import org.apache.http.HttpResponse;
  16. import org.apache.http.NameValuePair;
  17. import org.apache.http.client.entity.UrlEncodedFormEntity;
  18. import org.apache.http.client.methods.HttpPost;
  19. import org.apache.http.impl.client.DefaultHttpClient;
  20. import org.apache.http.message.BasicNameValuePair;
  21. import org.apache.http.params.HttpConnectionParams;
  22. import org.apache.http.protocol.HTTP;
  23. import org.xml.sax.Attributes;
  24. import org.xml.sax.InputSource;
  25. import org.xml.sax.SAXException;
  26. import org.xml.sax.XMLReader;
  27. import org.xml.sax.helpers.DefaultHandler;
  28.  
  29. import android.app.Activity;
  30. import android.app.AlertDialog;
  31. import android.app.ProgressDialog;
  32. import android.content.Intent;
  33. import android.os.Bundle;
  34. import android.os.Looper;
  35. import android.view.View;
  36. import android.widget.Button;
  37. import android.widget.EditText;
  38. import de.demo.main.R;
  39.  
  40. public class Login extends Activity {
  41.     private static final String UPDATE_URL = "http://paddesite.pa.ohost.de/login.php";
  42.     public ProgressDialog progressDialog;
  43.     private EditText UserEditText;
  44.     private EditText PassEditText;
  45.    
  46.     public void onCreate(Bundle savedInstanceState) {
  47.         super.onCreate(savedInstanceState);
  48.         setContentView(R.layout.main);
  49.  
  50.         progressDialog = new ProgressDialog(this);
  51.         progressDialog.setMessage("Please wait...");
  52.         progressDialog.setIndeterminate(true);
  53.         progressDialog.setCancelable(false);
  54.        
  55.         UserEditText = (EditText) findViewById(R.id.username);
  56.         PassEditText = (EditText) findViewById(R.id.password);
  57.        
  58.         Button button = (Button) findViewById(R.id.okbutton);
  59.         button.setOnClickListener(new View.OnClickListener() {
  60.             public void onClick(View v) {
  61.                 int usersize = UserEditText.getText().length();
  62.                 int passsize = PassEditText.getText().length();
  63.                 if(usersize > 0 && passsize > 0) {
  64.                     progressDialog.show();
  65.                     String user = UserEditText.getText().toString();
  66.                     String pass = PassEditText.getText().toString();
  67.                     doLogin(user, pass);
  68.                 } else createDialog("Error","Please enter Username and Password");
  69.             }
  70.         });
  71.        
  72.         button = (Button) findViewById(R.id.cancelbutton);
  73.         button.setOnClickListener(new View.OnClickListener() {
  74.             public void onClick(View v) { quit(false, null); }
  75.         });
  76.     }
  77.  
  78.     private void quit(boolean success, Intent i) {
  79.         setResult( (success) ? -1:0, i);
  80.         finish();
  81.     }
  82.    
  83.     private void createDialog(String title, String text) {
  84.         AlertDialog ad = new AlertDialog.Builder(this)
  85.         .setPositiveButton("Ok", null)
  86.         .setTitle(title)
  87.         .setMessage(text)
  88.         .create();
  89.         ad.show();
  90.     }
  91.    
  92.     private void doLogin(final String login, final String pass) {
  93.         final String pw = md5(pass);
  94.         Thread t = new Thread() {
  95.             public void run() {
  96.                 Looper.prepare();
  97.                 DefaultHttpClient client = new DefaultHttpClient();
  98.                 HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);                
  99.                 HttpResponse response;
  100.                 HttpEntity entity;        
  101.                 try {
  102.                     HttpPost post = new HttpPost(UPDATE_URL);
  103.                     List <NameValuePair> nvps = new ArrayList <NameValuePair>();
  104.                     nvps.add(new BasicNameValuePair("username", login));
  105.                     nvps.add(new BasicNameValuePair("password", pw));
  106.                     post.setHeader("Content-Type", "application/x-www-form-urlencoded");
  107.                     post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
  108.                     response = client.execute(post);
  109.                     entity = response.getEntity();
  110.                     InputStream is = entity.getContent();
  111.                     read(is);
  112.                     is.close();
  113.                     if (entity != null) entity.consumeContent();
  114.                 } catch (Exception e) {
  115.                     progressDialog.dismiss();
  116.                     createDialog("Error", "Couldn't establish a connection");
  117.                 }
  118.                 Looper.loop();                
  119.             }
  120.         };
  121.         t.start();
  122.     }
  123.    
  124.     private void read(InputStream in) {
  125.         SAXParserFactory spf = SAXParserFactory.newInstance();
  126.         SAXParser sp;
  127.         try {
  128.             sp = spf.newSAXParser();
  129.             XMLReader xr = sp.getXMLReader();
  130.             LoginContentHandler uch = new LoginContentHandler();
  131.             xr.setContentHandler(uch);
  132.             xr.parse(new InputSource(in));
  133.         } catch (ParserConfigurationException e) {
  134.         } catch (SAXException e) {
  135.         } catch (IOException e) {}
  136.     }    
  137.    
  138.     private String md5(String in) {
  139.         MessageDigest digest;
  140.         try {
  141.             digest = MessageDigest.getInstance("MD5");
  142.             digest.reset();        
  143.             digest.update(in.getBytes());
  144.             byte[] a = digest.digest();
  145.             int len = a.length;
  146.             StringBuilder sb = new StringBuilder(len << 1);
  147.             for (int i = 0; i < len; i++) {
  148.                 sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
  149.                 sb.append(Character.forDigit(a[i] & 0x0f, 16));
  150.             }
  151.             return sb.toString();
  152.         } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
  153.         return null;
  154.     }
  155.    
  156.     private class LoginContentHandler extends DefaultHandler {
  157.         private boolean in_loginTag = false;
  158.         private int userID;
  159.         private boolean error_occured = false;
  160.  
  161.         public void startElement(String n, String l, String q, Attributes a)
  162.             throws SAXException
  163.         {
  164.             if(l == "login") in_loginTag = true;  
  165.             if(l == "error") {
  166.                 progressDialog.dismiss();
  167.                 if(Integer.parseInt(a.getValue("value")) == 1)
  168.                     createDialog("Error", "Couldn't connect to Database");
  169.                 if(Integer.parseInt(a.getValue("value")) == 2)
  170.                     createDialog("Error", "Error in Database: Table missing");
  171.                 if(Integer.parseInt(a.getValue("value")) == 3)
  172.                     createDialog("Error", "Invalid username and/or password");
  173.                 error_occured = true;
  174.             }
  175.             if(l == "user" && in_loginTag && a.getValue("id") != "")            
  176.                 userID = Integer.parseInt(a.getValue("id"));
  177.         }
  178.          
  179.         public void endElement(String n, String l, String q) throws SAXException {
  180.             if(l == "login") {
  181.                 in_loginTag = false;
  182.                 if(!error_occured) {
  183.                     progressDialog.dismiss();
  184.                     Intent i = new Intent();
  185.                     i.putExtra("userid", userID);
  186.                     quit(true,i);
  187.                 }
  188.             }
  189.         }
  190.          
  191.         public void characters(char ch[], int start, int length) { }
  192.         public void startDocument() throws SAXException { }
  193.         public void endDocument() throws SAXException { }
  194.     }    
  195. }
  196.  
Parsed in 0.072 seconds, using GeSHi 1.0.8.4


here is the main layout..

main.xml
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.    android:orientation="vertical"
  4.    android:layout_width="fill_parent"
  5.    android:layout_height="fill_parent"
  6.    android:gravity="center">
  7.    
  8.         <TextView  
  9.             android:layout_width="fill_parent"
  10.             android:layout_height="wrap_content"
  11.             android:text="Username"
  12.         />
  13.         <EditText
  14.             android:id="@+id/username"
  15.             android:layout_width="fill_parent"
  16.             android:layout_height="wrap_content"
  17.        android:singleLine="true"
  18.        android:fadingEdge="horizontal"
  19.        android:layout_marginBottom="20dip"/>
  20.         <TextView
  21.        android:layout_width="fill_parent"
  22.        android:layout_height="wrap_content"
  23.        android:text="Password"
  24.         />
  25.         <EditText
  26.        android:id="@+id/password"
  27.        android:layout_width="fill_parent"
  28.        android:layout_height="wrap_content"
  29.        android:password="true"
  30.        android:singleLine="true"
  31.         android:fadingEdge="horizontal"
  32.         />
  33.         <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  34.        android:orientation="vertical"
  35.        android:layout_width="fill_parent"
  36.        android:layout_height="fill_parent"
  37.        android:gravity="bottom">
  38.  
  39.         <Button
  40.            android:id="@+id/okbutton"
  41.            android:layout_width="fill_parent"
  42.            android:layout_height="wrap_content"
  43.            android:text="Login"
  44.        />    
  45.         <Button
  46.            android:id="@+id/cancelbutton"
  47.            android:layout_width="fill_parent"
  48.            android:layout_height="wrap_content"
  49.            android:text="Cancel"
  50.        />
  51.     </LinearLayout>      
  52. </LinearLayout>
  53.  
Parsed in 0.009 seconds, using GeSHi 1.0.8.4


the manifest file...

AndroidManifest.xml
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3.       package="de.demo.main"
  4.       android:versionCode="1"
  5.       android:versionName="1.0.0">
  6.     <application android:icon="@drawable/icon" android:label="LoginDemo">
  7.         <activity android:name="de.demo.main.Main" android:label="LoginDemo">
  8.             <intent-filter>
  9.                 <action android:name="android.intent.action.MAIN" />
  10.                 <category android:name="android.intent.category.LAUNCHER" />
  11.             </intent-filter>
  12.         </activity>
  13.         <activity android:name="de.demo.login.Login" android:label="LoginDemo">
  14.             <intent-filter>
  15.                 <action android:name="android.intent.action.VIEW" />
  16.                 <category android:name="android.intent.category.DEFAULT" />
  17.             </intent-filter>
  18.         </activity>        
  19.     </application>
  20. <uses-permission android:name="android.permission.INTERNET"></uses-permission>    
  21. </manifest>
  22.  
Parsed in 0.041 seconds, using GeSHi 1.0.8.4



and last but not least the php script on the server....

login.php
Code: Select all
<?php
    unset($_GET);
   
    if( isset($_POST['username']) && isset($_POST['password']) ) {
   
        echo '<?xml version="1.0"?>'."\n";
        echo "<login>\n";
   
        if (!@mysql_connect(host', 'user', 'pass')) { error(1); }
        if (!mysql_select_db('database')) { 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];
    }
?>


Try Username: test and Password: test

Greets
Padde


FYI, I don't know if anyone else had an issue with the PHP code but the following line should replace the authors as it was missing a quote around "host":
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  if (!mysql_connect('host', 'user', 'pass')) { error(1); }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4
myshoes
Junior Developer
Junior Developer
 
Posts: 12
Joined: Mon May 04, 2009 2:07 am

Postby padde » Sun May 24, 2009 11:47 pm

Thx for pointing that out myshoes.
I edited the version and added the missing quote.
I guess the failure wasnt discovered before because
most people use the version with the google account.
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Postby shishir.bobby » Sat Sep 05, 2009 5:22 am

hi padde

can u post a small sample program,in which i can send parameters to my server's db through android?
actually wat i want in my application is to send latitude/lognitude and username from android to my server's database...


thanks and regards
hopes for a quick reply :D :D :D
shishir.bobby
Experienced Developer
Experienced Developer
 
Posts: 76
Joined: Thu Apr 09, 2009 11:41 am

Re: Simple Login for Android (G1)

Postby Bourados » Mon Jul 26, 2010 6:00 pm

Hi padde,

I think it works no more :(
User avatar
Bourados
Freshman
Freshman
 
Posts: 3
Joined: Mon Jul 26, 2010 5:22 pm

Re: Simple Login for Android (G1)

Postby niccloud » Thu Oct 14, 2010 9:25 am

Hi. I am new to android. Quite noob. But when i try to enter a new user_id and password, it throws up an error stating that invalid user and password. From what i see in the database, the password seems to be encrypted somehow, could you enlighten me as to the method to go about this issue.
niccloud
Freshman
Freshman
 
Posts: 8
Joined: Tue Oct 12, 2010 4:28 am

Top
Next

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 8 guests