Login and
Registration Using Php MySQL in Android Example.
1.Take user permission in AndroidManifest.xml as given below and also add
dependencies in build.gradle .
AndroidManifest
<uses-permission android:name="android.permission.INTERNET"
/>
build.gradle
compile 'com.loopj.android:android-async-http:1.4.5' compile files("${android.getSdkDirectory().getAbsolutePath()}" + File.separator +
"platforms" + File.separator + "android-23" + File.separator + "optional" +
File.separator + "org.apache.http.legacy.jar")
2. activity_login.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin" android:orientation="vertical" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="User Name" android:id="@+id/textView" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editTextUserName" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Password" android:id="@+id/textView2" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:ems="10" android:id="@+id/editTextPassword" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Login" android:onClick="invokeLogin" android:id="@+id/button" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Register" android:id="@+id/register" android:layout_gravity="center_horizontal" /> </LinearLayout>
3.Login.class
package com.example.mihir.myphpexample; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; 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.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 java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class Login extends ActionBarActivity { private EditText editTextUserName; private EditText editTextPassword; Button Register; public static final String USER_NAME = "USERNAME"; String username; String password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loing); editTextUserName = (EditText) findViewById(R.id.editTextUserName); editTextPassword = (EditText) findViewById(R.id.editTextPassword); Register =(Button)findViewById(R.id.register); Register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Login.this, Registration.class); startActivity(intent); } }); } public void invokeLogin(View view){ username = editTextUserName.getText().toString(); password = editTextPassword.getText().toString(); login(username,password); } private void login(final String username, String password) { class LoginAsync extends AsyncTask<String, Void, String>{ private Dialog loadingDialog; @Override protected void onPreExecute() { super.onPreExecute(); loadingDialog = ProgressDialog.show(Login.this, "Please wait", "Loading..."); } @Override protected String doInBackground(String... params) { String uname = params[0]; String pass = params[1]; InputStream is = null; List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("username", uname)); nameValuePairs.add(new BasicNameValuePair("password", pass)); String result = null; try{ HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://compliments.esy.es/loginm.php"); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String result){ String s = result.trim(); loadingDialog.dismiss(); if(s.equalsIgnoreCase("success")){ Intent intent = new Intent(Login.this, UserProfile.class); intent.putExtra(USER_NAME, username); finish(); startActivity(intent); }else { Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show(); } } } LoginAsync la = new LoginAsync(); la.execute(username, password); } }
4.activity_registration.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin" android:orientation="vertical" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/string_enter_name" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/editTextName" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/string_choose_username" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/editTextUserName" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/string_choose_password" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:id="@+id/editTextPassword" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/string_enter_email" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:id="@+id/editTextEmail" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/button_register" android:id="@+id/buttonRegister" /> </LinearLayout>
5.Registration.class
package com.example.mihir.myphpexample; import android.app.ProgressDialog; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class Registration extends AppCompatActivity implements View.OnClickListener{ private EditText editTextName; private EditText editTextUsername; private EditText editTextPassword; private EditText editTextEmail; private Button buttonRegister; private static final String REGISTER_URL = "http://compliments.esy.es/register.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); editTextName = (EditText) findViewById(R.id.editTextName); editTextUsername = (EditText) findViewById(R.id.editTextUserName); editTextPassword = (EditText) findViewById(R.id.editTextPassword); editTextEmail = (EditText) findViewById(R.id.editTextEmail); buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(this); } @Override public void onClick(View v) { if(v == buttonRegister){ registerUser(); } } private void registerUser() { String name = editTextName.getText().toString().trim().toLowerCase(); String username = editTextUsername.getText().toString().trim().toLowerCase(); String password = editTextPassword.getText().toString().trim().toLowerCase(); String email = editTextEmail.getText().toString().trim().toLowerCase(); register(name,username,password,email); } private void register(String name, String username, String password, String email) { String urlSuffix = "?name="+name+"&username="+username+"&password="+password+"&email="+email; class RegisterUser extends AsyncTask<String, Void, String>{ ProgressDialog loading; @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(Registration.this, "Please Wait",null, true, true); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(String... params) { String s = params[0]; BufferedReader bufferedReader = null; try { URL url = new URL(REGISTER_URL+s); HttpURLConnection con = (HttpURLConnection) url.openConnection(); bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream())); String result; result = bufferedReader.readLine(); return result; }catch(Exception e){ return null; } } } RegisterUser ru = new RegisterUser(); ru.execute(urlSuffix); } }
6.MySQLtble
Now you have to create data base table name “users”.
7. register.php
Create register.php for registration.
<?php
$name
= $_GET['name'];
$username
= $_GET['username'];
$password
= $_GET['password'];
$email
= $_GET['email'];
if($name
== '' || $username == '' || $password == '' || $email == ''){
echo
'please fill all values';
}else{
require_once('db_connect.php');
$sql
= "SELECT * FROM users WHERE username='$username' OR email='$email'";
$check
= mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo
'username or email already exist';
}else{
$sql
= "INSERT INTO users (name,username,password,email)
VALUES('$name','$username','$password','$email')";
if(mysqli_query($con,$sql)){
echo
'successfully registered';
}else{
echo
'oops! Please try again!';
}
}
mysqli_close($con);
}
?>
8.loginm.php
Create loginm.php for login.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username
= $_POST['username'];
$password
= $_POST['password'];
require_once('db_connect.php');
$sql
= "select * from users where username='$username' and
password='$password'";
$check
= mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo
"success";
}else{
echo
"Invalid Username or Password";
}
}else{
echo
"error try again";
}
?>
9.db_connect.php
For Connection for php file we required db_connect
file in which host, user, password and
databse name are used.
<?php
define('HOST','mysql.hostinger.in');
define('USER','u532517283_user');
define('PASS','**********
');
define('DB','u532517283_bdm');
$con =
mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>
So finally we are done with user login and
registration in android using php MySQL.
THANK YOU..
No comments:
Post a Comment