Tuesday, August 18, 2015

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:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

        android:id="@+id/textView" />
        android:id="@+id/editTextName" />

        android:id="@+id/textView2" />

        android:id="@+id/editTextAddress" />

        android:text="Add to Database"
        android:id="@+id/button" />

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;

    protected void onCreate(Bundle savedInstanceState) {

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


    private void insertToDatabase(String name, String add){
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            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("");
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();

                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                return "Data was save";

            protected void onPostExecute(String result) {

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

    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;

    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

  $con = mysqli_connect(HOST,USER,PASS,DB);

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

  $sql = "insert into sample(name,address) values ('$name','$address')";
    echo 'success';
    echo 'failure';