Android PHP MySQL - HTTP GET - Fill ListView

android networking

This is an Android PHP MySQL HTTP GET Tutorial with HttpURLConnection and ListView.

Android PHP MySQL Retrieve- HTTP GET tutorial here. In this tutorial we are covering how to retrieve data from MySql database via PHP using HttpUrlConnection.Then we show the data in a simple ListView.

What is a Database?

A database, generally speaking, refers to any organized collection of data

There are several types of databases:

  1. Flat file databases ― these store data sequentially, often in plain text files.

  2. Hierarchical databases ― these organize data in parent/child relationships.

  3. Key-value/document-oriented databases ― these store free-form data indexed by a key or hash value.

  4. Relational databases ― these organize data in rows and tables. This is the most popular and is what we use in most of our examples.

What is MySQL ?

MySQL is an open source, multithreaded, relational database management system created by Michael "Monty" Widenius in 1995.

Many businesses these days develop and maintain custom software with MySQL. Additionally, majority of the most popular websites(e.g Wikipedia) and software use MySQL for their database.

One of the most prominent features of MySQL is its speed and scalability. Together with MariaDB, MySQL's identical twin brother/sister, tends of thousands of rows and billions of rows of data can efficiently be handled.

However, you can also use MySQL for small amounts of data, like we will do to store our PDF documents in this android pdf viewer app we will create.

Why do Alot of People Choose MySQL?

There are many RDBMS(Relational Database Management System) databases. However MySQL is the most popular.

This is because of the following factors:

  1. Speed. MySQL is fast. Its developers claim that MySQL is about the fastest database system you can get.You can investigate this claim by visiting here, a performance-comparison page on the MySQL Web site.

  2. Ease of use. Even though MySQL is highly performant, it's relative a simple database system. Setting it up and Administering it is much less complex than other large systems.

  3. Query language support. MySQL also provides support for SQL(Structured Query Language). SQL is the standard language of choice for almost all modern database systems.

  4. Capability. The MySQL server is multi-threaded. This implies that many clients can connect to it at the same time. Each client can use multiple databases simultaneously.

  5. Connectivity and security. MySQL is fully networked, and databases can be accessed from anywhere on the Internet. Hence you can share your data with anyone, anywhere. But MySQL has access control so that one person who shouldn’t see another’s data cannot.To provide additional security, MySQL supports encrypted connections using the Secure Sockets Layer (SSL) protocol.

  6. Availability and cost. MySQL is an Open Source project available under multiple licensing terms. First, it is available under the terms of the GNU General Public License (GPL).This means that MySQL is available without cost for most in-house uses. Second, for organizations that prefer or require formal arrangements or that do not want to be bound by the conditions of the GPL, commercial licenses are available.

What is MySQLi?

MySQLi is a PHP extension which allows us to access the functionality provided by MySQL 4.1 and above.

As an extension, mysqli exposes APIs to the PHP programmer, to allow us work with MySQL database programmatically.

Normally there are three ways(APIs) of working with MySQL from database:

  1. PHP MySQLi extension.
  2. PHP MySQL extension.
  3. PHP Data Objects(PDO).

In this class we will use the most commonly used API which is mysqli.

Advantages of MySQLi

MySQLi is the most popular API for working with MySQL database because of the following reasons:

  1. Provision of both Object Oriented and Procedural Interfaces.
  2. Embedded Server support.
  3. Support for Prepared Statements.
  4. Ability to use Multiple Statements.
  5. Transactions support.

etc

You can find more information about mysqli here.

Introduction to PHP?

PHP is a popular general-purpose scripting language that is especially suited to web development.

Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.

PHP Hello World
<?php
echo "Hello world";

PHP's website is here.

Classes

Class definitions start with the keyword class, followed by a class identifier, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.

A class may contain its own constants, variables (called "properties"), and functions (called "methods").

Here's a simple class definition in PHP:

<?php
class HelloClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
?>

You can then create an instance:

<?php
$h = new HelloClass();

// This can also be done with a variable:
$className = 'HelloClass';
$h = new $className(); // new HelloClass()
?>

We will be working with PHP in an Object Oriented manner.

Introduction to HttpURLConnection

HttpUrlconnection is a UrlConnection for HTTP used to send as well receive data over the web. These data may be of any type and length.

HttpURLConnection was added in android 1.0 and is a URLConnection with support for HTTP-specific features. Like its parent URLConnection, it resides in the java.net package. This class allows us do networking easily and is the standard networking library in android.

HttpUrlConnection can also be used to send and receive streams whose length isn’t known in advance.

To be used,we obtain a new HttpUrlconnection object by calling url.openConnection() and casting to HttpUrlConnection.

If we open a connction to a url with "https" scheme,this returns HttpsUrlConnection.

Here is a simple usage of HttpURLConnection to download a webpage:

   URL url = new URL("http://www.google.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }

For example, to retrieve the webpage at http://www.android.com/:

   URL url = new URL("http://www.android.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }
Posting Content

To post some content to a web server, first you have to configure the connection for output using setDoOutput(true).

For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.

 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     urlConnection.setDoOutput(true);
     urlConnection.setChunkedStreamingMode(0);

     OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
     writeStream(out);

     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }
HTTP Authentication

HttpURLConnection supports HTTP basic authentication. You can use Authenticator to set the VM-wide authentication handler:

  Authenticator.setDefault(new Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
       return new PasswordAuthentication(username, password.toCharArray());
     }
   });
Sessions with Cookies

To establish and maintain a potentially long-lived session between client and server, HttpURLConnection includes an extensible cookie manager. Enable VM-wide cookie management using CookieHandler and CookieManager:

  CookieManager cookieManager = new CookieManager();
   CookieHandler.setDefault(cookieManager);

What is ListView?

A ListView is an android widget that allows us to render a list of scrollable items.

ListView is an adapterview like gridview and spinner.

This means that it requires an adapter for it to insert its items. The adapter becomes responsible for pulling data from a content source.

This source can be an array or something more complex like database or from the network.

Not only that but the adapter will also be responsible for converting each item result into a view that will be placed into the listview.

This is because as an adapterview the ListView does not know the details, such as type and contents, of the views it contains.

So it will ask for the views on demand from a ListAdapter as needed. For instance it asks for these views as the user scrolls up or down.

Each of the views in the ListView is positioned immediately below the previous view in the list.

ListView API Definition

Here's ListView's API definition.

java.lang.Object
   ↳    android.view.View
       ↳    android.view.ViewGroup
           ↳    android.widget.AdapterView<android.widget.ListAdapter>
               ↳    android.widget.AbsListView
                   ↳    android.widget.ListView

Clearly you can see ListView is residing in the android.widget package and deriving from the abstract AbsListView class.

Video Tutorial(ProgrammingWizards TV Channel)

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel.

Basically we have a TV for programming where do daily tutorials especially android.

Full Code

This android php mysql listview tutorial.We are using HttpURLConnection to make a HTTP GET request.

1. PHP Code

Here's our php code:

<?php

$host='127.0.0.1';
$username='root';
$pwd='';
$db="spacecraftDB";

$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');

if(mysqli_connect_error($con))
{
    echo "Failed to Connect to Database ".mysqli_connect_error();
}

$sql="SELECT * FROM spacecraftTB";

$result=mysqli_query($con,$sql);
if($result)
{
    while($row=mysqli_fetch_array($result))
    {
        $data[]=$row;
    }

    print(json_encode($data));
}

mysqli_close($con);

?>

2. Java Code.

Android apps can be mainly written in Java or Kotlin. These days however there are many frameworks like Flutter also which use languages like Dart.

In this class we are using Java programming language.

We will have these classes in our project.

(a). Our Connector Class
  • Has a static connect method that takes a URL Address string and returns a HttpURLConnection object.
  • Simply establishes connection to our server.
  • We set connection properties like Request method which is "GET",as we are making a HTTP GET request.
package com.tutorials.hp.mysqlhttpgetlistview.m_MySQL;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * ROLE : ESTABLISH CONNECTION TO SERVER
 */
public class Connector {

    public static Object connect(String urlAddress)
    {
        try
        {
            URL url=new URL(urlAddress);
            HttpURLConnection con= (HttpURLConnection) url.openConnection();

            //SET CON PROPERTIES
            con.setRequestMethod("GET");
            con.setConnectTimeout(15000);
            con.setReadTimeout(15000);
            con.setDoInput(true);

            return con;

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "Error "+e.getMessage();

        } catch (IOException e) {
            e.printStackTrace();
            return "Error "+e.getMessage();

        }
    }

}
(b). Our Downloader Class
  • Basically,we download data here.
  • We do this in AsyncTask.
  • Through a BufferedInputStream.
  • Then read using a BufferedReader.
  • We then call DataParser class to parse our data.
package com.tutorials.hp.mysqlhttpgetlistview.m_MySQL;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

public class Downloader extends AsyncTask<Void,Void,String>{
    Context c;
    String urlAddess;
    ListView lv;

    ProgressDialog pd;

    public Downloader(Context c, String urlAddess, ListView lv) {
        this.c = c;
        this.urlAddess = urlAddess;
        this.lv = lv;
    }

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

        pd=new ProgressDialog(c);
        pd.setTitle("Retrieve");
        pd.setMessage("Retrieving..Please wait");
        pd.show();
    }

    @Override
    protected String doInBackground(Void... params) {
        return this.downloadData();
    }

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

        pd.dismiss();
        if(jsonData.startsWith("Error"))
        {
            Toast.makeText(c,"Unsuccessful "+jsonData,Toast.LENGTH_SHORT).show();
        }else
        {
            //PARSE
            new DataParser(c,jsonData,lv).execute();
        }

    }

    private String downloadData()
    {
        Object connection=Connector.connect(urlAddess);
        if(connection.toString().startsWith("Error"))
        {
            return connection.toString();
        }

        try {
            HttpURLConnection con= (HttpURLConnection) connection;

            InputStream is=new BufferedInputStream(con.getInputStream());
            BufferedReader br=new BufferedReader(new InputStreamReader(is));

            String line;
            StringBuffer jsonData=new StringBuffer();

            while ((line=br.readLine()) != null)
            {
                jsonData.append(line+"n");

            }

            br.close();
            is.close();

            return jsonData.toString();

        } catch (IOException e) {
            e.printStackTrace();
            return "Error "+e.getMessage();
        }

    }
}

(c). Our DataParser Class

  • Yes,its DataParser class.
  • To parse our data.
  • We use the native org.JSON classes to parse.Using JSONArray and JSONObect.
  • We then fill a simple ArrayList with data we have parsed.
  • Then pass the arraylist to our ArrayAdapter.
  • And bind the adapter to the ListView.
  • Then simple ItemClickListener.
package com.tutorials.hp.mysqlhttpgetlistview.m_MySQL;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class DataParser extends AsyncTask<Void,Void,Boolean> {

    Context c;
    String jsonData;
    ListView lv;

    ProgressDialog pd;
    ArrayList<String> spacecrafts=new ArrayList<>();

    public DataParser(Context c, String jsonData, ListView lv) {
        this.c = c;
        this.jsonData = jsonData;
        this.lv = lv;
    }

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

        pd=new ProgressDialog(c);
        pd.setTitle("Parse");
        pd.setMessage("Pasring..Please wait");
        pd.show();
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        return this.parseData();
    }

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

        pd.dismiss();
        if(result)
        {
            ArrayAdapter adapter=new ArrayAdapter(c,android.R.layout.simple_list_item_1,spacecrafts);
            lv.setAdapter(adapter);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(c, spacecrafts.get(position), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private Boolean parseData()
    {
        try
        {
            JSONArray ja = new JSONArray(jsonData);
            JSONObject jo;

            spacecrafts.clear();

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

                jo = ja.getJSONObject(i);

                String name = jo.getString("name");

                spacecrafts.add(name);
            }

            return true;

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }
}

(d). Our MainActivity

  • Launcher activity.
  • Initialize UI like ListView.
  • Executes the sender AsyncTask on button click,passing on ListView,Context and URL.
package com.tutorials.hp.mysqlhttpgetlistview;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import com.tutorials.hp.mysqlhttpgetlistview.m_MySQL.Downloader;

public class MainActivity extends AppCompatActivity {

    final static String urlAddress="http://10.0.2.2/android/spacecraft_select_images.php";

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

        final ListView lv= (ListView) findViewById(R.id.lv);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Downloader(MainActivity.this,urlAddress,lv).execute();
            }
        });
    }

}

3. Our Layouts

(a) activity_main.xml

Our main activity layout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="com.tutorials.hp.mysqlhttpgetlistview.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
(b) ContentMain.xml
  • With a simple ListView which will render our data.
<?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="com.tutorials.hp.mysqlhttpgetlistview.MainActivity"
    tools:showIn="@layout/activity_main">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         />
</RelativeLayout>

Section 7 : AndroidManifest.xml

  • Remember to add permission for internet in your manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorials.hp.mysqlhttpgetlistview">

    <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=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Download

Hey,everything is in source code reference that is well commented and easy to understand and can be downloaded below.

Also check our video tutorial it's more detailed and explained in step by step.

No. Location Link
1. GitHub Direct Download
2. GitHub Browse
3. YouTube Video Tutorial

About Me

My name is Oclemy, after recently finishing my Software Engineering undergraduate program, am now dedicating alot of time to my two babies: Camposha.info and my YouTube Channel ProgrammingWizards TV apart from my daily work.

Am committed to making them world class resources in the next few years. Help me by subscribing to my YouTube Channel ProgrammingWizards TV and sharing my articles.

Best Regards,

Oclemy.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think

Dear readers drop us your comments below. We are building a community of students and learners. Start by dropping us your suggestions below. What tutorials do you want us to do for example? Where can we improve? What are some awesome resources out there? Do you have any code you want to share with us?
By the way that example or snippet you have lying in your computer can really help beginner programmers. We can share it here with other students.

Previous Post Next Post