When you create an Android application that requires the user's login, this tip might be useful to you. In this Android tip, I am going to show you how to create a login activity using PHP and MySQL.
To create an Android PHP Login, first you need to login to the phymyadmin and create a database called dbtest. In my machine, I have WampServer installed to work as a web server. In the database, you will create a table called tbluser that has three fields: userid, username, and password. You also need to create an account with "test" user name and "test" password. The account will be used in PHP code to connect to the dbtest database. Then run the sql statement below to insert a sample user.
<?php
include("connection.php");
$user_name=$_POST['username'];
$pwd=$_POST['password'];
$sql="SELECT userid, username, password FROM tbluser WHERE username=? AND password=?";
if ($stmt = $mysqli -> prepare($sql)){
$stmt -> bind_param("ss",$user_name,$pwd);
$stmt -> execute();
$stmt->bind_result($uid,$uname, $pwd);
while ($stmt->fetch())
{
echo $uname;
}
$stmt->close();
}
?>
connection.php file
<?php
$DB_USER='test';
$DB_PASS='test';
$DB_HOST='localhost';
$DB_NAME='dbtest';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
>
<EditText
android:id="@+id/txt_user"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="User Name"
android:inputType="text"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
/>
<EditText
android:id="@+id/txt_pwd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
/>
<Button
android:id="@+id/btlogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="doLogin"
android:layout_gravity="center"
android:text="Log In"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:textColor="#ffffff"
/>
<TextView
android:id="@+id/txt_status"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:gravity="center"
android:textColor="#ff1100"/>
</LinearLayout>
package com.example.andtip;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import android.os.AsyncTask;
public class MainActivity extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog pd;
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
//create a LayoutTransition object
return true;
}
public void doLogin(View view){
EditText txtuser=(EditText)findViewById(R.id.txt_user);
EditText txtpwd=(EditText)findViewById(R.id.txt_pwd);
BackTask task=new BackTask(); task.execute(txtuser.getText().toString().trim(),txtpwd.getText().toString().trim(),null);
}
//background process to validate the user at remove server
private class BackTask extends AsyncTask<String,String,Void>{
String returnText="";
String username;
String password;
protected void onPreExecute(){
super.onPreExecute();
//show process dialog
pd = new ProgressDialog(context);
pd.setTitle("Validating the user");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(String...params){
username=params[0];
password=params[1];
try{
//create HttpClient object
httpclient=new DefaultHttpClient();
//create HttpPost object
httppost= new HttpPost("http://10.0.2.2:8080/login.php");
//add your post data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",username)); nameValuePairs.add(new BasicNameValuePair("password",password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
//create ResponseHander object
ResponseHandler<String> responseHandler = new BasicResponseHandler();
//get responded text
returnText= httpclient.execute(httppost, responseHandler);
}catch(Exception e){
if(pd!=null)
pd.dismiss(); //close the dialog if error occurs
String errmess=e.getMessage();
if(errmess!=null)
Log.e("error from Login",errmess);
}
return null;
}
protected void onPostExecute(Void result){
TextView txtstatus=(TextView)findViewById(R.id.txt_status);
//close the progress dialog
if(pd!=null)
pd.dismiss();
try{
if(returnText.equals(username)){
txtstatus.setText("");
//redirect user to another activity
Intent intent=new Intent(context,SecondActivity.class);
intent.putExtra("user", username);
context.startActivity(intent);
}
else{
txtstatus.setText("Invalid login! Please try again.");
}
}catch(Exception e){}
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".SecondActivity" >
<TextView
android:id="@+id/txtuser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
/>
</RelativeLayout>
package com.example.andtip;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;
public class SecondActivity extends Activity {
String user;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//read data sent from the login activity
Intent intent=getIntent();
Bundle b=intent.getExtras();
user=b.getString("user");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
public void onStart(){
super.onStart();
TextView view=(TextView)findViewById(R.id.txtuser);
view.setText("Welcome "+user);
}
}
Posted by: Dara | post date: 07-16-2014 | Subject: Android Apps Development
|
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.