X

Android Login And Registration based on MYSQL Database using php Part 2.

 

Android Login Registration MySQL :

Android Login Registration MySQL  in this tutorial in Continuation with previous tutorial, we will see how to code an android app to connect with server and make register and login.

We make use of php files which we have created in our previous tutorial.

For First part of tutorial visit : Login And Registration based on MYSQL Database using php Part 1

Firstly we require a java class to make our connection

 

connect.java file

 

Providing the api’s for Android Login Registration MySQL.

public class Connect {


    public static final String URL_LOGIN = "http://10.0.3.2/work/login.php";

    public static final String URL_REGISTER = "http://10.0.3.2/work/register.php";

}

 

Creating register screen :

Now we need to design a register screen to enter user details like name, username, password and register button to register.

 

register.xml :

We are designing a register screen for Android Login Registration MySQL.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingLeft="40dp"
    android:paddingRight="40dp">

    <EditText
        android:id="@+id/register_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="name..." />

    <EditText
        android:id="@+id/register_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:hint="username..." />


    <EditText
        android:id="@+id/register_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:hint="password..."
        android:inputType="textPassword" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/register_btn1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Login" />

        <Button
            android:id="@+id/register_btn2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Register" />
    </LinearLayout>

</LinearLayout>

 

Adding register functionality i.e., user enter values will be saved to server and used when user try to login.

 

 

Register.java

We are configuring the register screen and making necessary calls for login and registration integration.

 

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
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 org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class Register extends ActionBarActivity {

    EditText nametxt,unametxt, pwordtxt;

    Button loginbtn, registerbtn;

    String name,username ,password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        nametxt = (EditText) findViewById(R.id.register_name);
        unametxt = (EditText) findViewById(R.id.register_username);
        pwordtxt = (EditText) findViewById(R.id.register_password);

        loginbtn = (Button) findViewById(R.id.register_btn1);
        registerbtn = (Button) findViewById(R.id.register_btn2);

        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(Register.this,Login.class);
                startActivity(i);


            }
        });

        registerbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                name = nametxt.getText().toString();
                username = unametxt.getText().toString();
                password = pwordtxt.getText().toString();

                Register();
            }
        });
    }


    private void Register(){
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {

            private Dialog loadingDialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loadingDialog = ProgressDialog.show
                          (Register.this, "Please wait", "Loading...");
            }

            @Override
            protected String doInBackground(String... params) {

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("name", name));
                nameValuePairs.add(new BasicNameValuePair("username", username));
                nameValuePairs.add(new BasicNameValuePair("password", password));


                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(Connect.URL_REGISTER);
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();



                } catch (IOException e) {

                }
                return "success";
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                loadingDialog.dismiss();

                AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                builder.setTitle("AndroidCoding.in");
                builder.setMessage("User Registered Successfully");
                builder.setCancelable(true);

                builder.setPositiveButton(
                        "Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                                finish();
                                Intent i = new Intent(Register.this,Login.class);
                                startActivity(i);
                            }
                        });

                AlertDialog alert3 = builder.create();
                alert3.show();

            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(name, username, password);
    }


}

 

Now we need to design first screen which will ask user to login or else can register. so need to create a activity for login.

Creating login screen

 

login.xml

 

  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingLeft="40dp"
    android:paddingRight="40dp">


    <EditText
        android:id="@+id/login_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="username..." />


    <EditText
        android:id="@+id/login_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:hint="password..."
        android:inputType="textPassword" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/login_btn1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Login" />

        <Button
            android:id="@+id/login_btn2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Register" />
    </LinearLayout>

</LinearLayout>

 

In login class we have to add register button as well as login functionality.login functionality includes async class which will make login.

Three steps are there in login async class

onPreExecute // before execution progress dialog is displayed

doInBackground // in background performs login

onPostExecute // will make changes based upon result from doInBackground 

 

Login.java

 

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.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.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.util.ArrayList;
import java.util.List;


public class Login extends ActionBarActivity {

    EditText unametxt, pwordtxt;

    Button loginbtn, registerbtn;

    public static final String USER_NAME = "USERNAME";

    String username, password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        unametxt = (EditText) findViewById(R.id.login_username);
        pwordtxt = (EditText) findViewById(R.id.login_password);

        loginbtn = (Button) findViewById(R.id.login_btn1);
        registerbtn = (Button) findViewById(R.id.login_btn2);

        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                username = unametxt.getText().toString();
                password = pwordtxt.getText().toString();

                UserLogin(username,password);

            }
        });

        registerbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               Intent i = new Intent(Login.this,Register.class);
                startActivity(i);
            }
        });
    }





    private void UserLogin(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(Connect.URL_LOGIN);
                    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 (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, Home.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);

    }



}

 

Creating HomeScreen file

Finally, after user login a home screen sometimes called as dashboard activity will appear, now we will design this screen.

 

home.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">



    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/title"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Logout"
        android:layout_marginTop="60dp"
        android:id="@+id/logoutbtn"/>

</LinearLayout>

 

In Home Screen we can add all the required functionality presently i am adding a logout functionality in HomeScreen.

 

Home.java :

This screen deals with facebook login page in your app.

 

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class Home extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        Intent intent = getIntent();
        String username = intent.getStringExtra(Login.USER_NAME);

        TextView title = (TextView) findViewById(R.id.title);

        Button logout = (Button) findViewById(R.id.logoutbtn);

        title.setText("Welcome "+username);

        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                Intent i = new Intent(Home.this,Login.class);
                startActivity(i);
            }
        });
    }


}

 

Android Manifest.xml File

Note: Adding Internet permission to manifest file is most important in this app make sure you have added it.

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

 Also add Register and Home Activity’s.

 

AndroidManifest.xml

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidcoding.LoginRegister">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Login">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity android:name=".Home" />

        <activity android:name=".Register" />

    </application>

</manifest>

Android Login Registration MySQL Output :

The screen below depicts the usage of Android Login Registration MySQL integration.

Login Screen

 

Registration Screen

Home Screen

 

For First part of tutorial visit : Login And Registration based on MYSQL Database using php Part 1

If you have any queries regarding this tutorial on Android Login Registration MySQL add a comment below.  If you like this tutorial do like and share us for more interesting updates.

 

abhishek:
Related Post

This website uses cookies.