Here i explained a designing login interfaces, it has no functionality. In this tutorial i am explaining how to build login form in android using php,mysql.This tutorial covers how to build api using php and mysql.
API (Application Programming Interface)
Accepting requests by GET/POST methods
Interact with PHP classes to get data from database or store in database.
1.Creating MySQL Database and Tables
A i am writing php code for connecting mysql database to maintain users. Open your mysqlconsole or phpmyadmin and run following query to create database.
a)create database mydatabase
b)use mydatabase
c)create table tbl_user( username varchar(20), password varchar(20));
2.Building PHP
Following are the files are required to build api in php. You can find description of file below.
check.php - This file contains variables to connect to datbase and and retrive value form it.
Check.php:
<?php
$hostname_localhost ="localhost";
$database_localhost ="mydatabase";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from tbl_user where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
}
else {
echo "User Found";
}
?>
3.Starting Android Project
Until now we wrote a server side programming to connect database. Next thing is build android app to interact with database. In this project i am coding simple app which will have two screen login screen, Success screen. So lets get started by creating new project in Eclipse IDE
1. Create a new project by going to File ⇒ New Android Project. Fill all the details and name your activity as Androidphpconnectiondemo.
2. Next step is to create a new package to store all our library files. Right Click on ⇒ src ⇒ New ⇒ Package and name it as library.
4.Database Handler
In the application to retrieve user information i am using mysql datbase. So create new class in you library package folder and name it as androidphpconnectiondemo.java and fill the class with following code. This class file has function to handle database operation like retrieve user information.
public class AndroidPHPConnectionDemo extends Activity
{
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.username);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(AndroidPHPConnectionDemo.this, "", "Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/my_folder_inside_htdocs/check.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));
// $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(AndroidPHPConnectionDemo.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert()
{
AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable()
{
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
5. User Functions
Create a new class file under libray package name it as userpage.java this class will have function to handle all user event.
Android application testing localhost use http://localhost/your phpfile location with".phpfile"
Normally localhost will run on port http://localhost/. In avd to connect to localhost you need to use url http://10.0.2.2/
if you want to deploy your api on website then use the url http://yoursite.com/api/
public class UserPage extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.userpage);
}
}
6. Designing the Screens
As of now we have developed the class file in this application. Next thing we have to build screen for useinteraction. we need two screen loginscreen and success screen.
Create 3xml file under res->layout folder and name them as userpage.xml. In main.xml i build login screen.
Main.xml:
<?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:layout_gravity="center|center_vertical" >
<TextView
android:id="@+id/tv0"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login Form"
android:textSize="20sp"
android:gravity="center"
android:textStyle="bold" />
<TextView
android:id="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Username" />
<EditText
android:text=""
android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true">
</EditText>
<TextView
android:id="@+id/tv2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Password" />
<EditText
android:text=""
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true">
</EditText>
<Button
android:text="Login"
android:id="@+id/Button01"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
userpage.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:text="Login Success."
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
7.AndroidManifest
Dont forget to update you androidmanifest.xml file. Change following modifications add internet permission and add entries of each activity.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.coderzheaven"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidPHPConnectionDemo"
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=".UserPage"
android:label="@string/app_name" />
</application>
</manifest>
8. Make sure the above file you have placed in following image
9.Final Output