Friday, June 3, 2016

Registration & Login with Server (using localhost & MySql)

"Jai Saraswati Maa"

Dear All today i am uploading a superb example of how to create registration form with server also including Login functionality.
Before doing Android coding please create database with XAMPP server as
Database name - mydb
Table name - info
Table columns are      name , user_name , user_pass all TEXT type.

Ok......

Now create a folder in C:\xampp\htdocs    as mapp which contains controller part means php files.

I have created three files in php those are
First file is                   init.php      coding is

<?php
$server_name = "localhost";
$sql_user = "root";
$sql_pass= "";
$db_name="mydb";
$con = mysqli_connect($server_name,$sql_user,$sql_pass,$db_name);
if(!$con)
{
//echo "Connection Failed".mysqli_connect_error();
}
else
{
//echo "Connected with Database";

}
?>

Second file is for Registration  purpose  which is reg.php

<?php
require "init.php";
$name = $_POST["user"];
$user_name=$_POST["user_name"];
$user_pass=$_POST["user_pass"];
$sql_query="insert into info values('$name','$user_name','$user_pass');";
if(mysqli_query($con,$sql_query))
{
//echo "Data Inserted....";
}
else
{
//echo "Error....";
}

?>

Third file is for Login purpose which is  log.php

<?php
require "init.php";
$user_name=$_POST["login_name"];
$user_pass=$_POST["login_pass"];
$sql_query="select name from info where user_name like '$user_name' and user_pass like '$user_pass';";
$res = mysqli_query($con,$sql_query);
if(mysqli_num_rows($res)>0)
{
$row= mysqli_fetch_assoc($res);
$name = $row["name"];
echo "Welcome....".$name;
}
else
{
echo "Error....";
}

?>


********************  Now come on the Android part *************
Please add permission in manifest file as

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

1.  Output will be like this
A. Main Screen


B. Registration Screen




2. Layout files

A.  activity_main.xml     is as

<?xml version="1.0" encoding="utf-8"?>

<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="com.example.student.webapplocal.MainActivity">
    <TextView        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Login Form"

        android:textSize="25dp"

        android:textStyle="bold"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:id="@+id/textView" />

    <EditText        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/userName"

        android:hint="User Name"        android:layout_below="@+id/textView"

        android:layout_marginTop="52dp"

        android:layout_alignParentStart="true"

        android:layout_alignParentEnd="true" />

    <EditText        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:inputType="textPassword"

        android:ems="10"        android:id="@+id/userPass"

        android:hint="User Password"

        android:layout_below="@+id/userName"

        android:layout_alignParentStart="true"

        android:layout_marginTop="42dp"

        android:layout_alignEnd="@+id/userName" />

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Login"        android:id="@+id/logBut"

        android:layout_marginTop="60dp"

        android:onClick="userLogin"

        android:layout_below="@+id/userPass"

        android:layout_alignParentStart="true" />

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Register"        android:id="@+id/regBut"

        android:onClick="userReg"

        android:layout_alignTop="@+id/logBut"

        android:layout_alignEnd="@+id/userPass" />
</RelativeLayout>

B. activity_register.xml is as 

<?xml version="1.0" encoding="utf-8"?>

<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="com.exam.ravi.webapplocalhostex1.Register"

    android:onClick="regMe">

    <TextView        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceLarge"

        android:text="Registration Form"

        android:id="@+id/textView2"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true" />

    <EditText        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/editTextName"

        android:hint="Name"        android:layout_below="@+id/textView2"

        android:layout_alignParentEnd="true"

        android:layout_alignParentStart="true" />

    <EditText

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/editTextUN"

        android:hint="User Name"        android:layout_below="@+id/editTextName"

        android:layout_alignParentStart="true"

        android:layout_alignEnd="@+id/editTextName" />

    <EditText

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:inputType="textPassword"

        android:ems="10"        android:id="@+id/editTextUP"

        android:hint="User Pass"        android:layout_below="@+id/editTextUN"

        android:layout_alignParentEnd="true"

        android:layout_alignParentStart="true" />

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Reg"        android:id="@+id/button"

        android:layout_marginTop="44dp"

        android:layout_below="@+id/editTextUP"

        android:layout_centerHorizontal="true"

        android:onClick="regMe" />
</RelativeLayout>

3.......... Java codes

A. MainActivity.java is as 

package com.example.student.webapplocal;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    EditText LogName,LogPsss;
    String logName,logPass;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LogName  = (EditText) findViewById(R.id.userName);
        LogPsss  = (EditText) findViewById(R.id.userPass);
    }

    public void userReg(View view)
    {
        startActivity(new Intent(this,Register.class));
    }
    public void userLogin(View view)
    {
        logName =LogName.getText().toString();
        logPass = LogPsss.getText().toString();
        String method ="login";
        BackgroundTask backgroundTask = new BackgroundTask(this);
        backgroundTask.execute(method, logName, logPass);
    }
}

B. Register.java is as 

package com.example.student.webapplocal;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class Register extends AppCompatActivity {
    EditText Name,UName,Upass;
    String user,username,userpass;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        Name = (EditText) findViewById(R.id.editTextName);
        UName = (EditText) findViewById(R.id.editTextUN);
        Upass = (EditText) findViewById(R.id.editTextUP);
    }
    public void regMe(View view)
    {
        user = Name.getText().toString();
        username = UName.getText().toString();
        userpass = Upass.getText().toString();
        String method= "register";
        BackgroundTask backgroundTask= new BackgroundTask(this);
        backgroundTask.execute(method,user,username,userpass);
        finish();

    }
}

C. BackgroundTask.java is as 

package com.example.student.webapplocal;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class BackgroundTask extends AsyncTask<String,String,String> {
    Context ctx;
    AlertDialog alertDialog;
    BackgroundTask(Context ctx) {
        this.ctx = ctx;
    }

    @Override    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(ctx).create();
        alertDialog.setTitle("Login Information.... ");
    }

    @Override    protected String doInBackground(String... params) {
        String reg_url = "http://10.0.2.2/mapp/reg.php";
        String login_url = "http://10.0.2.2/mapp/log.php";

        String method = params[0];
        if (method.equals("register")) {
            String name = params[1];
            String user_name = params[2];
            String user_pass = params[3];
            try {
                URL url = new URL(reg_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)
                                       url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream OS = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new 
                           BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String data = URLEncoder.encode("user", "UTF-8") + "=" 
                                         URLEncoder.encode(name, "UTF-8") + "&" +
                        URLEncoder.encode("user_name", "UTF-8") + "=" 
                        URLEncoder.encode(user_name, "UTF-8") + "&" +
                        URLEncoder.encode("user_pass", "UTF-8") + "=" +
                        URLEncoder.encode(user_pass, "UTF-8");

                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream IS = httpURLConnection.getInputStream();
                IS.close();
                return "Registration Success";
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else if (method.equals("login")) {
            String login_name = params[1];
            String login_pass = params[2];
            try {
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) 
                                                      url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new
                BufferedWriter(new OutputStreamWriter (outputStream, "UTF-8"));
                String data = URLEncoder.encode("login_name", "UTF-8") + "=" 
                                    URLEncoder.encode(login_name, "UTF-8") + "&" +
                        URLEncoder.encode("login_pass", "UTF-8") + "=" 
                                URLEncoder.encode(login_pass, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new 
                                InputStreamReader(inputStream, "iso-8859-1"));
                String response = "";
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    response = response + line;

                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    }

    @Override    protected void onPostExecute(String result) {
        if (result.equals("Registration Success")) {
            Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
        } else {
           alertDialog.setMessage(result);
            alertDialog.show();
        }
    }
}


No comments:

Post a Comment