IMG_20160502_023938

This tutorial will explain how you can design an android mobile app from the scratch that communicates with the internet. In this tutorial for example, an android app is designed that does two things which are namely:

  1. Login a username and password of a user
  2. Create new account for a user.

The below reveals the various subheadings that is explained in this tutorial.


The Best and sustainable alternative to MMM is here; GetHelpWorldwide. Click here for details
  1. Tools used to achieve this design and their functions
  2. Creating mysql database and table for the purpose of this tutorial
  3. The php files/scripts and its expected outputs.
  4. The android app design (the various codes and it functions)
  5. Screenshots of how to test the application
  6. Various links and downloadables.
  7. Final note.

1.TOOLS USED TO ACHIEVE THIS DESIGN AND THEIR FUNCTIONS

  • Android Studio: This is the IDE (Integrated development environment) that is used in designing the android app. It is an environment to write android codes, design android template.
  • XAMMP SERVER: This is a local server that is used in designing the web aspect of this project. It houses Apache server, php installations, Mysql installations, Phpmyadmin. Phpmyadmin is a GUI(Graphical User Interface) that is used to create mysql database and tables.
  • php and mysql: php is the computer language used to interact with the apache web server. Also, we interact with our database via php scripts. Mysql is the query language that is used to talk to the database.

2. CREATING MYSQL DATABASE AND TABLE

Using the phpmyadmin @ http://localhost/phpmyadmin create a database, in this tutorial the name of the database is “user_details”. The next is to create table under this database. The name of the table is “user_table” and it contains 4 columns namely; “_id”, “username”, “password” and “status”. Using Mysql command, this is how to create a database; CREATE DATABASE user_details.

For the table, this is the command;

CREATE TABLE `user_details`.`user_table` ( `_id` INT NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(60) NOT NULL , `password` VARCHAR(60) NOT NULL , `status`
INT(1) NOT NULL , PRIMARY KEY (`_id`)) ENGINE = InnoDB;

If you are familiar with mysql and phpmyadmin, you will be able to interpret this codes above and simply use the phpmyadmin to achieve them.

3. THE PHP FILES/SCRIPTS USED AND ITS EXPECTED OUTPUT.

php is a language that communicates with the web server and deliver outputs. This is how the syntax of php looks like; <?php  echo ‘success’ ?>. This script simply output “success”. It is a language that is really easy to learn and very popular across the internet. Under the downloadables, you can download all the file and put them all in one folder under your local server webroot and make your necessary changes to make your own work in your way.

For this tutorials, create a php file named: keep.php, this file stores your database credentials.

keep.php


<?php
db_username = my_username
db_pword = my_password
db_name = user_details
?>

 

 

create another file name: quick_addKlass.php, this file contains a php class that is used to connect with the database (db), interact with the db, output various result, close database connection.

quick_addKlass.php


<?php

class quick_addKlass1
{
protected static $conn;

public function connect()
{
if(!isset(self::$conn))
{
$config = parse_ini_file('keep.php');
self::$conn = new mysqli('localhost', $config['db_username'], $config['db_pword'], $config['db_name']);
}

if(self::$conn === false)
{
//handle error here and other related matters.

return false;
}
return self::$conn;
}

public function closeConn(){
$conn = $this -> connect();
return $conn -> close();
}

//fetch the last error from the database.
/**
*
* @return  this method returns the last error obtained from any transaction
*/
public function errorMethod()
{
$connekt = $this -> connect();
return $connekt -> error;
}

public function check2login($username, $password)
{
$conn = $this->connect();
$stmt1 = "select username, password from user_table where (username = ? and password = ?) limit 1";

$prep1 = $conn->prepare($stmt1);//prepare the statement.
$prep1->bind_param('ss', $username, $password);//;//bind each variable to expected character to be received
$prep1->execute();//execute command.
$prep1->store_result();
if($prep1->num_rows == 1){
echo 'y';//login success
}

else
echo 'n';//failed login, not exist probably.
$prep1->close();
$this->closeConn();
}

public function createNew($username, $password)
{
$conn = $this->connect();
$stmt1 = "insert into user_table(username, password) values (?,?)";

$prepare = $conn->prepare($stmt1);//prepare the statement.
$prepare->bind_param('ss', $username, $password);//bind the variables.
if($prepare->execute()){
echo 'y';//inserted successfully
}
else{
echo 'n';//error occured, probably duplicate record.
}
$prepare->close();
$this->closeConn();
}

}
?>

 

The above code is a class that contains different function to achieve login or creating new account from the android app.

for login, if username and password coming from the app is valid with the one on the database, the function will

output: "y"

 

for login, if username or password is not valid, the function

output:"n"

 

for account creation, if username is new to the database, the function output

output:"y"

 

for account creation, if username exist on the database, the function output

output:"n"

 

create another file named “login.php“. This file is what the android app connects with, its like the primary file that connects every other php file in this tutorials.

login.php


<?php

if(isset($_POST['u_name']) && isset($_POST['p_word']) && isset($_POST['cmd']))
{
$username = $_POST['u_name'];
$password = $_POST['p_word'];
$which_one = $_POST['cmd'];

if(empty($username) || empty($password) || empty($which_one))
{
echo 'empty';
}
else
{
require 'quick_addKlass.php';
$quickObj = new quick_addKlass1();

if($which_one === "create")
{
$quickObj->createNew($username, $password);
}
else if($which_one === "login")
{
$quickObj->check2login($username, $password);
}
else{
echo 'nce';//No Category Error (nce)
}
}
}
else{
echo 'ns';//error occured, the post array Not Set.
}
?>

4. Android app design

To design the android app, we use Android Studio IDE. Eclipse IDE can also be used. Under the downloadables, you can download the android project folder and import into your android studio.

4.1 MainActivity.java

This java class is the main place the app starts its lifecycle. It controls the input from the user, it sends the input to the web server

MainActivity.java

<pre>package tech.naija.logintester;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
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 org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private EditText usernameET, passwordET;
    private Button loginButton, createNewButton;
    private NetworkTest testNework;
    public static final String urlCode = "http://naijatech.com.ng/test_login/";
    private String username, password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        usernameET = (EditText) findViewById(R.id.userId);
        passwordET = (EditText) findViewById(R.id.passwordId);
        loginButton = (Button) findViewById(R.id.loginButId);
        createNewButton = (Button) findViewById(R.id.createNewId);
        testNework = new NetworkTest(MainActivity.this);

        loginButton.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {

                username = usernameET.getText().toString();
                password = passwordET.getText().toString();

                if(username.trim().length() != 0 && password.trim().length() != 0)
                {
                    if(testNework.areYouKonnected())
                    {
                        new Thread2Login(username, password, "login").execute();
                    }
                    else{
                        Toast.makeText(MainActivity.this, "Check your network connections", Toast.LENGTH_SHORT).show();
                    }

                }
                else
                {
                    Toast.makeText(MainActivity.this, "Make sure you provide username and password", Toast.LENGTH_SHORT).show();
                }
            }
        });

        createNewButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(MainActivity.this, "You typed: " +password.getText().toString(), Toast.LENGTH_SHORT).show();
                username = usernameET.getText().toString();
                password = passwordET.getText().toString();

                if (username.trim().length() != 0 && password.trim().length() != 0) {
                    if (testNework.areYouKonnected()) {
                        new Thread2Login(username, password, "create").execute();
                    } else {
                        Toast.makeText(MainActivity.this, "Check your network connections", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "Make sure you provide username and password", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    public class Thread2Login extends AsyncTask<Void, String, String>
    {
        String username, password, collectReturn, cmd, catchExceptions;
        ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);

        public Thread2Login(String username, String password, String cmd)
        {
            this.username = username;
            this.password = password;
            this.cmd = cmd;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if(cmd == "create")
            {
                progressDialog.setMessage("Kindly wait, while your account is registered");
                progressDialog.setTitle("Registering New Account...");
            }
            if(cmd == "login")
            {
                progressDialog.setMessage("Kindly wait, while the server log you in");
                progressDialog.setTitle("Logging in...");
            }

            progressDialog.setCancelable(false);
            progressDialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {
            try{
                ArrayList<NameValuePair> pairedNames = new ArrayList<NameValuePair>();
                pairedNames.add(new BasicNameValuePair("u_name", username));//set the variable name(user_name) that will hold the data
                pairedNames.add(new BasicNameValuePair("p_word", password));//set the variable name(pass_word) that will hold the data
                pairedNames.add(new BasicNameValuePair("cmd", cmd));//set the variable name(pass_word) that will hold the data
                final String loginHttpLink = urlCode + "login.php";
                HttpPost post4http = new HttpPost(loginHttpLink);
                HttpClient client4http = new DefaultHttpClient();
                post4http.setEntity(new UrlEncodedFormEntity(pairedNames));
                HttpParams param4http = client4http.getParams();

                HttpConnectionParams.setConnectionTimeout(param4http, 5000);//sets timeout for the http connection.
                HttpConnectionParams.setSoTimeout(param4http, 5000);//sets timeout for the http conn.
                //the below shows the response of the request sent.
                HttpResponse responseHttp = client4http.execute(post4http);
                HttpEntity returnedEntity = responseHttp.getEntity();
                collectReturn = EntityUtils.toString(returnedEntity);
                Log.e("What was returned", collectReturn);//output that was returned good for debugging purpose.

                if(collectReturn.equals("ns")){//the post array not set.
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(MainActivity.this, "Error occured, try again", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                if(collectReturn.equals("nce")){//category not known, probably intrusion.
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(MainActivity.this, "Error occured, try again", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                if(collectReturn.equals("y")){//login success here.
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(cmd.equals("login")){
                                progressDialog.dismiss();
                                Intent newIntent = new Intent(MainActivity.this, NewArea.class);
                                newIntent.putExtra("username", username);
                                newIntent.putExtra("password", password);
                                newIntent.putExtra("cmd", "login");

                                finish();
                                startActivity(newIntent);
                                //Toast.makeText(MainActivity.this, "Login success", Toast.LENGTH_LONG).show();
                            }
                            if(cmd.equals("create")){
                                progressDialog.dismiss();
                                //Toast.makeText(MainActivity.this, "Account Created", Toast.LENGTH_LONG).show();
                                Intent newIntent = new Intent(MainActivity.this, NewArea.class);
                                newIntent.putExtra("username", username);
                                newIntent.putExtra("password", password);
                                newIntent.putExtra("cmd", "create");

                                finish();
                                startActivity(newIntent);
                            }

                        }
                    });
                }
                if(collectReturn.equals("n")){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(cmd.equals("login")){
                                progressDialog.dismiss();
                                Toast.makeText(MainActivity.this, "Username or Password not correct, try again.", Toast.LENGTH_SHORT).show();
                            }
                            if(cmd.equals("create")){
                                progressDialog.dismiss();
                                Toast.makeText(MainActivity.this, "Username already exist, try another username", Toast.LENGTH_SHORT).show();
                            }

                        }
                    });
                }

            }
            catch(UnsupportedEncodingException e){
                catchExceptions = e.toString();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "Error occured: " + catchExceptions, Toast.LENGTH_SHORT).show();
                    }
                });
            }
            catch(IOException e){
                catchExceptions = e.toString();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "Error occured: " + catchExceptions, Toast.LENGTH_SHORT).show();
                    }
                });
            }
            catch(Exception e)
            {
                catchExceptions = e.toString();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "Error occured: " + catchExceptions, Toast.LENGTH_SHORT).show();
                    }
                });
            }
            return null;
        }

        /*
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
        */
    }

}</pre>

4.2 NewArea.java
This is a java class that MainActivity.java sends username, password and action(create new
or login) if any of the user action is successful. NewArea.java reveals action that
happened, the username and password of the user. See the code below

NewArea.java

<pre>package tech.naija.logintester;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

public class NewArea extends AppCompatActivity
{

    private TextView usernameTV, passwordTV, welcomeHeadingTV;
    private ImageButton linkButton;
    private String username, password, cmd;

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

        usernameTV = (TextView) findViewById(R.id.textView);
        passwordTV = (TextView) findViewById(R.id.textView2);
        welcomeHeadingTV = (TextView) findViewById(R.id.textView3);
        linkButton = (ImageButton) findViewById(R.id.imageView);

        Intent returnIntent = this.getIntent();
        username = returnIntent.getStringExtra("username");
        password = returnIntent.getStringExtra("password");
        cmd = returnIntent.getStringExtra("cmd");

        if(cmd.equals("create")){
            welcomeHeadingTV.setText("Account Created Successfully");
            usernameTV.setText("Your Username is:  "+username);
            passwordTV.setText("Your Password is:  " +password);
        }
        if(cmd.equals("login")){
            welcomeHeadingTV.setText("Account Login Successfully");
            usernameTV.setText("Your Username is:  "+username);
            passwordTV.setText("Your Password is:  " +password);
        }

        linkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent linkIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://naijatech.com.ng"));
                startActivity(linkIntent);
            }
        });

    }

    @Override
    public void onBackPressed(){
        super.onBackPressed();
        startActivity(new Intent(NewArea.this, MainActivity.class));
        finish();
    }

    @Override
    protected void onPause(){
        super.onPause();

    }

    @Override
    protected void onStop(){
        super.onStop();

    }

}</pre>

4.3 activity_main.xml
This xml file shows the default template revealed to the user at the beginning of the
application.

<pre><?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:background="@color/bgcolor"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#7DF1F1"
        android:id="@+id/linearLayout">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20sp"
            android:paddingBottom="10sp"
            android:paddingTop="10sp"
            android:textSize="25sp"
            android:id="@+id/heading1"
            android:textColor="#000"
            android:text="@string/app_name"    />

    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/linearLayout"    >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"   >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Input your username"
        android:layout_marginRight="10sp"
        android:layout_marginLeft="10sp"
        android:inputType="text"
        android:textColor="#000"
        android:layout_marginTop="50dp"
        android:textColorHint="#000"
        android:id="@+id/userId"
        android:layout_centerHorizontal="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:hint="Input your password"
        android:layout_marginRight="10sp"
        android:layout_marginLeft="10sp"
        android:inputType="textPassword"
        android:textColor="#000"
        android:textColorHint="#000"
        android:id="@+id/passwordId"
        android:layout_below="@+id/userId"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10sp"
        android:text="Login"
        android:id="@+id/loginButId"
        android:layout_below="@+id/passwordId"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10sp"
        android:text="Create New Account"
        android:id="@+id/createNewId"
        android:layout_below="@+id/loginButId"
        android:layout_centerHorizontal="true" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/createNewId"
                android:layout_marginTop="30sp"
                android:src="@drawable/nt"
                android:layout_centerHorizontal="true" />

        </RelativeLayout>
    </ScrollView>

</RelativeLayout></pre>

This is the picture of the above activity_main.xml code

IMG_20160502_023900
4.4 new_area.xml

This xml layout reveals only on success of the activity_main.xml. See the code below

<pre><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="@color/bgcolor"
    android:paddingBottom="@dimen/activity_vertical_margin"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#7DF1F1"
        android:id="@+id/linearLayout">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20sp"
            android:paddingBottom="10sp"
            android:paddingTop="10sp"
            android:textSize="25sp"
            android:id="@+id/heading1"
            android:textColor="#000"
            android:text="@string/app_name"    />

    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/linearLayout"    >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView"
        android:layout_marginTop="42dp"
        android:layout_below="@+id/textView3"
        android:layout_alignLeft="@+id/textView3"
        android:layout_alignStart="@+id/textView3"
        android:textColor="#000"
        android:textSize="15dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView2"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="57dp"
        android:textColor="#000"
        android:textSize="15dp" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:src="@drawable/nt"
        android:background="#51f4a2"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView3"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignStart="@+id/textView2"
        android:layout_marginTop="10dp"
        android:textStyle="bold"
        android:textColor="#000"
        android:textSize="15dp" />

        </RelativeLayout>
    </ScrollView>

</RelativeLayout></pre>

See the picture of the above code below:

IMG_20160502_023601

5. SCREENSHOTS OF THE APP AND ITS BEHAVIOURS

5.1 The below picture shows when a user inputs a username and password.

 IMG_20160502_023938

5.2 The below picture shows when  a user inputs an invalid username or password, and the app says, it doesnot exist.

IMG_20160502_023812

6. VARIOUS LINKS AND DOWNLOADABLES

  • To download the android app that is already connected to an online server and working fine, see the link
  • To build your own version or modify the android project and the php files on your computer, download the folders here, see the link

7. FINAL NOTE

This tutorials is a guide that reveals how android application can talk to an online server. To grab this tutorial better, some background of android app learning is needed. Also, knowledge of php scripting language is needed.

If you are have any comments, or any other inputs, you can use the comment section or

email NaijaTech @[email protected], [email protected]

Enjoy!!!!!

 

 

 

 

 

 

 

 

Share This: