Android MySQL → Android MySQL – Save/Insert(HTTPURLConnection) – Camposha

Android MySQL

Android MySQL

Android MySQL

Android MySQL – Save/Insert(HTTPURLConnection)

Alot of mobile applications employ webservice to enrich their functionalities and capabilities.

Even though mobile devices are at their most powerful currently, they are still not comparable to servers. Servers understandably:

  • Have more memory.
  • Have more processing power.
  • Have more hard drives.

This then makes it imperatvie that delegate some jobs or storage services to the servers.

The most popular server side prgramming language is PHP. While the most popular Relational Database Management System(RDBMS) is MySQL. Combine those with Android the most popular mobile OS, then we have three technologies to build powerful mobile apps.

This tutorial is a start. We want to see how to connect to MySQL database from our android application via PHP. We’ll save data to the database from our app.

PHP and Java will communicate via JSON data exchange format. We’ll make use HTTPURLConnection to make webservice calls.

Android MySQL Save

Let’s go.

Our MySQL Database

Let’s start by creating a mysql database. You can use a GUI program like PHPMyAdmin.

Here’s the database table structure
Android MySQL Save

Clearly you can see our table structure comprises:

  • id (Auto-incremented).
  • name (string)
  • propellant (string)
  • description (string)

Our PHP Script

Here’s the php script

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

    $name=$_POST['name'];
    $propellant=$_POST['propellant'];
    $description=$_POST['description'];

    $sql="INSERT INTO spacecraftTB(Name,Propellant,Description) VALUES('$name','$propellant','$description')";

    $result=mysqli_query($con,$sql);

    if($result)
    {
        echo ('Successfully Saved........');

    }else
    {
        echo('Not saved Successfully............');

    }

    mysqli_close($con);

    ?>

Gradle Scripts

We’ll add two dependencies in our build.gradle.

Build.gradle

This is the app level(it’s found in the app folder of your project) build.gradle.

We’ll add two dependencies: com.android.support:appcompat-v7 and com.android.support:design.

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

AndroidManifest.xml

In your androidmanifest.xml add the permission for internet. Otherwise you application won’t be able to make network calls:

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

Our Layouts

We have two layout files:

1. activity_main.xml

This is our MainActivity’s layout.It will get inflated into MainActivity’s user interface. Our root tag is android.support.design.widget.CoordinatorLayout.

This layout is responsible for the following roles:

  1. It defines our appbar layout using the android.support.design.widget.AppBarLayout tag.
  2. It defines us toolbar using the android.support.v7.widget.Toolbar tag.
  3. It defines us a floating action button using the android.support.design.widget.FloatingActionButton.
  4. It will hold content_main.xml.
    <?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.androidmdmysqlsave.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>

2. content_main.xml

Our content_main.xml. The root tag is RelativeLayout.
It has the following roles:

  1. It defines our input edittexts and buttons.
  2. It will get included as part of activity_main.xml which will be inflated into our MainActivity UI.

Our Java Classes

Let’s now come to our Java classes.

1. Spacecraft.java

This is our data object. It’s a POJO class.

This class will define for us a single spacecraft. The spacecraft will have name, propellant and destination.

All the three will be saved into mysql database.

The roles of this class include:

  1. Define a Spacecraft object and its properties.

2. Connector.java

This is our Connector class.

As the name suggests it will connect to our URL address and return us a HTTPURLConnection object. We’ll catch java.net.MalformedURLException and java.io.IOException.

It roles include:

  1. Receive a URL address and attempt to connect to it.
  2. Return to the caller a java.net.HttpURLConnection object or null.

3. DataPackager.java

This is our datapackager class.

It’s roles include:

  1. Obtain data from a POJO object and put them into the org.json.JSONObject instance.
  2. Obtain that data’s keys and values from our JSONObject and encode it into a UTF-8 URL String to be sent via the network.
  3. Catch org.json.JSONException and java.io.UnsupportedEncodingException.
  4. Return the encoded UTF-8 string or null.

4. Sender.java

Data was packaged in the previous class: DataPackager.java.

It’s now time to send it.

This class will be responsible for:

  1. Receive context, url address and edittexts via the constructor from the MainActivity.
  2. Retrieve typed texts from the Edittexts.
  3. Show a progress dialog.
  4. Send data via the network in a background thread using Aynctask.
  5. Return response.

5. MainActivity.java

So here’s our MainActivity, a class that derives from AppCompatActivity.
The roles for this class include:

  1. It’s our launcher activity.
  2. Define the url address to our php script.
  3. Declare and initialize our views and widgets. These include : edittexts and buttons.
  4. Override OnCreate() method, inflate the XML layout and set it as content view.
  5. Reference the toolbar and set it to actionbar.
  6. Instantiate Sender class and execute it.

Download the code here.

Leave a Reply

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

Price

Free

Rating

Not enough ratings to display
X