Gefunden bei: http://www.anddev.org
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
Java
package de.demo.main;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import de.demo.login.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);
}
}
Alles anzeigen
Now the Login Activity..
Login Activity
Java
package de.demo.login;
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 de.demo.main.R;
public class Login extends Activity {
private static final String UPDATE_URL = "http://paddesite.pa.ohost.de/login.php";
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 = (EditText) findViewById(R.id.username);
PassEditText = (EditText) findViewById(R.id.password);
Button button = (Button) findViewById(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 > 0 && passsize > 0) {
progressDialog.show();
String user = UserEditText.getText().toString();
String pass = PassEditText.getText().toString();
doLogin(user, pass);
} else createDialog("Error","Please enter Username and Password");
}
});
button = (Button) findViewById(R.id.cancelbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { quit(false, null); }
});
}
private void quit(boolean success, Intent i) {
setResult( (success) ? -1:0, i);
finish();
}
private void createDialog(String title, String 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) {
final String pw = md5(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 <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", login));
nvps.add(new BasicNameValuePair("password", pw));
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = client.execute(post);
entity = response.getEntity();
InputStream is = entity.getContent();
read(is);
is.close();
if (entity != null) entity.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 String md5(String in) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(in.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
return null;
}
private class LoginContentHandler extends DefaultHandler {
private boolean in_loginTag = false;
private int userID;
private boolean error_occured = false;
public void startElement(String n, String l, String q, Attributes a)
throws SAXException
{
if(l == "login") in_loginTag = true;
if(l == "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(l == "user" && in_loginTag && a.getValue("id") != "")
userID = Integer.parseInt(a.getValue("id"));
}
public void endElement(String n, String l, String q) throws SAXException {
if(l == "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 start, int length) { }
public void startDocument() throws SAXException { }
public void endDocument() throws SAXException { }
}
}
Alles anzeigen
here is the main layout..
main.xml
Java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Username"
/>
<EditText
android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:fadingEdge="horizontal"
android:layout_marginBottom="20dip"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Password"
/>
<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"
android:singleLine="true"
android:fadingEdge="horizontal"
/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="bottom">
<Button
android:id="@+id/okbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login"
/>
<Button
android:id="@+id/cancelbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cancel"
/>
</LinearLayout>
</LinearLayout>
Alles anzeigen
the manifest file...
AndroidManifest.xml
Java
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.demo.main"
android:versionCode="1"
android:versionName="1.0.0">
<application android:icon="@drawable/icon" android:label="LoginDemo">
<activity android:name="de.demo.main.Main" android:label="LoginDemo">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="de.demo.login.Login" android:label="LoginDemo">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
Alles anzeigen
and last but not least the php script on the server....
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('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];
}
?>
Alles anzeigen
the MySQL dump
Code
-- 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');
Alles anzeigen
Zugangsdaten zum testen
username: test
passwort: test