This is an android mysql gridview with checkboxes tutorial. We see how to insert, select and show in a gridview.

  • Look the aim is to see how to work with Boolean values with MySQL database.
  • We want to insert data to MySQL database first.
  • We are inserting from an edittext,from a spinner as well as from a checkbox.
  • The user checks/unchecks the checkbox if the technology for our fictional spacecraft exists.
  • He selects the propellant from a spinner and enters the spacecraft name in a material checkbox.
  • We then select our data from database.It is strings and booleans.
  • The gridview is custom to hold textviews and checkboxes.
  • In actuality,MySQL doesn't natively support boolean data types.So we shall use a simple integer to represent boolean values to be bound to checkbox.
  • 1 to represent true and 0 to false.The integer is nullable.

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.

What is GridView?

A gridview is an adapterview that shows items in a two-dimensional grid.

Android GridView

These grids are scrollable. GridView is an adapterview because it works with adapters. Adapters can then bind data to the gridview.

This is important because then it means that the gridview is decoupled from it's data source. So you can customize the gridview as you like without interfering with the data source. You can also work on the data source without affecting the visual appearance of the gridview.

GridView derives from AbsListview.

public class GridView extends android.widget.AbsListView{}

Both reside in the android.widget packages.

AbsListview is an abstract class and you won't use in directly. You'll use it in case you want to implement your own custom view with unique properties.

Even the sister of GridView which is ListView also directly derives from AbsListview. So AbsListview is a base class. It's used to implement virtualized list of items. Given it's virtualized you can implement it to show lists in various forms:

  • Lists -vertical and horizontal
  • Grids
  • Carousel
  • Stack

And so on.

Fast Networking Library Introduction

Fast Android Networking Library is a Complete Android Networking Library that also supports HTTP/2 created by Amit Shekhar, a popular open source contributor.

It provides us with powerful networking capabilities yet in an elegant manner. It's a mature library and is currently one of the most popular networking library.

Fast Android Networking Library allows us perform any type of networking in Android applications.

It's a library built on top of OkHttp Networking Layer.

Fast Android Networking Library does alot of work for you in the background, such that you only make your request and listen for the response.

Top Reasons to start using Fast Android Networking Library

Here are some of the reasons why you need to consider using this library for networking needs in android.

  1. Android Framework Engineers in the recent years got rid of HttpClient, that is in Android Marshmallow(Android M). Because of this alot of networking libraries like Volley became obsolete.
  2. Fast Android Networking does allows you do these things easier than any other library:

    1. Making HTTP requests.
    2. Downloading any type of file.
    3. Uploading files.
    4. Loading image from network into ImageView, etc.
  3. Fast Networking Library provides a simple interface for doing all types of things in networking like setting priority, cancelling, etc.
  4. Fast Networking Library uses Okio hence no more GC overhead in android applications. Okio is made to handle GC overhead while allocating memory. Okio does some clever things to save CPU and memory.
  5. Fast Networking Library is built on top of the proven OkHttp.
  6. Fast Networking Libary supports HTTP/2.
Requirements

Fast Android Networking Library is generous with it's requirements.

To use it you need:

  1. Android 2.3 (Gingerbread) and later.
Fast Networking Libary Installation

To insall Fast Networking Library, head over to your app level and add it as a dependency:

implementation 'com.amitshekhar.android:android-networking:1.0.2'

Then in your android manifest don't forget to add permission:

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

Using it in Java

Well once you've installed it you can head over to your java code and initialize it first:

AndroidNetworking.initialize(getApplicationContext());
1. How to make a HTTP GET Request in Fast Networking Library

You invoke the AndroidNetworking.get() method:

AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                 .addPathParameter("pageNumber", "0")
                 .addQueryParameter("limit", "3")
                 .addHeaders("token", "1234")
                 .setTag("test")
                 .setPriority(Priority.LOW)
                 .build()
                 .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });  
2. How to make a HTTP POST Request in Fast Networking Library

You invoke the AndroidNetworking.post() method:

AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createAnUser")
                 .addBodyParameter("firstname", "Amit")
                 .addBodyParameter("lastname", "Shekhar")
                 .setTag("test")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });
3. How to Download a File in Fast Networking Library

You invoke the AndroidNetworking.download() method:

AndroidNetworking.download(url,dirPath,fileName)
                 .setTag("downloadTest")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .setDownloadProgressListener(new DownloadProgressListener() {
                    @Override
                    public void onProgress(long bytesDownloaded, long totalBytes) {
                      // do anything with progress  
                    }
                 })
                 .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                      // do anything after completion
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error    
                    }
                });  
4. How to Upload a File to Server in Fast Networking Library

You invoke the AndroidNetworking.upload() method:

AndroidNetworking.upload(url)
                 .addMultipartFile("image",file)    
                 .addMultipartParameter("key","value")
                 .setTag("uploadTest")
                 .setPriority(Priority.HIGH)
                 .build()
                 .setUploadProgressListener(new UploadProgressListener() {
                    @Override
                    public void onProgress(long bytesUploaded, long totalBytes) {
                      // do anything with progress 
                    }
                 })
                 .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // do anything with response                
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error 
                    }
                 }); 

fast_networking_library

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.

Android MySQL GridView CheckBoxes Insert, Select Show Example

Let's look at our example:

Android MySQL GridView

MySQL Table

Here's our mysql table structure:

Table Structure

Project Structure

Here's our project structure.

Project Structure

1. PHP Code

Here are our php code. Place them in the same folder.

(a) Constants.php
<?php

class Constants
{
    //DATABASE DETAILS
    static $DB_SERVER="localhost";
    static $DB_NAME="galileoDB";
    static $USERNAME="root";
    static $PASSWORD="";
    const TB_NAME="galileoTB";
    //STATEMENTS
    static $SQL_SELECT_ALL="SELECT * FROM galileoTB";
}
(b) CRUD.php
<?php

require_once("/DBAdapter.php");
if($_POST['action']=="save"){

         $dbAdapter=new DBAdapter();
         $name=$_POST['name'];
         $propellant=$_POST['propellant'];
         $technologyexists=$_POST['technologyexists'];
        $dbAdapter->insert(array($name,$propellant,$technologyexists));
}
else if($_POST['action']=="update")
{
         $dbAdapter=new DBAdapter();
         $id=$_POST['id'];
         $name=$_POST['name'];
         $propellant=$_POST['propellant'];
         $technologyexists=$_POST['technologyexists'];
        $dbAdapter->update($id,array($name,$propellant,$technologyexists));

}
else if($_POST['action']=="delete")
{
         $dbAdapter=new DBAdapter();
         $id=$_POST['id'];

        $dbAdapter->delete($id);
}
?>
(c) DBAdapter.php
<?php

require_once("/Constants.php");
class DBAdapter
{
/*******************************************************************************************************************************************/
/*
   1.CONNECT TO DATABASE.
   2. RETURN CONNECTION OBJECT
*/
    public function connect()
    {

       $con=mysqli_connect(Constants::$DB_SERVER,Constants::$USERNAME,Constants::$PASSWORD,Constants::$DB_NAME);
        if(mysqli_connect_error(!$con))
        {
           // echo "Unable To Connect";
            return null;
        }else
        {

            return $con;
        }
    }
    /*******************************************************************************************************************************************/
/*
   1.INSERT SPACECRAFT INTO DATABASE
 */
    public function insert($s)
    {
        // INSERT
        $con=$this->connect();

        if($con != null)
        {
            $sql="INSERT INTO galileoTB(name,propellant,technologyexists) VALUES('$s[0]','$s[1]','$s[2]')";
            try
            {
                $result=mysqli_query($con,$sql);
                if($result)
                {
                    print(json_encode(array("Success")));
                }else
                {
                    print(json_encode(array("Unsuccessfull")));
                }
            }catch (Exception $e)
            {
               print(json_encode(array("PHP EXCEPTION : CAN'T SAVE TO MYSQL. "+$e->getMessage())));
            }
        }else{
            print(json_encode(array("PHP EXCEPTION : CAN'T CONNECT TO MYSQL. NULL CONNECTION.")));
        }
        mysqli_close($con);
    }
/*******************************************************************************************************************************************/
/*
   1.SELECT FROM DATABASE.
*/
    public function select()
    {
       $con=$this->connect();
        if($con != null)
        {
            $retrieved=mysqli_query($con,Constants::$SQL_SELECT_ALL);
            if($retrieved)
            {
                while($row=mysqli_fetch_array($retrieved))
                {

                   // echo $row["name"] ,"    \t | ",$row["propellant"],"</br>";
                   $spacecrafts[]=$row;
                }
                print(json_encode($spacecrafts));
            }else
            {
                 print(json_encode(array("PHP EXCEPTION : CAN'T RETRIEVE FROM MYSQL. ")));
            }
        }else{
            print(json_encode(array("PHP EXCEPTION : CAN'T CONNECT TO MYSQL. NULL CONNECTION.")));
        }
        mysqli_close($con);
    }
/*******************************************************************************************************************************************/
/*
   1.UPDATE  DATABASE.

*/
    public function update($id, $s)
    {
        // UPDATE
        $con=$this->connect();

        if($con != null)
        {
            $sql="UPDATE galileoTB SET name='$s[0]',propellant='$s[1]',technologyexists='$s[2]' WHERE id='$id'";
            try
            {
                $result=mysqli_query($con,$sql);
                if($result)
                {
                    print(json_encode(array("Successfully Updated")));
                }else
                {
                    print(json_encode(array("Not Successfully Updated")));
                }
            }catch (Exception $e)
            {
                 print(json_encode(array("PHP EXCEPTION : CAN'T UPDATE INTO MYSQL. "+$e->getMessage())));
            }
        }else{
            print(json_encode(array("PHP EXCEPTION : CAN'T CONNECT TO MYSQL. NULL CONNECTION.")));
        }
        mysqli_close($con);
    }
/*******************************************************************************************************************************************/
/*
   1.DELETE SPACECRAFT FROM DATABASE.

*/
    public function delete($id)
    {
        $con=$this->connect();

        if($con != null)
        {
//            $name=$_POST['Name'];
//            $pos=$_POST['Position'];
//            $team=$_POST['Team'];
            $sql="DELETE FROM galileoTB WHERE id='$id'";
            try
            {
                $result=mysqli_query($con,$sql);
                if($result)
                {
                    print(json_encode(array("Successfully Deleted")));
                }else
                {
                    print(json_encode(array("Not Successfully Deleted")));
                }
            }catch (Exception $e)
            {
                print(json_encode(array("PHP EXCEPTION : CAN'T DELETE FROM MYSQL. "+$e->getMessage())));
            }
        }else{
            print(json_encode(array("PHP EXCEPTION : CAN'T CONNECT TO MYSQL. NULL CONNECTION.")));
        }
        mysqli_close($con);
    }

}
(d) Index.php
<?php

require_once("/DBAdapter.php");
    $dbAdapter=new DBAdapter();
    $dbAdapter->select();
?>

2. Gradle Scripts

Here are our gradle scripts in our build.gradle file(s).

(a). build.gradle(app)

Here's our app level build.gradle file. We have the dependencies DSL where we add our dependencies.

This file is called app level build.gradle since it's located in the app folder of the project.

If you are using Android Studio version 3 and above use implementation keyword while if you are using a version less than 3 then still use the compile keyword.

Once you've modified this build.gradle file you have to sync your project. Android Studio will indeed prompt you to do so.

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

We are using Fast Android Networking Library as our HTTP Client. You may use newer versions.

3. Resoources.

Android platform provides a powerful and flexible way of adding static content as a resource.

These static content will also be packaged into the APK file. The static content will be stored either as a resource or as an asset.

Resources belong to a given type. These types can be:

  1. Drawable.
  2. Layout.
  3. Value.

Let's start by looking at the layout resources

(a). model.xml

Our row model layout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_margin="10dp"
    card_view:cardCornerRadius="5dp"
    card_view:cardElevation="5dp"
    android:layout_height="200dp">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Name"
                android:id="@+id/nameTxt"
                android:padding="10dp"
                android:textColor="@color/colorAccent"
                android:textStyle="bold"
                android:layout_alignParentLeft="true"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Propellant....................."
                android:id="@+id/txtPropellant"
                android:padding="10dp"
                android:layout_alignParentLeft="true"
                />
            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="25dp"
                android:id="@+id/chkTechExists"
                android:checked="true" />

    </LinearLayout>

</android.support.v7.widget.CardView>
(b). content_main.xml

Our content_main layout. This layout is being inserted into our activity_main.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="com.tutorials.hp.mysqlgridviewbool.MainActivity"
    tools:showIn="@layout/activity_main">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/nameTxt"
            android:hint="Name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:textSize="25dp"
            android:enabled="true"
            android:focusable="true" />

        <LinearLayout
            android:orientation="horizontal"
            android:padding="5dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:textSize="25dp"
                android:text="Propellant"
                android:textStyle="bold"
                android:layout_width="250dp"
                android:layout_height="wrap_content" />
            <Spinner
                android:id="@+id/sp"
                android:textSize="25dp"
                android:textStyle="bold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:padding="5dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:textSize="25dp"
                android:text="Technology Exists ??"
                android:textStyle="bold"
                android:layout_width="250dp"
                android:layout_height="wrap_content" />
            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="25dp"
                android:id="@+id/techExists"
                android:checked="true" />
        </LinearLayout>

        <RelativeLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button android:id="@+id/addBtn"
                android:layout_width="wrap_content"
                android:layout_height="60dp"
                android:text="Save"
                android:clickable="true"
                android:padding="5dp"
                android:background="#009968"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                android:textSize="20dp" />

            <Button android:id="@+id/refreshBtn"
                android:layout_width="wrap_content"
                android:layout_height="60dp"
                android:text="Retrieve"
                android:padding="5dp"
                android:clickable="true"
                android:background="#f38630"
                android:textColor="@android:color/white"
                android:layout_alignParentTop="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true"
                android:textStyle="bold"
                android:textSize="20dp" />

        </RelativeLayout>

        <GridView
            android:id="@+id/gv"
            android:numColumns="2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </GridView>

    </LinearLayout>
</RelativeLayout>
(c). activity_main.xml

This is the layout for our MainActivity class.

<?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.mysqlgridviewbool.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>
(a) Spacecraft.java

Our data object.

package com.tutorials.hp.mysqlgridviewbool.mModel;

public class Spacecraft {

    /*
    INSTANCE FIELDS
     */
    private int id;
    private String name;
    private String propellant;
    private int technologyExists;

    /*
    GETTERS AND SETTERS
     */
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPropellant() {
        return propellant;
    }

    public void setPropellant(String propellant) {
        this.propellant = propellant;
    }

    public int getTechnologyExists() {
        return technologyExists;
    }

    public void setTechnologyExists(int technologyExists) {
        this.technologyExists = technologyExists;
    }
    /*
    TOSTRING
     */
    @Override
    public String toString() {
        return name;
    }
}
(b) MySQLClient.java

We are using Android Networking Library by Ahmed Shekhar to perform our network calls.These shall happen in the background thread and return us responses in JSON format.The library is fast and easy to use.

First take note that the full source code reference is above,download it including the PHP we used. Here's our MySQL client class,our most important class.  

package com.tutorials.hp.mysqlgridviewbool.mMySQL;

import android.content.Context;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.Toast;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONArrayRequestListener;
import com.tutorials.hp.mysqlgridviewbool.mAdapter.GridViewAdapter;
import com.tutorials.hp.mysqlgridviewbool.mModel.Spacecraft;

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

import java.util.ArrayList;

public class MySQLClient {

    //SAVE/RETRIEVE URLS
    private static final String DATA_INSERT_URL="http://10.0.2.2/android/Aristotle/crud.php";
    private static final String DATA_RETRIEVE_URL="http://10.0.2.2/android/Aristotle/index.php";

    //INSTANCE FIELDS
    private final Context c;
    private GridViewAdapter adapter ;

    public MySQLClient(Context c) {
        this.c = c;

    }
    /*
   SAVE/INSERT
    */
    public void add(Spacecraft s, final View...inputViews)
    {
        if(s==null)
        {
            Toast.makeText(c, "No Data To Save", Toast.LENGTH_SHORT).show();
        }
        else
        {
            AndroidNetworking.post(DATA_INSERT_URL)

                    .addBodyParameter("action","save")
                    .addBodyParameter("name",s.getName())
                    .addBodyParameter("propellant",s.getPropellant())
                    .addBodyParameter("technologyexists",String.valueOf(s.getTechnologyExists()))
                    .setTag("TAG_ADD")
                    .build()
                    .getAsJSONArray(new JSONArrayRequestListener() {
                        @Override
                        public void onResponse(JSONArray response) {

                            if(response != null)
                                try {
                                    //SHOW RESPONSE FROM SERVER
                                    String responseString = response.get(0).toString();
                                    Toast.makeText(c, "PHP SERVER RESPONSE : " + responseString, Toast.LENGTH_SHORT).show();

                                    if (responseString.equalsIgnoreCase("Success")) {
                                        //RESET VIEWS
                                        EditText nameTxt = (EditText) inputViews[0];
                                        Spinner spPropellant = (Spinner) inputViews[1];

                                        nameTxt.setText("");
                                        spPropellant.setSelection(0);
                                    }else
                                    {
                                        Toast.makeText(c, "PHP WASN'T SUCCESSFUL. ", Toast.LENGTH_SHORT).show();

                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Toast.makeText(c, "GOOD RESPONSE BUT JAVA CAN'T PARSE JSON IT RECEIVED : "+e.getMessage(), Toast.LENGTH_SHORT).show();
                                }

                        }

                        //ERROR
                        @Override
                        public void onError(ANError anError) {
                            Toast.makeText(c, "UNSUCCESSFUL :  ERROR IS : "+anError.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    });

        }
    }

    /*
    RETRIEVE/SELECT/REFRESH
     */
    public void retrieve(final GridView gv)
    {
        final ArrayList<Spacecraft> spacecrafts = new ArrayList<>();

        AndroidNetworking.get(DATA_RETRIEVE_URL)
                .setPriority(Priority.HIGH)
                .build()
                .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                        JSONObject jo;
                        Spacecraft s;
                        try
                        {
                            for(int i=0;i<response.length();i++)
                            {
                                jo=response.getJSONObject(i);

                                int id=jo.getInt("id");
                                String name=jo.getString("name");
                                String propellant=jo.getString("propellant");
                                String techExists=jo.getString("technologyexists");

                                s=new Spacecraft();
                                s.setId(id);
                                s.setName(name);
                                s.setPropellant(propellant);
                                s.setTechnologyExists(techExists.equalsIgnoreCase("1") ? 1 : 0);

                                spacecrafts.add(s);
                            }

                            //SET TO SPINNER
                            adapter =new GridViewAdapter(c,spacecrafts);
                            gv.setAdapter(adapter);

                        }catch (JSONException e)
                        {
                            Toast.makeText(c, "GOOD RESPONSE BUT JAVA CAN'T PARSE JSON IT RECEIEVED. "+e.getMessage(), Toast.LENGTH_LONG).show();

                        }

                    }

                    //ERROR
                    @Override
                    public void onError(ANError anError) {
                        anError.printStackTrace();
                        Toast.makeText(c, "UNSUCCESSFUL :  ERROR IS : "+anError.getMessage(), Toast.LENGTH_LONG).show();

                    }
                });
    }
}
(c). GridViewAdapter.java

Here's our GridView adapter class.The base class we are deriving from is baseadapter of course.We map our integers to boolean.  

package com.tutorials.hp.mysqlgridviewbool.mAdapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.tutorials.hp.mysqlgridviewbool.R;
import com.tutorials.hp.mysqlgridviewbool.mModel.Spacecraft;

import java.util.ArrayList;

public class GridViewAdapter extends BaseAdapter {

    Context c;
    ArrayList<Spacecraft> spacecrafts;

    public GridViewAdapter(Context c, ArrayList<Spacecraft> spacecrafts) {
        this.c = c;
        this.spacecrafts = spacecrafts;
    }

    @Override
    public int getCount() {
        return spacecrafts.size();
    }

    @Override
    public Object getItem(int i) {
        return spacecrafts.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            view= LayoutInflater.from(c).inflate(R.layout.model,viewGroup,false);
        }

        TextView txtName = (TextView) view.findViewById(R.id.nameTxt);
        TextView txtPropellant = (TextView) view.findViewById(R.id.txtPropellant);

        CheckBox chkTechExists = (CheckBox) view.findViewById(R.id.chkTechExists);

        final Spacecraft s= (Spacecraft) this.getItem(i);

        txtName.setText(s.getName());
        txtPropellant.setText(s.getPropellant());
        chkTechExists.setChecked( s.getTechnologyExists()==1);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(c, s.getName(), Toast.LENGTH_SHORT).show();
            }
        });

        return view;
    }
}
(d). MainActivity.java

Our main and launcher activity.

package com.tutorials.hp.mysqlgridviewbool;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.Toast;

import com.tutorials.hp.mysqlgridviewbool.mAdapter.GridViewAdapter;
import com.tutorials.hp.mysqlgridviewbool.mModel.Spacecraft;
import com.tutorials.hp.mysqlgridviewbool.mMySQL.MySQLClient;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    //INSTANCE FIELDS
    private TextInputEditText txtName;
    private CheckBox chkTechnologyExists;
    private Spinner spPropellant;
    private GridView gv;
    private Button btnAdd,btnRetrieve;

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

        //REFERENCE VIEWS
        this.initializeViews();

        populatePropellants();

        //HANDLE EVENTS
        this.handleClickEvents();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               gv.setAdapter(new GridViewAdapter(MainActivity.this,new ArrayList<Spacecraft>()));
            }
        });

    }

    /*
    REFERENCE VIEWS
     */
    private void initializeViews()
    {

        txtName= (TextInputEditText) findViewById(R.id.nameTxt);
        chkTechnologyExists= (CheckBox) findViewById(R.id.techExists);
        spPropellant= (Spinner) findViewById(R.id.sp);
        gv= (GridView) findViewById(R.id.gv);

        btnAdd= (Button) findViewById(R.id.addBtn);
        btnRetrieve= (Button) findViewById(R.id.refreshBtn);

    }

    /*
    HANDLE CLICK EVENTS
     */
    private void handleClickEvents()
    {
        //EVENTS : ADD
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //GET VALUES
                String name=txtName.getText().toString();
                String propellant=spPropellant.getSelectedItem().toString();
                Boolean technologyexists=chkTechnologyExists.isChecked();

                //BASIC CLIENT SIDE VALIDATION
                if((name.length()<1 || propellant.length()<1  ))
                {
                    Toast.makeText(MainActivity.this, "Please Enter all Fields", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    //SAVE

                    Spacecraft s=new Spacecraft();
                    s.setName(name);
                    s.setPropellant(propellant);
                    s.setTechnologyExists(technologyexists ? 1 : 0);

                    new MySQLClient(MainActivity.this).add(s,txtName,spPropellant);
                }
            }
        });

        //EVENTS : RETRIEVE
        btnRetrieve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new MySQLClient(MainActivity.this).retrieve(gv);

            }
        });

    }

    private void populatePropellants()
    {
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item);

        adapter.add("None");
        adapter.add("Chemical Energy");
        adapter.add("Nuclear Energy");
        adapter.add("Laser Beam");
        adapter.add("Anti-Matter");
        adapter.add("Plasma Ions");
        adapter.add("Warp Drive");

        spPropellant.setAdapter(adapter);
        spPropellant.setSelection(0);

    }
}

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