Android MySQL → Android PHP MySQL ListView Tutorial and Examples. – Camposha

Android MySQL

Android MySQL

Android MySQL

Android PHP MySQL ListView Tutorial and Examples.

Android PHP MySQL ListView Examples and Tutorials.

We want to learn how to work with MySQL database and ListView in android using HttpUrlConnection once and for all. Hence we will explore several complete examples.

Let’s start.

1. Android MySQL – Select and Show in ListView(HTTPURLConnection).

Previously we had seen how to connect to mysql and isnert data into database from android. Well that was a HTTP POST request we were making.

We can also retrieve data and show them into a ListView.

MySQL ListView

While fetching data we will show a progress dialog.
Progress Dialog MySQL

HttpURLConnection

Still we use the standard Android Networking API that is java.net.HTTURLConnection. Read more about HttpUrlConnection here.

Our MySQL Database

Here’s our MySQL table structure:
MySQL Tabe Structure

We have the following fields:

  1. Id(AutoIncremented) – Integer.
  2. Name – String.
  3. Position – String.

Read more about mysql here.

Project Structure

Here’s the project structure:
Project Structure

Let’s go.

1. Gradle Scripts

In our app level build.gradle we add some dependencies.

(a). Build.gradle

We add android.support:appcompat-v7 and android.support:design.

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.2.1'
        compile 'com.android.support:design:23.2.1'
    }

2. Our PHP Script

Here’s the PHP script that will connect to the MySQL database.

    <?php

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

    $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();
    }

    $query=mysqli_query($con,"SELECT * FROM playerstb");
    if($query)
    {
        while($row=mysqli_fetch_array($query))
        {
            $flag[]=$row;
        }

        print(json_encode($flag));
    }
    mysqli_close($con);
    ?>

3. AndroidManifest.xml

Add the permission for internet in the androidmanifest.xml.

    <uses-permission android_name="android.permission.INTERNET"

4. Layouts

Let’s create some layouts.

(a). activity_main.xml

Our MainActivity’s primary layout. Will get inflated into MainActivity user interface.
At the root we have android.support.design.widget.CoordinatorLayout.

This layout has the following responsibilities: No. Responsibility
1. Define the AppbarLayout using android.support.design.widget.AppBarLayout tag.
2. Define the ToolBar using the android.support.v7.widget.Toolbar tag.
3. Define the FloatingActionButton using the android.support.design.widget.FloatingActionButton tag.
4. Include the content_main.xml which will render our other views and widgets.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout 
        
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_fitsSystemWindows="true"
        tools_context="com.tutorials.hp.mysqlselector.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). content_main.xml

Our content_main.xml layout. The root tag is RelativeLayout.

It has the following responsibilities:

No. Responsibility
1. Define/Hold the ListView that will display our data from MySQL database.
2. It will be included inside the activity_main.xml to form the MainActivity layout.
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        
        
        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.mysqlselector.MainActivity"
        tools_showIn="@layout/activity_main">

        <TextView
            android_padding="5dp"
            android_id="@+id/textView"
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_text="Players List!" />
        <ListView
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_id="@+id/lv"
            android_layout_below="@+id/textView"
            android_layout_alignParentLeft="true"
            android_layout_alignParentStart="true" />
    </RelativeLayout>

5. Java Classes

We have three custom java classes.

(a). Downloader.java

Our Downloader.java class, a public class that will derive from android.os.AsyncTask. This provides us with easy to use threading capabilities.

The purposes of this class includes:

No. Responsibility
1. Receive an android.content.Context object, a URL address and a ListView widget from the MainActivity.
2. Instantiate,show and dismiss progress dialog.
3. Establish connection to the provided URL via the java.net.HTTPURLConnection.
4. Download data and return it as a string in the background thread.
5. Catch IOException and MalformedURLException.
6. Instantiate Parser object, pass Context, downloaded string and listview.And execute it.
(b). Parser.java

This is our custom Parser class. The class still extends android.os.AsyncTask.

This class will parse our JSON string and fill our listview.

It has the following roles:

No. Responsibility
1. Receive Context object,ListView and the downloaded data from Downloaded class.
2. Define an arraylist to hold the downloaded data.
3. Instantiate, show and dismiss the progress dialog.
4. Parse the json string and populate our ArrayList. We do this in the background thread inside the doInbackground() method.
5. Bind our arraylist to our ListView.
(c). MainActivity.java

Our public class that will be the launcher activity. It will derive from android.support.v7.app.AppCompatActivity.

This class the following responsibilities:

No. Responsibility
1. Allow itself to become an android activity component by

deriving from android.support.v7.app.AppCompatActivity.|
|2.|Listen to activity creation callbacks by overrding the onCreate() method.|
|3.|Invoke the onCreate() method of the parent Activity

class and tell it of a Bundle we’ve received. |
|4.|Inflate the activity_main.xml into a View object and set

it as the content view of this activity.|
|5.| Define our URL address. This URL address leads to ou PHP script|
|6.| Reference the android.support.v7.widget.Toolbar and set it to the SupportActionBar.|
|7.| Reference ListView from layout.|
|8.| Instantiate Downloader class. Pass in the URL addtess, ListView and Context.|
|9.| Execute the download operation.|

Download

You can download the code here.


2. Android MySQL – Select Multiple Columns and Fill Custom ListView

[center]Android MySQL – Select Multiple Columns and Fill Custom ListView Tutorial[/center]

How to select multiple columns from mysql database and populate a custom listview with multiple textviews.

Overview

Welcome. In this class we are going to look at MySQL database. How to connect to MySQL, retrieve multiple columns and rows from a given database table and bind them to a custom ListView.

That ListView will have several fields, each representing a given record column from our mysql database table.

These fields will include:

  • ID.
  • Name.
  • Propellant.
  • Description.

Our application will have the following classes:

No. Class Description
1. Spacecraft.java Will represent our data object. We will be selecting spacecrafts from our mysql database.
2. CustomAdapter.java This is the adapter needed to adapt our data to our custom listview. It will also inflate the custom layout which will make up the ListView view items.
3. Connector.java This is the class responsibe for setting up our connection and returning a HttpURLConnection object.
4. DataParser.java This is the class responsible for parsing our JSON data and returning an ArrayList containing our data.
5. Downloader.java This is the class responsible for actually downloading our json data in a background thread via AsyncTask. The networking class used for this download is our HttpURLConnection.
6. MainActivity.java This is our main activity. It represents the overall user interface or screen.

Tools Used

These are the tools we used to create the project:

  1. Language : Java.
  2. Platform : Android.
  3. IDE : Android Studio.
  4. OS : Windows 8.1

Let’s go.

1. PHP Code

Here’s our PHP Code to select multiple columns data from our mysql database and return it in json format.
Am using Wamp: C:wampwwwandroidspacecraft_select.php.

2. Setup

(a). Create Basic Activity Project
  1. First create a new project in android studio. Go to File –> New Project.
(b). Project Structure

Here’s our project structure:

Project Structure

(c). Build.Gradle

Our app level(app folder) build.gradle.

AndroidStudio allows us to add our application dependencies right here using compile statements.

So we add our dependencies here. You may use later versions of the dependencies.

(d). AndroidManifest.xml

We add internet permission here.

3. Create User Interface

User interfaces are typically created in android using XML layouts as opposed to direct java coding.

Here are our layouts for this project:

(a). activity_main.xml
  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.
(b). content_main.xml

This layout gets included in your activity_main.xml.
We define our UI widgets here.

(c). model.xml

This is our custom row layout. Our model layout.

4. Java Code

(a). Spacecraft.java

Android is normally written in Java programming language. Java classes are normally organized in packages. This class will have the com.tutorials.hp.mdmysqlselect.mDataObject package.

This class is a public class and represents a single spacecraft for us.

The class will have the following instance fields:

  1. Id – spacecraft id.
  2. Name – spacecraft name.
  3. Propellant – spacecraft propellant.
  4. description – spacecraft description.

We create the getters and setters of these instance fields.

(b). CustomAdapter.java

This class will be deriving from android.widget.BaseAdapter. This class is public class.

This class will maintain a couple of instance fields:

  1. Context object – Will assist in inflation of our model layout.
  2. ArrayList of generic type Spacecraft class.
  3. LayoutInflater object to inflate our model.xml layout.

The constructor of this class will take in a Context object and an ArrayList of spacecrafts objects.

Then inside the Constructor we assign those objects to their respective class instance fields that we had defined.

We then initialiaze our LayoutInflater class: inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE) assigning to LayoutInflater class.

LayoutInflater instance will later allow us inflate our XML layout into view object.

After deriving from baseadapter, we will be forced to implement a couple of abstract methods.
These include :

  1. getCount() – return the number of spacecrafts to bind to our ListView.
  2. getItem()– get a single spacecraft object.
  3. getView() – inflate the model.xml layout and return it as a view object.
(c). Connector.java

Next we come to our Connector.java class.

This class is a public class with one static method.

This method is our connect(..) method. This method will take a string object we are calling urlAddress to represent the URL string to our server side PHP script that will allow us fetch data from mysql database.

This method will return us a java.net.HttpURLConnection.

We’ll have a try-catch block, catching two exceptions :

  1. java.net.MalformedURLException – Raised when a malformed URL is encountered.
  2. java.io.IOException – Raised when an IO(Input Output) error has occured.

First we attempt to instantiate a java.net.URL passing in our URL address. URL stands for Uniform Resouce Locator and points to a Resource in a the World Wide Web. In this case that resource will be our php script.

url.openConnection() will return us a URLConnection object which represents the connection to the remote object referred to by the URL.

We cast that URLConnection to HttpURLConnection. HttpURLConnection is a url connection which supports HTTP specific features. It works with the HTTP protocol.

con.setRequestMethod() will set the HTTP Request method that we support. These can be :

  1. GET.
  2. POST.
  3. PUT.
  4. DELETE.
  5. HEAD.
  6. OPTIONS.

We use GET since we are fetching data.

con.setReadTimeout() will specify the timeout for reading our resouce while con.setConnectTimeout() indicates the timeout for our connection.

con.setDoInput() indicates that our connection supports input of data.

(d). DataParser.java

This is our Data Parser class.

(e). Downloader.java
(f). MainActivity.java

 

Leave a Reply

Your email address will not be published. Required fields are marked *

X