Android Login App with Backend


Before we begin, lets understand what RESTful API is?

REST stands for REpresentational State Transfer.
  1. Rest is resource based.
    1. Things vs Actions.
    2. Nouns vs Verbs.
    3. Identified by URIs: Multiple URI may refer to same resource.
    4. Separate from their representation.
  2. Representations  : Its about how resources get manipulated.  This representation gets transferred between client and server. Typically, the representations are JSON or XML object. For example : Resource : Person (Ajay) , Service : Contact Info (We can use HTTP verb, GET for that purpose), and its representation would be in JSON or XML object with name, address and phone number. 
  3. It has Uniform Interface : 
    1. It defines the Interface between client and server.
    2. Simplifies and decouples the architecture. 
    3. It is fundamental to RESTful design.
    4. For us this could be simplifies as;
      1. HTTP verbs (GET, PUT, POST , DELETE)
      2. URIs (Resource Name)
      3. HTTP response (status, body)
  4. REST is stateless Meaning
    1. Server contains no client state.
    2. Each request contains contains enough context to process the message.
    3. Any session state is held on the client (There could be stateful Rest, based on OAuth 2 ). 
  5. It is a Client Server architecture
    1. Assume it as disconnected system. It keeps separation between your data and client. You should design such UI , considering both ways considering having connected system and when its not. 
    2. Uniform interface is the link between the two
  6. REST must be Cacheable implicitly, explicitly or it could be negotiated based on client.  
  7. Layered System : Client can't assume direct connection to server. It improves scalability.
  8. Code on Demand : It means, it sends logic to client to execute. Server gives appropriate logic to client based on request. 
This theory will give you around 40 to 50% of idea how REST can be useful, but you will realize its power and usefulness when you understand it with real time example, and in this tutorial, i will exactly walk you through steps. 

PART 1 : BUILDING BACK-END with PHP AND MYSQL


Prerequisite : You should have basic knowledge about WAMP/XAMP apache web server, and how it works. Also, you should be able to use Android studio and some of basic things in Android such as using AyncTask  in android. So, lets begin.

In this tutorial, i will create a basic android app using which you can login from your php backend server.

You should have your XAMP/WAMP server ready. If you haven't, you can download it from here
http://www.wampserver.com/en/  - wamp server
https://www.apachefriends.org/download.html -- xamp server
Choose them based on your OS, and install them. Personally I would recommend you using Bitnami Apache server, which comes with many supported frameworks and every easy to work with.
You can download it here - https://bitnami.com/stack/wamp.

Now, to create a login functionality, we first need to build a backend database schema, which would enable us to store the password and username for the user. So here's the table query, its nothing special, just creating a table called users , to store the information.

CREATE TABLE IF NOT EXISTS users 
( id int(20) NOT NULL AUTO_INCREMENT,
username varchar(70) NOT NULL, password varchar(40) NOT NULL,
email varchar(50) NOT NULL,
created_at datetime NOT NULL,
updated_at datetime DEFAULT NULL,
PRIMARY KEY (id), UNIQUE KEY email (email)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1
You can run this query on phpmyAdmin. If you have server running, go to your localhost/phpmyadmin  log in and execute query. it will just create a table to store our data.
after running the above query, you should have table and database similar to this.



Now that we have database schema, we are ready to build our server API, which would allow us to fill the data, and get the data from server.

On your apache server, create a folder named android_login_api (you can use your name as per your wish). Create a following structure in your htdocs directory of Apache server. (look at the path)


Create a following directory structure
          server/htdocs/android_login_api
                                           |
                                           |----->include(folder)
                                           |                |
                                           |                | ----- config.php, db.php , user.php  (Three files in include folder)
                                           |
                                           |----> index.php

What this files do?
config.php - saving your database information for connection purpose.
db.php -  to establish the connection using config.php credentials.
user.php - api which would determine login success/failed, register a new user. Add new values to dabatabse.

Now open the config.php  and add following code : This is just a database connection details. Please replace it with your passwords and database name.
<?php

define("DB_HOST", "localhost");
define("DB_USER", "yourDbUserName");
define("DB_PASSWORD", "yourDatabasePassword");
define("DB_NAME", "yourDatabaseName");
?>
now open the db.php using which we will establish connection with our php to database. add the following code (Read my comments, since i cannot explain each line in tutorial. In comments, i have tried to explain very nicely.)

<?php

//including config.php file to get the database credentials we saved earliar
include_once 'config.php';

class DbConnect{

private $connect;
public function __construct(){

//connecting using the parameters passed in config.php
$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

//if error post it on server
if (mysqli_connect_errno($this->connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}

//if no errors, get the connection. getDB function returns an instance of our database connection.
public function getDb(){

return $this->connect;
}

}
Now that we have our database connection, create user.php inside include folder. This file will contain the login and user registration code. Add following code in user.php (read comments to understand ).

<?php

//Including db.php for login purpose
include_once 'db.php';

class User{

//creating a variable to hold an instance of database.
private $db;
//table name we are using to add data of username and password
private $db_table = "users";


public function __construct(){
$this->db = new DbConnect();
}

//Api function for login
public function isLoginExist($username, $password){

//if username and password passed matches with uesrs record then find 1,
$query = "select * from " . $this->db_table . " where username = '$username' AND password = '$password' Limit 1";

//result is saved
$result = mysqli_query($this->db->getDb(), $query);

//if you found more than 0 , then yes It exists with return true
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
mysqli_close($this->db->getDb());
return false;
}

//registeration
public function createNewRegisterUser($username, $password, $email){

//query inserting email, username and password to users table
$query = "insert into users (username, password, email, created_at, updated_at) values ('$username', '$password', '$email', NOW(), NOW())";
//getDb -- instance of database, with the query above passed in .
$inserted = mysqli_query($this->db->getDb(), $query);

//1 = success , JSON , so in Android we can get this value in JSON 1, then this means, registration successfully done..
if($inserted == 1){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
//closing the connection
mysqli_close($this->db->getDb());

//returning Json object with success = 1 or 0 (true/false);
return $json;
}

//Login purpose
public function loginUsers($username, $password){

$json = array();
//if isLoginExist returns true, then
//$canUserLogin = true
// so, if that's true, then success = 1 , so user can login.
$canUserLogin = $this->isLoginExist($username, $password);
if($canUserLogin){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
return $json;
}

}
?>
All the request will hit this file, for getting results. In this example, we are distinguishing registration and login using just one extra parameter which is email . if user passes email, password and username then its registration else login. This file will return the JSON object with success value.

Now, inside android_login_api folder, create a file called index.php and add following code.

<?php

require_once 'include/user.php';

$username = "";
$password = "";
$email = "";

if(isset($_POST['username'])){
$username = $_POST['username'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}

// Instance of a User class
$userObject = new User();
echo "apprajapati server is running...";
// Registration of new user
if(!empty($username) && !empty($password) && !empty($email)){
$hashed_password = md5($password);
$json_registration = $userObject->createNewRegisterUser($username, $hashed_password, $email);
echo json_encode($json_registration);
}

// User Login
if(!empty($username) && !empty($password) && empty($email)){
//passwords are always stored in hash.. using md5 built in functionality of php to do that..
$hashed_password = md5($password);
$json_array = $userObject->loginUsers($username, $hashed_password);
echo json_encode($json_array);
}
?>
In above file, we are just getting json_edcode data with value of 'success' = 1 or 0 . It will return formatted data {"success":1} or {"success":0}.

This is all we need to do server side. This enables us to login (if username, password exists in database) , or register (if we pass username, password, and email) .

Now, This was RESTapi , now we can move to towards building our app.

PART 2 : BUILDING ANDROID APPLICATION 

Prerequisite : You should be pretty familiar with basic Android stuff. Also, AyncTask. Also, you should be using Android Studio, since its the official IDE of Android. I also believe if you want to learn, nothing can stop you and you will learn. so lets get started...

Create a project from android studio, with simple Blank Activity
Go to File - New - New Project - Give app name - Target API level and choose blank activity,



This will create a basic structure of your app.
It will have
MainActivity.java with some basic things which app needs to run.
and resource folder with activity_main and content_main.xml . This both file are used for only one screen, which is MainActivity. Here i am assuming you are pretty familiar with the basic structure of app, and how views are called and initialized.

after you create an project, the first thing we should do is to add permission for Internet in AndroidManifest.xml  file. Its because, we are going to use Internet connection to make call to server, and this is crucial step. Without this, you will get server error, because your app won't be able to connect to your server. so lets add this.

<uses-permission android:name="android.permission.INTERNET"/>
So, first step is to create a Login Screen  which will somewhat look as below (you can customize it the way you want) :
 This is screen of MainActivity. The whole structure is defined in activity_main.xml and other views which we see such as image, edittext and buttons are specified in content.xml file.



As i said earlier, i would not go deep in explaining views in android. You should be familiar with it, also its pretty simple and straightforward.

How the flow will work? 
simple, when user enters username and password , i will send those strings to our server. If the entry exists, then server will give us {success:1} and if not, then {success:0}. From 0 and 1 value of success, we will determine it, and allow or decline the user to login. Pretty simple right??

so now, lets create our screen shown beside..
(there might be case where you have only one screen for MainActivity , you should add code accordingly) if you create project from Android studio, it will have it as i said.

content_main.xml file represents this screen. So, open it in android studio, and add the following code.
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="www.apprajapati.AndroidLogin.MainActivity"
tools:showIn="@layout/activity_main">

<!--image on top of screen -->

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="50dp"
android:src="@drawable/blogsymbol"/>


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/username"
android:id="@+id/username"
android:textSize="16sp"
android:layout_marginTop="180dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:id="@+id/username_login"
android:layout_below="@+id/username"
android:layout_alignLeft="@+id/username"
android:layout_alignStart="@+id/username" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/password"
android:id="@+id/password"
android:textSize="16sp"
android:layout_below="@+id/username_login"
android:layout_alignLeft="@+id/username_login"
android:layout_alignStart="@+id/username_login"
/>

<!--em is font size -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/password_login"
android:layout_marginRight="20dp"
android:layout_marginBottom="10dp"
android:layout_below="@+id/password"
android:layout_alignLeft="@+id/password"
android:layout_alignStart="@+id/password" />

<Button
android:layout_width="@dimen/login_register_width"
android:layout_height="@dimen/login_register_height"
android:text="@string/login"
android:id="@+id/login_button"
android:layout_below="@+id/password_login"
android:layout_marginLeft="12dp"
android:layout_marginRight="20dp"
android:background="#20000000"
/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Don't have account Yet? Click below to Register"
android:id="@+id/alternative"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="12dp"
android:layout_below="@id/login_button"
android:layout_marginRight="20dp"
android:textSize="16sp" />


<Button
android:layout_width="@dimen/login_register_width"
android:layout_height="@dimen/login_register_height"
android:text="@string/register_button"
android:layout_marginLeft="12dp"
android:layout_marginRight="20dp"
android:id="@+id/register_button"
android:background="#20000000"
android:layout_below="@+id/alternative"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />

</RelativeLayout>
above code will create a above shown image. Which means, we are done on the UI side for login. Now, lets write some code to make it work, its pretty simple actually..

First of all, make an  java interface in your app, naming it Constant_ServerUrl.  This is for getting our android app connected to our php server. It would look as follows :

10.0.2.2 IP address is nothing, but your localhost. Since, we are building this on localhost , you must run this app to test on Emulator. Emulator understands this 10.0.2.2 ip address and it will connect to your localhost/android_login_api. This way, we are able to make connection between our SERVER AND APP.  for more information on that please visit : https://developer.android.com/studio/run/emulator-commandline.html.

In main activity add following code (read my comments for understanding the code
MainActivity.java
 
public class MainActivity extends AppCompatActivity implements Constant_ServerUrl {

//Views for Login
private EditText userName;
private EditText mPassword;

private String enteredUserName; //to store the UserName

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

//Initialize the views of EditText
userName = (EditText) findViewById(R.id.username_login);
mPassword = (EditText) findViewById(R.id.password_login);

//initializing buttons
Button loginButton = (Button) findViewById(R.id.login_button);
Button registerButton = (Button) findViewById(R.id.register_button);

//Validation
assert loginButton != null;
loginButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

//getting both values entered in Username and password
enteredUserName = userName.getText().toString();
String enteredPassword = mPassword.getText().toString();

if(enteredUserName.equals("") || enteredPassword.equals("")){
Toast.makeText(MainActivity.this, "Username or Password Must not be Empty.",Toast.LENGTH_LONG).show();
return;
}
if(enteredUserName.length()<=1||enteredPassword.length()<=1){
Toast.makeText(MainActivity.this, "Username or Password Must be greater than four character.",Toast.LENGTH_LONG).show();
return;
}
//if everything works out... check out the details entered by user using Server
AsyncTaskLogin loginTask = new AsyncTaskLogin();
loginTask.execute(baseUrl,enteredUserName, enteredPassword); //PASSING THREE necessary values to check

}
});
assert registerButton != null;
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(intent);
}
});

}

// Params, the type of the parameters sent to the task upon execution.
// Progress, the type of the progress units published during the background computation.
// Result, the type of the result of the background computation.
//In our case, this three parameters are , String =Params , Void =Progress , Result= String
private class AsyncTaskLogin extends AsyncTask<String, Void, Integer> {


//This is the main method in AsyncTask, you must implement this, because this is where
// it creates a new thread to work in background. You cannot do UI task on this thread.
@Override
protected Integer doInBackground(String... params) {

//HttpParams =
HttpParams httpParams = new BasicHttpParams();
//BasicHttpParams = Default implementation of HttpParams interface.
//This class represents a collection of HTTP protocol parameters.
// Protocol parameters may be linked together to form a hierarchy.
// If a particular parameter value has not been explicitly defined in the collection itself,
// its value will be drawn from the parent collection of parameters.

// HttpConnectionParams An adaptor for accessing connection parameters in HttpParams.
HttpConnectionParams.setConnectionTimeout(httpParams,5000);
HttpConnectionParams.setSoTimeout(httpParams,5000);

HttpClient httpClient = new DefaultHttpClient(httpParams);
//Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP
// requests while handling cookies, authentication, connection management, and other features.
// Thread safety of HTTP clients depends on the implementation and configuration of the specific client.

HttpPost httpPost = new HttpPost(params[0]); //Params[0] = baseUrl of our API
String jsonResult = "";
int answer = 0;
try{
List<NameValuePair> nameValuePairs = new ArrayList<>(2); //2 is capacity of ArrayList
nameValuePairs.add(new BasicNameValuePair("username",params[1]));
nameValuePairs.add(new BasicNameValuePair("password",params[2]));

httpPost.setEntity(new UrlEncodedFormEntity( nameValuePairs));

HttpResponse response = httpClient.execute(httpPost);
// jsonResult = inputStreamToString(response.getEntity().getContent()).
// toString(); //got response and converted into string and passed it to build string
jsonResult = EntityUtils.toString(response.getEntity());
Log.d("json_result_doinba:",jsonResult);
// jsonResult = EntityUtils.toString(response.getEntity());
JSONObject myObject = new JSONObject(jsonResult);
answer = Integer.parseInt(String.valueOf(myObject.getInt("success")));
Log.d("answer:", String.valueOf(answer));


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

return answer;
}


//After getting the result you might want to redirect to another screen or getting somewhere.
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);


if(result == 0){
Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
}

//If json result Value is 1, then it means RestApi sent "success" - SO LET THE USER LOGIN
//if success then let the user go in LoginActivity..
if(result == 1){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("USERNAME", enteredUserName);
intent.putExtra("MESSAGE", "You have successfully Logged In.");
startActivity(intent);
}
}

}

}
Above code will make your Login screen work. please read comments, since i cannot explain each line in code. I have commented every line , so you can understand. 

So, now lets move on to the next, when you enter the login details, and press login button, it will open an Activity with your name on it, displaying a message that you have successfully logged in.
To create that screen XML layout, add following code in your login_activity.xml 
(Remember, LoginActivity.java is tied to this xml view, so LoginActivity.java has its implementation and xml file contains UI)

login_activity.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".LoginActivity"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/welcomeText"
android:text="@string/welcome"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textColor="#000"
android:textSize="30sp"
android:textStyle="bold"
android:layout_marginTop="150dp"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/username"
android:id="@+id/login_user"

android:textSize="40sp"
android:textStyle="bold"
android:layout_below="@+id/welcomeText"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/message"
android:layout_marginTop="44dp"
android:layout_below="@+id/login_user"
android:layout_centerHorizontal="true" />

</RelativeLayout>
The above code will create screen as follows :


Simply, when you pressed login button, and executed the code in MainActivity.java  , you have validated the username and password added. It checked from sever whether this exists? , if yes, then it takes up the name of username and pass the message via the intent. 

If you will look code for MainActivity.java,  you will see, after validating, i am passing two things , a username and message with an intent to open this LoginActivity.java shown in the image beside.










Now that we have created a screen, lets add some code to get the data passed from MainActivity, to show data in LoginActivity.java.

public class LoginActivity extends AppCompatActivity {

private TextView userText;
private TextView messageView;

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

//initializing the value
userText = (TextView) findViewById(R.id.login_user) ;
messageView = (TextView) findViewById(R.id.message);

//getting an Intent
Intent intent = getIntent();
Bundle bundle = intent.getExtras();

//getting the value passed while logged in inside Intent
//Intent is passed from MainActivity in AsyncTask after validating the username and password from server

String loggedInUser = bundle.getString("USERNAME");
String message = bundle.getString("MESSAGE");
String upperCase = capitalizeFirstCharacter(loggedInUser);
userText.setText(upperCase);
messageView.setText(message);

}
private String capitalizeFirstCharacter(String textInput){
String input = textInput.toLowerCase();
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
return output;
}
}
Now, you can think how the LoginActivity is getting data? Android beginners might know but ill explain this, look at this part of code in MainActivity.java.

 if(result == 1){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("USERNAME", enteredUserName);
intent.putExtra("MESSAGE", "You have successfully Logged In.");
startActivity(intent);
}
This is the code, where it says, when you result you get of {success:1} from server, It means, username and password exits in database thus its valid, so let the user login.
Now via Intent i am opening LoginActivity and also passing two extra key pair value of "MESSAGE" and "USERNAME" , so this are the values being used by LoginActivity to display the username. I hope i explained clearly.

Now, lets create a RegisterActivity.java and its UI which would be inside register_activity.xml.

so first thing lets create a screen (UI ) of register activity. simply add the following code in register_activity.xml 
<?xml version="1.0" encoding="utf-8"?>
<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=".RegisterActivity">

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="50dp"
android:src="@drawable/blogsymbol"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/username"
android:id="@+id/username"
android:textSize="16sp"
android:layout_marginTop="150dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:id="@+id/edittext_username"
android:layout_below="@+id/username"
android:layout_alignLeft="@+id/username"

android:layout_alignStart="@+id/username" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/password"
android:id="@+id/password"
android:textSize="16sp"
android:layout_below="@+id/edittext_username"
android:layout_alignLeft="@+id/edittext_username"
android:layout_alignStart="@+id/edittext_username"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/edittext_password"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:layout_below="@+id/password"
android:layout_alignLeft="@+id/password"
android:layout_alignStart="@+id/password" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/email"
android:id="@+id/textView3"
android:textSize="16sp"
android:layout_below="@+id/edittext_password"
android:layout_alignLeft="@+id/edittext_password"
android:layout_alignStart="@+id/edittext_password"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/edittext_email"
android:layout_marginRight="20dp"


android:layout_below="@+id/textView3"
android:layout_alignLeft="@+id/textView3"
android:layout_alignStart="@+id/textView3" />
<Button
android:layout_width="@dimen/login_register_width"
android:layout_height="@dimen/login_register_height"
android:text="@string/sign_up"
android:id="@+id/sign_up"
android:layout_below="@+id/edittext_email"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp" />
</RelativeLayout>
Above code will create an UI as shown in following image

This screen will be created from above code. Now, we all know just screen doesn't work. We need to code for to make it alive and useful.

So here, when we enter the details, and press sign up, it will simply perform the insert query through our server API, and would let the user enter.
Later then, you can use same details to login from login screen.













RegisterActivity.java


public class RegisterActivity extends AppCompatActivity implements Constant_ServerUrl {

private EditText mUsername;
private EditText mPassword;
private EditText mEmail;
protected Button signup;
private String addedUsername;



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


mUsername = (EditText) findViewById(R.id.edittext_username);
mPassword = (EditText) findViewById(R.id.edittext_password);
mEmail = (EditText) findViewById(R.id.edittext_email);

signup = (Button) findViewById(R.id.sign_up);

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

addedUsername = mUsername.getText().toString();
String enteredPassword = mPassword.getText().toString();
String enteredEmail = mEmail.getText().toString();

if (addedUsername.equals("") || enteredPassword.equals("") || enteredEmail.equals("")) {
Toast.makeText(RegisterActivity.this, "Username or password or email must be filled", Toast.LENGTH_LONG).show();
return;
}
if (addedUsername.length() <= 1 || enteredPassword.length() <= 1) {
Toast.makeText(RegisterActivity.this, "Username or password length must be greater than one", Toast.LENGTH_LONG).show();
return;
}
// request authentication with remote server4

AsyncRegister registration = new AsyncRegister();
registration.execute(baseUrl, addedUsername, enteredPassword, enteredEmail);

}
});
}

private class AsyncRegister extends AsyncTask<String, Void, Integer>{


@Override
protected void onPreExecute() {
super.onPreExecute();
}

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

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);

HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
int answer = 0;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", params[1]));
nameValuePairs.add(new BasicNameValuePair("password", params[2]));
nameValuePairs.add(new BasicNameValuePair("email", params[3]));

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpClient.execute(httpPost);
// jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
jsonResult = EntityUtils.toString(response.getEntity());
JSONObject myObject = new JSONObject(jsonResult); //converting it into JSON
answer = Integer.parseInt(String.valueOf(myObject.getInt("success")));
System.out.println("Returned_registration_jsonresult:" + jsonResult.toString());
System.out.print("value_of_ans" + answer);

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return answer;
}

@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if(result.equals("") || result == null){
Toast.makeText(RegisterActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
// int jsonResult = returnParsedJsonObject(result);
if(result == 0){
Toast.makeText(RegisterActivity.this, "Invalid username or password or email", Toast.LENGTH_LONG).show();
return;
}
if(result == 1){
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
intent.putExtra("USERNAME", addedUsername);
intent.putExtra("MESSAGE", "You have successfully Registered! Welcome");
startActivity(intent);
}
}

}


}
Now, your app is complete. You can simply understand from my comments in the code. Its very simple and neat. Also, you could verify  your data from database. After you will register, you can check your database from localhost/phpmyadmin to check whether users table has the information you passed.

THINGS TO REMEMBER : I have only added code which is necessary, other parts of app, will be created automatically when you create project with blank activity as shown in first image in tutorial. Remember  to start your apache server and database before you test.

As you can see in the image, after you register with app, you will be able to see your data has been added to your database.

This is how server-client and RESTApi works. I hope i have made it simple and explained you well. Still, if you have any problems , or suggestion, please leave a comment. I would love to hear from you guys.

Happy Coding!!

References :
http://www.restapitutorial.com/lessons/whatisrest.html

Post a Comment

0 Comments