andriod login registration php mysql json example


Very Simple Example



Register.php

<?php
   
    $etname = $_POST['etname'];
    $etuname = $_POST['etuname'];
    $etpass = $_POST['etpass'];
    $etemail = $_POST['etemail'];
    $etcontact = $_POST['etcontact'];
    $etage = $_POST['etage'];
   
    $response = array();

    $con=mysql_connect("localhost","root","");
    $database=mysql_select_db("beautyton");

    $sql = "insert into register(name,user_name,pass_word,email_id,contact_no,age) values('$etname','$etuname','$etpass','$etemail','$etcontact','$etage')";
   
    $query_exec = mysql_query($sql) or die(mysql_error());
    $rows = mysql_num_rows($query_exec);
   
 if($rows > 0) {
   
     $response["success"] = 0;
     echo json_encode($response);
     }
 else  {
   
    $response["success"] = 1;
    echo json_encode($response);
}
   
    mysql_close();
    
?>



Register_table :






Register.xml

<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:background="@drawable/images6"
    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=".Register" >
    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"       >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

           

            <TableLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/scrollView1" >

                <TableRow
                    android:id="@+id/tableRow1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="6sp" >

                    <TextView
                        android:id="@+id/tv_un"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Name:"
                        android:textColor="#444444"
                        android:textSize="7pt" />

                    <EditText
                        android:id="@+id/name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@android:drawable/editbox_background"
                        android:ems="10" />
                </TableRow>

                <TableRow
                    android:id="@+id/tableRow2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="6sp" >

                    <TextView
                        android:id="@+id/tv_pw"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="User Name:"
                        android:textColor="#444444"
                        android:textSize="7pt" />

                    <EditText
                        android:id="@+id/uname"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@android:drawable/editbox_background"
                        android:ems="10" />
                </TableRow>

                <TableRow
                    android:id="@+id/tableRow3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="6sp" >

                    <TextView
                        android:id="@+id/pass"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Password :"
                        android:textColor="#444444"
                        android:textSize="7pt" />

                    <EditText
                        android:id="@+id/password"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@android:drawable/editbox_background"
                        android:ems="10"
                        android:inputType="textPassword" />
                </TableRow>

                <TableRow
                    android:id="@+id/tableRow4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="6sp" >

                    <TextView
                        android:id="@+id/textmail"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="E-Mail :"
                        android:textColor="#444444"
                        android:textSize="7pt" />

                    <EditText
                        android:id="@+id/mail"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@android:drawable/editbox_background"
                        android:ems="10"
                        android:inputType="textWebEmailAddress" />
                </TableRow>

                <TableRow
                    android:id="@+id/tableRow5"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="6sp" >

                    <TextView
                        android:id="@+id/phone"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Contact No :"
                        android:textColor="#444444"
                        android:textSize="7pt" />

                    <EditText
                        android:id="@+id/contact"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@android:drawable/editbox_background"
                        android:ems="10"
                        android:inputType="phone" />
                </TableRow>

                <TableRow
                    android:id="@+id/tableRow6"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="6sp" >

                    <TextView
                        android:id="@+id/agetext"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Age :"
                        android:textColor="#444444"
                        android:textSize="7pt" />

                    <EditText
                        android:id="@+id/age"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@android:drawable/editbox_background"
                        android:ems="5"
                        android:inputType="number" />
                </TableRow>
              
            </TableLayout>
        </LinearLayout>
    </ScrollView>

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Registeration Form"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <ImageButton
        android:id="@+id/register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/scrollView1"
        android:layout_below="@+id/scrollView1"
        android:layout_marginTop="51dp"
        android:background="@null"
        android:src="@drawable/submit" />

</RelativeLayout>


JSONParser.java :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url,String method, List<NameValuePair> params) {
        // Making HTTP request
                try {
                   
                    // check for request method
                    if(method == "POST"){
                        // request method is POST
                        // defaultHttpClient
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost(url);
                        httpPost.setEntity(new UrlEncodedFormEntity(params));

                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        HttpEntity httpEntity = httpResponse.getEntity();
                        is = httpEntity.getContent();
                       
                    }else if(method == "GET"){
                        // request method is GET
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        String paramString = URLEncodedUtils.format(params, "utf-8");
                        url += "?" + paramString;
                        HttpGet httpGet = new HttpGet(url);

                        HttpResponse httpResponse = httpClient.execute(httpGet);
                        HttpEntity httpEntity = httpResponse.getEntity();
                        is = httpEntity.getContent();
                    }           
                   

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    json = sb.toString();
                    System.out.println("JSONPARSER<><><><>"+json);
                } catch (Exception e) {
                    Log.e("Buffer Error", "Error converting result " + e.toString());
                }

                // try parse the string to a JSON object
                try {
                    jObj = new JSONObject(json);
                } catch (JSONException e) {
                    Log.e("JSON Parser", "Error parsing data " + e.toString());
                }

                // return JSON String
                //System.out.println("OBJECT?????"+jObj);
                return jObj;

            }
    }


Register.java

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.JSONParser;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class Register extends Activity {

    EditText txt1,txt2,txt3,txt4,txt5,txt6;
    ImageButton btnsubmit;
    String etname,etuname,etpass,etemail,etcontact,etage;
    JSONObject json;
    JSONParser jParser = new JSONParser();
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btnsubmit = (ImageButton)findViewById(R.id.register);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        txt1 = (EditText)findViewById(R.id.name);
        txt2 = (EditText)findViewById(R.id.uname);
        txt3 = (EditText)findViewById(R.id.password);
        txt4 = (EditText)findViewById(R.id.mail);
        txt5 = (EditText)findViewById(R.id.contact);
        txt6 = (EditText)findViewById(R.id.age);

        btnsubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                etname = txt1.getText().toString();
                etuname = txt2.getText().toString();
                etpass = txt3.getText().toString();
                etemail = txt4.getText().toString();
                etcontact = txt5.getText().toString();
                etage = txt6.getText().toString();

                if(etname.equals("")||etuname.equals("")||etpass.equals("")||etemail.equals("")||etcontact.equals("")||etage.equals("") )
                {
                    Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
                    return;
                }

                ProgressDialog pDialog = new ProgressDialog(Register.this);
                pDialog.setMessage("Loading..");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();

                try{

                    HttpClient httpclient = new DefaultHttpClient();

                    HttpPost httppost = new HttpPost("http://10.0.2.2/beautyton/register.php");
                    httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);
                    // Building Parameters
                    nameValuePairs.add(new BasicNameValuePair("etname", etname));
                    nameValuePairs.add(new BasicNameValuePair("etuname", etuname));
                    nameValuePairs.add(new BasicNameValuePair("etpass", etpass));
                    nameValuePairs.add(new BasicNameValuePair("etemail", etemail));
                    nameValuePairs.add(new BasicNameValuePair("etcontact", etcontact));
                    nameValuePairs.add(new BasicNameValuePair("etage", etage));
                    // getting JSON string from URL
                    httppost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
                    HttpResponse response = httpclient.execute(httppost);

                    Toast.makeText(getApplicationContext(), "Registered Success", Toast.LENGTH_LONG).show();
                    Intent intent=new Intent(getApplicationContext(),Login.class); 
                    startActivity(intent);   

                }
                catch(Exception e){
                    e.printStackTrace();
                }

            }
        });
    }
}



Login PHP file

<?php
$hostname_localhost ="localhost";
$database_localhost ="beauty";// DB name
$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);

$etuname = $_POST['etuname'];
$etpass = $_POST['etpass'];


$response = array();

$sql = "SELECT user_name,pass_word,age FROM register WHERE user_name = '$etuname' AND pass_word = '$etpass'";
 $q=mysql_query($sql) or die(mysql_error());
   
   
     if (mysql_num_rows($q) > 0) {
     $response["ttable"] = array();
     while ($row = mysql_fetch_array($q)) {
        // temp user array
        $timetab = array();
        $timetab["username"] = $row["user_name"];//table field
        $timetab["password"] = $row["pass_word"];//table filed
        $timetab["age"] = $row["age"];

       
     array_push($response["ttable"], $timetab);
    }
     $response["success"] = 1;
     echo json_encode($response);
     } else {
        $response["success"] = 0;
        $response["message"] = "Not found";
        echo json_encode($response);
     }
   
    mysql_close();
?>

Login.xml :

<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=".Login"
    android:background="@drawable/images6">


<TextView
         android:id="@+id/title"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"       
         android:layout_centerHorizontal="true"
         android:text="Beauty"        
         android:textStyle="bold"
         android:textColor="#444444"
         android:textSize="15pt" />


     <TextView
         android:id="@+id/tv_un"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_below="@+id/title"
         android:layout_centerHorizontal="true"
         android:text="User Name:"
         android:layout_marginTop="10sp"
         android:textColor="#444444"
         android:textSize="10pt" />

     <EditText
         android:id="@+id/et_un"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_below="@+id/tv_un"
         android:layout_centerHorizontal="true"
         android:background="@android:drawable/editbox_background_normal"
         android:ems="10" />

     <TextView
         android:id="@+id/tv_pw"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_below="@+id/et_un"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="20dp"
         android:text="Password:"
         android:textColor="#444444"
         android:textSize="10pt" />

     <EditText
         android:id="@+id/et_pw"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_below="@+id/tv_pw"
         android:layout_centerHorizontal="true"
         android:background="@android:drawable/editbox_background"
         android:ems="10"
         android:password="true" />

     <ImageButton
         android:id="@+id/imageButton2"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_below="@+id/imageButton1"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="15dp"
         android:background="@null"
         android:src="@drawable/registerr" />

     <ImageButton
         android:id="@+id/imageButton1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_below="@+id/et_pw"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="32dp"
         android:background="@null"
         android:src="@drawable/loginbuttonn" />

    </RelativeLayout>


Login.java :

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.example.*;

public class Login extends Activity {

    ImageButton btnlogin,btnregister;
    EditText txt1,txt2;
    String etuname,etpass;
    String url_table="http://10.0.2.2/beautyton/login.php";
    JSONParser jParser = new JSONParser();
    JSONArray jsonArray;
    String dbname,dbpass,dbage;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        txt1 = (EditText)findViewById(R.id.et_un);
        txt2 = (EditText)findViewById(R.id.et_pw);

        btnlogin = (ImageButton)findViewById(R.id.imageButton1);
        btnregister = (ImageButton)findViewById(R.id.imageButton2);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        btnregister.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getApplicationContext(), Register.class);
                startActivity(intent);

            }
        });

        btnlogin.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                etuname = txt1.getText().toString();
                etpass = txt2.getText().toString();

                System.out.println(etuname);
                System.out.println(etpass);

                if(etuname.equals("")||etpass.equals("") )
                {
                    Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
                    return;
                }

                ProgressDialog pDialog = new ProgressDialog(Login.this);
                pDialog.setMessage("Loading..");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("etuname",etuname));
                params.add(new BasicNameValuePair("etpass",etpass));
                System.out.println("PARAMETER++++++++"+params);
                // getting JSON string from URL
                JSONObject json = jParser.getJSONFromUrl(url_table, "POST", params);
                Log.d("RESPONSE", json.toString());

                try {

                    int suc=json.getInt("success");

                    if(suc==1) {
                       
                        JSONArray jsonArray = json.getJSONArray("ttable");
                        for(int i=0;i<jsonArray.length();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                           
                            dbage = jsonObject.getString("age");
                           
                        }
                        System.out.println("DBAGE<><>"+dbage);
                       
                        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString("dbage", dbage);
                        editor.commit();

                        Intent intent = new Intent(getApplicationContext(), Activity_Category.class);
                        startActivity(intent);
                    }
                    else{
                        Toast.makeText(getApplicationContext(), "Login Error", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(getApplicationContext(), Login.class);
                        startActivity(intent);
                    }
                }
                catch(Exception e){
                    e.printStackTrace();

                }

            }
        });
    }
}


Login_table :


No comments:

Post a Comment

AUTHOR