Add to MySQL android apps

The mobile application example in this article is a basic tutorial for a beginner programmer who wants to learn about android development. In this example tutorial the user will type the data in the mobile phone using apps then send the data to a web server over the Internet and add or insert the data to MySQL database. The figure below illustrates how the data is sent from mobile phone to a web server:
android php mysql tutorial
To begin with this tutorial we need to have a PC that will serve as our web server. This PC should have the following software: Apache web server and MySQL or XAMP which is a complete package. In order for our android apps database application to work we need to create a database in MySQL. To do that assuming that our web server is already running open web browser for example Firefox, in the address bar type http://localhost/phpmyadmin. In the Create new database textbox type add_per as the name of database.  Click the create button to create a new database. 

android apps database

Create a table and name it as sample with two fields namely (name data type varchar and address data type varchar both with 255 length)

After setting up the database it is now time to create the android apps. Open the android studio. To create the apps design click on activity_main.xml and type the following code:
<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:orientation="vertical"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:id="@+id/textView" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextName" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Address"
        android:id="@+id/textView2" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextAddress" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add to Database"
        android:onClick="insert"
        android:id="@+id/button" />
</LinearLayout>

The design of the android apps will look like this:
insert data to mysql database
For the code, click on MainActivity.java and type the following code:
package com.kid.mydata;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends ActionBarActivity {

    private EditText editTextName;
    private EditText editTextAdd;


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

        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextAdd = (EditText) findViewById(R.id.editTextAddress);


    }

    public void insert(View view){
        String name = editTextName.getText().toString();
        String add = editTextAdd.getText().toString();

        insertToDatabase(name,add);
    }

    private void insertToDatabase(String name, String add){
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {
               String paramUsername = params[0];
               String paramAddress = params[1];


                String name = editTextName.getText().toString();
                String add = editTextAdd.getText().toString();

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("name", name));
                nameValuePairs.add(new BasicNameValuePair("address", add));

                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost("http://192.168.5.76/data/adddata.php");
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();


                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                }
                return "Data was save";
            }

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

                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
                editTextName.setText("");
                editTextAdd.setText("");
                EditText mEdit;
                mEdit = (EditText)findViewById(R.id.editTextName);
                mEdit.requestFocus();
            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(name, add);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

In order for our android apps database application to run and communicate to web services we need to add Internet permission in the manifest file. To do that open the manifest file by clicking on it. It s found at the left side of your screen. Add the code below and place it above the <application … /application>:

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

Lastly go to XAMPP htdocs folder and create a new folder and name it as data then open a text editor and write the following PHP script and save it as data.php

<?php
  define('HOST','127.0.0.1');
  define('USER','root');
  define('PASS','');
  define('DB','add_per');
  $con = mysqli_connect(HOST,USER,PASS,DB);

$name = $_POST['name'];
$address = $_POST['address'];

  $sql = "insert into sample(name,address) values ('$name','$address')";
  if(mysqli_query($con,$sql)){
    echo 'success';
  }
  else{
    echo 'failure';
  }
  mysqli_close($con);
?>