Thursday, January 7, 2016

Android MySQL Database Tutorial 2 - Android Login with PHP MySQL







package com.example.programmingknowledge.mysqldemo;

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.EditText;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {
    EditText UsernameEt, PasswordEt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        UsernameEt = (EditText)findViewById(R.id.etUserName);
        PasswordEt = (EditText)findViewById(R.id.etPassword);
    }

public void OnLogin(View view) {
    String username = UsernameEt.getText().toString();
    String password = PasswordEt.getText().toString();
    String type = "login";
    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, username, password);
}

}




package com.example.programmingknowledge.mysqldemo;

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

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;

/**
 * Created by ProgrammingKnowledge on 1/5/2016.
 */
public class BackgroundWorker extends AsyncTask<String,Void,String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx) {
        context = ctx;
    }
    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "http://192.168.1.6/login.php";
        if(type.equals("login")) {
            try {
                String user_name = params[1];
                String password = params[2];
                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 post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
                        +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result="";
                String line="";
                while((line = bufferedReader.readLine())!= null) {
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

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

    @Override
    protected void onPostExecute(String result) {
        alertDialog.setMessage(result);
        alertDialog.show();
    }

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




<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:id="@+id/myrl">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/etUserName"
        android:layout_alignParentTop="true"
        android:layout_marginTop="47dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/etPassword"
        android:layout_below="@+id/etUserName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/btnLogin"
        android:layout_below="@+id/etPassword"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="48dp"
        android:layout_marginStart="48dp"
        android:layout_marginTop="50dp"
        android:onClick="OnLogin"/>
</RelativeLayout>




<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.programmingknowledge.mysqldemo" >
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>"
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>




<?php 
$db_name = "employee101";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$conn = mysqli_connect($server_name, $mysql_username, $mysql_password,$db_name);

?>




<?php 
require "conn.php";
$user_name = $_POST["user_name"];
$user_pass = $_POST["password"];
$mysql_qry = "select * from employee_data where username like '$user_name' and password like '$user_pass';";
$result = mysqli_query($conn ,$mysql_qry);
if(mysqli_num_rows($result) > 0) {
echo "login success !!!!! Welcome user";
}
else {
echo "login not success";
}

?>




























Searches related to android mysql login

android mysql server

android mysql client

android mysql app

android mysql php json

android php mysql json login

How to create Simple Login form using php in android

Android Login and Registration with Php and Mysql

PHP Android Tutorial Part

Android Login and Registration with PHP, MySQL

android php mysql sample code

android php mysql json tutorial

android studio mysql connection

29 comments:

  1. I used the code but every time I click register button on Main Activity..the app keeps crashing. Can someone please help? Thanks~

    ReplyDelete
  2. I use hosting to upload the phps files. On the browsers running on pc the login.php work fine. but when I run the app on the phone. show this message : ... this site require JavaScript to work, please enable JavaScript in your browser... I don't know what that mean. and don't show the echo message. please help!. thanks.

    ReplyDelete
  3. Hello Sir,
    A very helpful tutorial by you. I need a small help from you. I need to go to another activity when user has logged in successfully. I tried myself but I was unable to do the same. Could you please help me out.
    Thanks

    ReplyDelete
    Replies
    1. Did anyone get a solution to this? I have the same issue. Any hints or tips would be greatly appreciated. Thanks.

      Delete
    2. Use Intent instead Toast or some other things

      Intent intent=new Intent(MainActivity.this,Main2Activity.class);
      startActivity(intent);

      Make a new activity before doing this code.

      Delete
    3. @Override
      protected void onPostExecute(String result) {
      alertDialog.setMessage(result);
      alertDialog.show();
      Intent intent=new Intent(context,MainActivity2Activity.class);
      context.startActivity(intent);

      }
      //write the above code in the postExcecute method of BackgroundWorker class.

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Please zoom into the code dynamically for your next videos.

    ReplyDelete
  6. I tried ur code with appcompatactivity. it doesn't work. please help me.

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Hi!
    As soon as I use special characters the Login is not successful. I have already changed the collation for 'username' and 'password' from "latin1_swedish_ci" to "utf8_general_ci" - without success. How can this be fixed?

    ReplyDelete
  9. mysqli_num_rows() expects parameter 1 to be mysqli_result boolean given
    need help

    ReplyDelete
    Replies
    1. you may try mysqli_num_rows($result)==1 for if statement in login.php

      Delete
  10. where i should put (Intent intent=new Intent(MainActivity.this,Main2Activity.class);
    startActivity(intent);) to change the activity after a correct authentification please help.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. "Error while waiting for device: Could not start AVD"
    What the problem??

    ReplyDelete
  13. thanks in advance .but i have another option in the login i send 4 var not 3 like that

    public class BackgroundWorker extends AsyncTask{ }

    it is give me an error because par 4 not 3 :( please help

    ReplyDelete

  14. I wonder how do I open another screen if the login success and send a msg if not sucess login.
    Someone help me

    ReplyDelete
  15. firstly, thx for the tutorial + code..
    the code work fine for me , but i need to conf my wamp access..
    refer : http://stackoverflow.com/questions/8586720/error-403-wamp-server

    ReplyDelete
  16. Getting the following error. Can someone assist please?

    java.io.IOException: unexpected end of stream on Connection{192.168.0.101:8889, proxy=DIRECT@ hostAddress=192.168.0.101 cipherSuite=none protocol=http/1.1} (recycle count=0)

    ReplyDelete
  17. Hello Sir, thanks for the useful tutorial but I have a problem..... When i click the LOgin Button the AlertDialog is empty!! there is only the title that i set in onPreExecute()... Any ideas about my problem?

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  18. I have been facing similar problem. Challenge was that I had put my login.php in a folder within the www folder. Android was catching the IOException error.
    Solution;
    Make sure that your login_url path is correct otherwise the file won't be found.

    ReplyDelete
  19. why i add in the new intent:

    @Override
    protected void onPostExecute(String result) {
    alertDialog.setMessage(result);
    alertDialog.show();
    Intent intent=new Intent(context,MainActivity2Activity.class);
    context.startActivity(intent);

    the android give me the response is stopped, but not to the new page ????

    ReplyDelete