android register, android rest api example, android register using PHP and MySQL, android register with online authentication

How to create a register application in android using Rest API

In the previous articles, we have shown you how to create a simple registration app in android and also how to login in android using Rest API. For easier understanding, it’s good that we show you how to register or create an account in android using Rest API whereby we will save the entered data to an online server

Now that we have covered how to create designs in the previous articles, we will go straight to the functionality of the app. You can follow the previous articles here

The register xml file code is as follows

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

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="@color/teal_200"

    tools:context=".RegisterActivty">

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:orientation="vertical"

        android:layout_marginLeft="40dp"

        android:layout_marginRight="40dp"

        android:layout_marginTop="15dp">

        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Enter Details to Create Account"

            android:textColor="#000"

            android:textSize="25dp"

            android:id="@+id/textdisplay"

            app:layout_constraintBottom_toBottomOf="parent"

            app:layout_constraintLeft_toLeftOf="parent"

            app:layout_constraintRight_toRightOf="parent"

            app:layout_constraintTop_toTopOf="parent" />

 

        <TextView

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginTop="30dp"

            android:textSize="20dp"

            android:textColor="#000"

            android:id="@+id/firstnametextview"

            android:text="Enter First Name">

        </TextView>

        <EditText

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginTop="15dp"

            android:hint="Enter first name here"

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

        </EditText>

 

        <TextView

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginTop="30dp"

            android:textSize="20dp"

            android:textColor="#000"

            android:id="@+id/lastnametextview"

            android:text="Enter Last Name">

        </TextView>

        <EditText

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginTop="15dp"

            android:hint="Enter last name here"

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

        </EditText>

        <TextView

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginTop="30dp"

            android:textSize="20dp"

            android:textColor="#000"

            android:id="@+id/emailtextview"

            android:text="Enter Email Address">

        </TextView>

 

        <EditText

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginTop="15dp"

            android:hint="Enter email here"

            android:inputType="textEmailAddress"

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

        </EditText>

        <TextView

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginTop="30dp"

            android:textSize="20dp"

            android:textColor="#000"

            android:id="@+id/usernametextview"

            android:text="Enter Username">

        </TextView>

        <EditText

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginTop="15dp"

            android:hint="Enter username here"

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

        </EditText>

        <TextView

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginTop="30dp"

            android:textSize="20dp"

            android:textColor="#000"

            android:id="@+id/passwordtextview"

            android:text="Enter Password">

        </TextView>

        <EditText

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginTop="15dp"

            android:inputType="textPassword"

            android:hint="Enter password here"

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

        </EditText>

        <Button

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_marginTop="10dp"

            android:id="@+id/registerbutton"

            android:text="Create Account">

        </Button>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

In the manifest file add the internet permission as follows

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

The full manifest file will be like this

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.firstandroidapp">

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/Theme.FirstAndroidApp">

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

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

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

            </intent-filter>

        </activity>

    </application>

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

</manifest>

The Register Rest API done using PHP and MySQL is as shown below

<?php

header("Content-Type:application/json");

$con=mysqli_connect("localhost","database_username","database_password","database_name") or die("error");

$firstname = $_POST["firstname"];

$lastname = $_POST["lastname"];

$email = $_POST["email"];

$username = $_POST["username"];

$password = $_POST["password"];

if(mysqli_query($con,"INSERT INTO customers(FirstName,LastName,Email,Username,Password) VALUES('$firstname','$lastname','$email','$username','$password'")){

$json = array("status" => 200,'message' => "Success");

}else{

$json = array("status" => 300,'message' => "Error");

}

echo json_encode($json);

mysqli_close($con)

?>

The code in the java file that collects the details from the XML file and converts them to string and then sends them to the online server using the Rest API is as follows

package com.example.firstandroidapp;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;

import android.app.ProgressDialog;

import android.content.Context;

import android.content.Intent;

import android.os.AsyncTask;

import android.os.Bundle;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

 

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

 

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 RegisterActivty extends AppCompatActivity {

    EditText firstnametext,lastnametext,emailtext,usernametext,passwordtext;

    Button register;

    String firstname,lastname,email,username,password;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register_activty);

        firstnametext=(EditText)findViewById(R.id.firstname);

        lastnametext=(EditText)findViewById(R.id.lastname);

        emailtext=(EditText)findViewById(R.id.email);

        usernametext=(EditText)findViewById(R.id.username);

        passwordtext=(EditText)findViewById(R.id.password);

        register=(Button) findViewById(R.id.registerbutton);

 

        firstname= firstnametext.getText().toString();

        lastname= lastnametext.getText().toString();

        email= emailtext.getText().toString();

        password= passwordtext.getText().toString();

        username= usernametext.getText().toString();

        register.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                if(firstname.equals("") || lastname.equals("") || email.equals("") || username.equals("") || password.equals("")){

                    Toast.makeText(getApplicationContext(), "All fields are required", Toast.LENGTH_SHORT).show();

                }else{

                    Register rg = new Register(RegisterActivty.this);

                    rg.execute();

                }

            }

        });

    }

 

    class Register extends AsyncTask<String, Void, String> {

        AlertDialog alertDialog;

        Context context;

        int msg;

 

        ProgressDialog progressDialog;

        Register(Context ctx) {

            this.context = ctx;

        }

 

        @Override

        protected void onPreExecute() {

            progressDialog = ProgressDialog.show(context, "", "submitting details...... Please wait");

 

        }

 

        @Override

        protected String doInBackground(String... params) {

 

            String login_url ="https://www.solutionspacenet.com/apis/register";

            try {

                URL url = new URL(login_url);

                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setConnectTimeout(10000);

                httpURLConnection.setRequestMethod("POST");

                httpURLConnection.setDoOutput(true);

                httpURLConnection.setDoInput(true);

                OutputStream OS = httpURLConnection.getOutputStream();

                BufferedWriter bufferedWriter = new BufferedWriter(

                        new OutputStreamWriter(OS, "UTF-8"));

                String data = URLEncoder.encode("firstname", "UTF-8") + "=" + URLEncoder.encode(firstname, "UTF-8") + "&"

                        + URLEncoder.encode("lastname", "UTF-8") + "=" + URLEncoder.encode(lastname, "UTF-8") + "&"

                        + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&"

                        + URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&"

                        + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

                bufferedWriter.write(data);

                bufferedWriter.flush();

                bufferedWriter.close();

                OS.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 += line;

                }

                bufferedReader.close();

                inputStream.close();

                httpURLConnection.disconnect();

 

                try {

                    JSONArray jsonarray = new JSONArray(response);

                    for (int i = 0; i < jsonarray.length(); i++) {

                        JSONObject jsonobject = jsonarray.getJSONObject(i);

                        msg = jsonobject.getInt("status");

                    }

                } catch (JSONException e) {

                    e.printStackTrace();

                    return response;

                }

                return "good";

            } catch (MalformedURLException e) {

                e.printStackTrace();

                return "fail";

            } catch (IOException ee) {

                ee.printStackTrace();

                return "fail";

            }

 

        }

 

        @Override

        protected void onProgressUpdate(Void... values) {

            super.onProgressUpdate(values);

        }

 

        @Override

        protected void onPostExecute(String result) {

            progressDialog.dismiss();

            if (result.equals("fail")) {

                progressDialog.dismiss();

            } else if (msg == 200) {

                usernametext.setText("");

                passwordtext.setText("");

                progressDialog.dismiss();

                Toast.makeText(context, "Registration successful", Toast.LENGTH_SHORT).show();

            } else if (msg == 0) {

                progressDialog.dismiss();

                Toast.makeText(context, "Registration Failed", Toast.LENGTH_LONG).show();

            }

 

        }

 

    }

}

 

Follow the steps keenly and you will achieve how to create a register application using Rest API