Vous êtes sur la page 1sur 24

Android MySQL Tutorial to

Perform Basic CRUD Operation


Prerequisites Android MySQL Tutorial

Android Studio (Though you can do the same with eclipse)


Wamp / Xamp Server (You can also use a live hosting server)

Creating the MySQL Database

First create a database table.

Employee Table

As you can see I have a table named employee with 4 columns (id, name,
designation, salary). Id is set auto increment and primary key so we do not need
to insert id.
Now we will create our php scripts.

Creating PHP Scripts


The first thing we need is to connect to the database. So create a file
named dbConnect.php and write the following code.
1
2
3
4
5
6
7
8
9
1
0
1
1
1

<?php
/*

My Database is androiddb
you need to change the database name rest the things are default if you are using wamp or xampp
server
You may need to change the host user name or password if you have changed the defaults in your
server
*/
//Defining Constants
define('HOST','localhost');

2
1
3
1
4
1
5
1
6
1
7
1
8

define('USER','root');
define('PASS','');
define('DB','androiddb');
//Connecting to Database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

Now in CRUD the first thing is to insert data (Create)

So create a file name addEmp.php. This script will add an employee.


1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$name = $_POST['name'];
$desg = $_POST['desg'];
$sal = $_POST['salary'];
//Creating an sql query
$sql = "INSERT INTO employee (name,designation,salary) VALUES ('$name','$desg','$sal')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Employee Added Successfully';
}else{
echo 'Could Not Add Employee';
}
//Closing the database
mysqli_close($con);
}

Now after adding an employee we will fetch the name and id of all the
employees. So that user can select a particular employee to see all the details of
that employee.

For this create a new file named getAllEmp.php and write the following code.
1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7

<?php
//Importing Database Script
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT * FROM employee";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"id"=>$row['id'],
"name"=>$row['name']
));
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);

Now we need to display a selected employee. For this create a new file
named getEmp.php and write the following code.

1 <?php
2
3 //Getting the requested id

4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8

$id = $_GET['id'];
//Importing database
require_once('dbConnect.php');
//Creating sql query with where clause to get an specific employee
$sql = "SELECT * FROM employee WHERE id=$id";
//getting result
$r = mysqli_query($con,$sql);
//pushing result to an array
$result = array();
$row = mysqli_fetch_array($r);
array_push($result,array(
"id"=>$row['id'],
"name"=>$row['name'],
"desg"=>$row['designation'],
"salary"=>$row['salary']
));
//displaying in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);

Now in CRUD we have completed (C-Create (Insert) and R-Read(Fetch)) the next is UUpdate. We may need to update the details of an existing employee. For this create a
new file named updateEmp.php and write the following code.

1
2
3
4
5
6
7
8
9
1
0

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$id = $_POST['id'];
$name = $_POST['name'];
$desg = $_POST['desg'];
$sal = $_POST['salary'];
//importing database connection script
require_once('dbConnect.php');

1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4

//Creating sql query


$sql = "UPDATE employee SET name = '$name', designation = '$desg', salary = '$sal' WHERE id =
$id;";
//Updating database table
if(mysqli_query($con,$sql)){
echo 'Employee Updated Successfully';
}else{
echo 'Could Not Update Employee Try Again';
}
//closing connection
mysqli_close($con);
}

Now the final thing which is D-Delete. We may need to delete an existing employee. For
this create a new file nameddeleteEmp.php and write the following.

1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1

<?php
//Getting Id
$id = $_GET['id'];
//Importing database
require_once('dbConnect.php');
//Creating sql query
$sql = "DELETE FROM employee WHERE id=$id;";
//Deleting record in database
if(mysqli_query($con,$sql)){
echo 'Employee Deleted Successfully';
}else{
echo 'Could Not Delete Employee Try Again';
}
//closing connection
mysqli_close($con);

Now thats all we have created all the scripts for CRUD operation. Now we need
the address of these scripts. In my case I am using wamp server. And my server is
running in my ip -> http://192.168.94.1
To know what is the ip in your system you can use ipconfig command. Open
command prompt and write ipconfig and hit enter.

So I am using wamp server and for wamp the root directory is www (usually
c:/wamp/www). And I stored my scripts inside www/Android/CRUD. So the paths to
my scripts would be
http://192.168.94.1/Android/CRUD/file_name.php
This is for my case. You have to know the correct url according to your system.
Now thats all for the server side part. Lets move to android studio.

Creating an Android Studio Project


Create a new Android Studio project. For this Android MySQL Tutorial I have
created my project named MySQLCRUD.
In this Android MySQL Application we will be performing some network operations we
need internet permission. So add internet permission to your manifest file.

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

Now create a new java class inside your package named Config. And write the
following code.
1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1

package net.simplifiedcoding.mysqlcrud;
/**
* Created by Belal on 10/24/2015.
*/
public class Config {
//Address of our scripts of the CRUD
public static final String URL_ADD="http://192.168.94.1/Android/CRUD/addEmp.php";
public static final String URL_GET_ALL = "http://192.168.94.1/Android/CRUD/getAllEmp.php";
public static final String URL_GET_EMP = "http://192.168.94.1/Android/CRUD/getEmp.php?id=";
public static final String URL_UPDATE_EMP =
"http://192.168.94.1/Android/CRUD/updateEmp.php";
public static final String URL_DELETE_EMP = "http://192.168.94.1/Android/CRUD/deleteEmp.php?
id=";
//Keys
public
public
public
public

that will be used to send the request to php scripts


static final String KEY_EMP_ID = "id";
static final String KEY_EMP_NAME = "name";
static final String KEY_EMP_DESG = "desg";
static final String KEY_EMP_SAL = "salary";

//JSON Tags
public static final String TAG_JSON_ARRAY="result";

7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
}
2
6
2
7
2
8
2
9
3
0

public
public
public
public

static
static
static
static

final
final
final
final

String
String
String
String

TAG_ID = "id";
TAG_NAME = "name";
TAG_DESG = "desg";
TAG_SAL = "salary";

//employee id to pass with intent


public static final String EMP_ID = "emp_id";

We will create a separate class for handling our networking request. So create a new
class inside your package named RequestHandler. And write the following code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

package net.simplifiedcoding.mysqlcrud;
import
import
import
import
import
import
import
import
import
import
import

java.io.BufferedReader;
java.io.BufferedWriter;
java.io.InputStreamReader;
java.io.OutputStream;
java.io.OutputStreamWriter;
java.io.UnsupportedEncodingException;
java.net.HttpURLConnection;
java.net.URL;
java.net.URLEncoder;
java.util.HashMap;
java.util.Map;

import javax.net.ssl.HttpsURLConnection;
public class RequestHandler {
//Method to send httpPostRequest
//This method is taking two arguments
//First argument is the URL of the script to which we will send the request
//Other is an HashMap with name value pairs containing the data to be send with the request
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
//Creating a URL
URL url;
//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try {

32
//Initializing Url
33
url = new URL(requestURL);
34
35
//Creating an httmlurl connection
36
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
37
38
//Configuring connection properties
39
conn.setReadTimeout(15000);
40
conn.setConnectTimeout(15000);
41
conn.setRequestMethod("POST");
42
conn.setDoInput(true);
43
conn.setDoOutput(true);
44
45
//Creating an output stream
46
OutputStream os = conn.getOutputStream();
47
48
//Writing parameters to the request
49
//We are using a method getPostDataString which is defined below
50
BufferedWriter writer = new BufferedWriter(
51
new OutputStreamWriter(os, "UTF-8"));
52
writer.write(getPostDataString(postDataParams));
53
54
writer.flush();
55
writer.close();
56
os.close();
57
int responseCode = conn.getResponseCode();
58
59
if (responseCode == HttpsURLConnection.HTTP_OK) {
60
61
BufferedReader br = new BufferedReader(new
62 InputStreamReader(conn.getInputStream()));
63
sb = new StringBuilder();
64
String response;
65
//Reading server response
66
while ((response = br.readLine()) != null){
67
sb.append(response);
68
}
69
}
70
71
} catch (Exception e) {
72
e.printStackTrace();
73
}
74
return sb.toString();
75
}
76
77
public String sendGetRequest(String requestURL){
78
StringBuilder sb =new StringBuilder();
79
try {
80
URL url = new URL(requestURL);
81
HttpURLConnection con = (HttpURLConnection) url.openConnection();
82
BufferedReader bufferedReader = new BufferedReader(new
83 InputStreamReader(con.getInputStream()));
84
85
String s;
86
while((s=bufferedReader.readLine())!=null){
87
sb.append(s+"\n");
88
}
89
}catch(Exception e){
90
}
91
return sb.toString();
92
}

93
94
public String sendGetRequestParam(String requestURL, String id){
95
StringBuilder sb =new StringBuilder();
96
try {
97
URL url = new URL(requestURL+id);
98
HttpURLConnection con = (HttpURLConnection) url.openConnection();
99
BufferedReader bufferedReader = new BufferedReader(new
10 InputStreamReader(con.getInputStream()));
0
10
String s;
1
while((s=bufferedReader.readLine())!=null){
10
sb.append(s+"\n");
2
}
10
}catch(Exception e){
3
}
10
return sb.toString();
4
}
10
5
private String getPostDataString(HashMap<String, String> params) throws
10 UnsupportedEncodingException {
6
StringBuilder result = new StringBuilder();
10
boolean first = true;
7
for (Map.Entry<String, String> entry : params.entrySet()) {
10
if (first)
8
first = false;
10
else
9
result.append("&");
11
0
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
11
result.append("=");
1
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
11
}
2
11
return result.toString();
3
}
11 }
4
11
5
11
6
11
7
11
8
11
9
12
0
12
1
12
2
12
3
12
4
12
5
12
6

12
7

For our application we will need two more activities other than our MainActivity.
One is to show the list of all employee from where user can select a particular
employee to see. And the other one is to show the details of selected employee
from where we can update and delete the employee as well. And from
the MainActivity we will add an employee. So before going further create two
more activities named ViewAllEmployee and ViewEmployee.
Now for activity_main.xml create the following layout

Use the following xml code for the above layout


1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
3
android:orientation="vertical"
4
android:layout_height="match_parent"
5 android:paddingLeft="@dimen/activity_horizontal_margin"
6
android:paddingRight="@dimen/activity_horizontal_margin"
7
android:paddingTop="@dimen/activity_vertical_margin"
8
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
9
1
<TextView
0
android:layout_width="wrap_content"
1
android:layout_height="wrap_content"
1
android:text="Employee Name" />
1
2
<EditText
1
android:layout_width="match_parent"
3
android:layout_height="wrap_content"
1
android:id="@+id/editTextName" />
4
1
<TextView
5
android:layout_width="wrap_content"
1
android:layout_height="wrap_content"
6
android:text="Designation" />
1
7
<EditText
1
android:layout_width="match_parent"
8
android:layout_height="wrap_content"
1
android:id="@+id/editTextDesg" />
9
2
<TextView
0
android:layout_width="wrap_content"
2
android:layout_height="wrap_content"
1
android:text="Salary" />
2

2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
<EditText
3
android:layout_width="match_parent"
3
android:layout_height="wrap_content"
3
android:id="@+id/editTextSalary" />
4
3
<Button
5
android:layout_width="match_parent"
3
android:layout_height="wrap_content"
6
android:text="Add Employee"
3
android:id="@+id/buttonAdd" />
7
3
<Button
8
android:layout_width="match_parent"
3
android:layout_height="wrap_content"
9
android:text="View Employee"
4
android:id="@+id/buttonView" />
0
4
</LinearLayout>
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1

Write the following code in MainActivity.java

1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5

package net.simplifiedcoding.mysqlcrud;
import
import
import
import
import
import
import
import
import
import
import

android.app.ProgressDialog;
android.content.Intent;
android.os.AsyncTask;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.Menu;
android.view.MenuItem;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;

import java.util.HashMap;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
//Defining views
private EditText editTextName;
private EditText editTextDesg;
private EditText editTextSal;
private Button buttonAdd;
private Button buttonView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing views
editTextName = (EditText) findViewById(R.id.editTextName);
editTextDesg = (EditText) findViewById(R.id.editTextDesg);
editTextSal = (EditText) findViewById(R.id.editTextSalary);
buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonView = (Button) findViewById(R.id.buttonView);
//Setting listeners to button
buttonAdd.setOnClickListener(this);
buttonView.setOnClickListener(this);
}
//Adding an employee
private void addEmployee(){
final String name = editTextName.getText().toString().trim();
final String desg = editTextDesg.getText().toString().trim();
final String sal = editTextSal.getText().toString().trim();
class AddEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Adding...","Wait...",false,false);
}

3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3 }
5
4
5
5
5
6
5
7
5
8
5
9
6
0
6
1
6
2
6
3
6
4
6
5
6

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... v) {
HashMap<String,String> params = new HashMap<>();
params.put(Config.KEY_EMP_NAME,name);
params.put(Config.KEY_EMP_DESG,desg);
params.put(Config.KEY_EMP_SAL,sal);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Config.URL_ADD, params);
return res;
}
}
AddEmployee ae = new AddEmployee();
ae.execute();
}
@Override
public void onClick(View v) {
if(v == buttonAdd){
addEmployee();
}
if(v == buttonView){
startActivity(new Intent(this,ViewAllEmployee.class));
}
}

6
6
7
6
8
6
9
7
0
7
1
7
2
7
3
7
4
7
5
7
6
7
7
7
8
7
9
8
0
8
1
8
2
8
3
8
4
8
5
8
6
8
7
8
8
8
9
9
0
9
1
9
2
9
3
9
4
9
5
9
6

9
7

Now from this activity we will move to the activity ViewAllEmployee. So create
the following layout in ViewAllEmployees layout file which
is activity_view_all_employee.xml.
In this activity we will create a ListView only.

You can use the following code for the above layout
1
2
3
4
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
5
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
6
android:orientation="vertical"
7
android:layout_height="match_parent"
8
android:paddingLeft="@dimen/activity_horizontal_margin"
9
android:paddingRight="@dimen/activity_horizontal_margin"
1
android:paddingTop="@dimen/activity_vertical_margin"
0
android:paddingBottom="@dimen/activity_vertical_margin"
1
tools:context="net.simplifiedcoding.mysqlcrud.ViewAllEmployee">
1
1
2
<ListView
1
android:layout_width="match_parent"
3
android:layout_height="wrap_content"
1
android:id="@+id/listView" />
4
1
5
</LinearLayout>
1
6
1
7

Because we are creating a ListView, we need one more Layout Resource File for our
ListView. Inside layouts create a new xml file named list_item.xml and write the
following code.

1
2
3
4
<?xml version="1.0" encoding="utf-8"?>
5
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
6
android:orientation="vertical" android:layout_width="match_parent"
7
android:layout_height="match_parent">
8
9
<TextView
1
android:id="@+id/id"
0
android:layout_width="wrap_content"
1
android:layout_height="wrap_content" />
1
1
<TextView
2
android:id="@+id/name"
1
android:layout_width="wrap_content"
3
android:layout_height="wrap_content" />
1
4
</LinearLayout>
1
5
1
6

Now write the following code in ViewAllEmployee.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

package net.simplifiedcoding.mysqlcrud;
import
import
import
import
import
import
import
import
import
import
import
import
import

android.app.ProgressDialog;
android.content.Intent;
android.os.AsyncTask;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.Menu;
android.view.MenuItem;
android.view.View;
android.widget.AdapterView;
android.widget.ListAdapter;
android.widget.ListView;
android.widget.SimpleAdapter;
android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ViewAllEmployee extends AppCompatActivity implements ListView.OnItemClickListener
{
private ListView listView;
private String JSON_STRING;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_employee);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);

37
getJSON();
38
}
39
40
41
private void showEmployee(){
42
JSONObject jsonObject = null;
43
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
44
try {
45
jsonObject = new JSONObject(JSON_STRING);
46
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
47
48
for(int i = 0; i<result.length(); i++){
49
JSONObject jo = result.getJSONObject(i);
50
String id = jo.getString(Config.TAG_ID);
51
String name = jo.getString(Config.TAG_NAME);
52
53
HashMap<String,String> employees = new HashMap<>();
54
employees.put(Config.TAG_ID,id);
55
employees.put(Config.TAG_NAME,name);
56
list.add(employees);
57
}
58
59
} catch (JSONException e) {
60
e.printStackTrace();
61
}
62
63
ListAdapter adapter = new SimpleAdapter(
64
ViewAllEmployee.this, list, R.layout.list_item,
65
new String[]{Config.TAG_ID,Config.TAG_NAME},
66
new int[]{R.id.id, R.id.name});
67
68
listView.setAdapter(adapter);
69
}
70
71
private void getJSON(){
72
class GetJSON extends AsyncTask<Void,Void,String>{
73
74
ProgressDialog loading;
75
@Override
76
protected void onPreExecute() {
77
super.onPreExecute();
78
loading = ProgressDialog.show(ViewAllEmployee.this,"Fetching
79 Data","Wait...",false,false);
80
}
81
82
@Override
83
protected void onPostExecute(String s) {
84
super.onPostExecute(s);
85
loading.dismiss();
86
JSON_STRING = s;
87
showEmployee();
88
}
89
90
@Override
91
protected String doInBackground(Void... params) {
92
RequestHandler rh = new RequestHandler();
93
String s = rh.sendGetRequest(Config.URL_GET_ALL);
94
return s;
95
}
96
}
97
GetJSON gj = new GetJSON();

98
99
10
0
10
1
10
2
10
3
10
4
10
5
10 }
6
10
7

gj.execute();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, ViewEmployee.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String empId = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.EMP_ID,empId);
startActivity(intent);
}

Now from this screen user can select a particular employee to see the detail. And
from this activity we will move to the next activity where we can delete or update
employee. So create following layout for your activity ViewEmployee. For this
activity I have activity_view_employee.xml . So we will create the following
layout.

Write the following code in ViewEmployee.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14

package net.simplifiedcoding.mysqlcrud;
import
import
import
import
import
import
import
import
import
import
import
import

android.app.ProgressDialog;
android.content.DialogInterface;
android.content.Intent;
android.os.AsyncTask;
android.support.v7.app.AlertDialog;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.Menu;
android.view.MenuItem;
android.view.View;
android.widget.Button;
android.widget.EditText;

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class ViewEmployee extends AppCompatActivity implements View.OnClickListener {
private
private
private
private

EditText
EditText
EditText
EditText

editTextId;
editTextName;
editTextDesg;
editTextSalary;

private Button buttonUpdate;


private Button buttonDelete;
private String id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_employee);
Intent intent = getIntent();
id = intent.getStringExtra(Config.EMP_ID);
editTextId = (EditText) findViewById(R.id.editTextId);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextDesg = (EditText) findViewById(R.id.editTextDesg);
editTextSalary = (EditText) findViewById(R.id.editTextSalary);
buttonUpdate = (Button) findViewById(R.id.buttonUpdate);
buttonDelete = (Button) findViewById(R.id.buttonDelete);
buttonUpdate.setOnClickListener(this);
buttonDelete.setOnClickListener(this);
editTextId.setText(id);
getEmployee();
}
private void getEmployee(){
class GetEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewEmployee.this,"Fetching...","Wait...",false,false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
showEmployee(s);
}

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
10
0
10
1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
11
0
11
1
11
2
11
3
11
4
11
5
11
6
11
7
11

@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Config.URL_GET_EMP,id);
return s;
}
}
GetEmployee ge = new GetEmployee();
ge.execute();
}
private void showEmployee(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
String name = c.getString(Config.TAG_NAME);
String desg = c.getString(Config.TAG_DESG);
String sal = c.getString(Config.TAG_SAL);
editTextName.setText(name);
editTextDesg.setText(desg);
editTextSalary.setText(sal);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateEmployee(){
final String name = editTextName.getText().toString().trim();
final String desg = editTextDesg.getText().toString().trim();
final String salary = editTextSalary.getText().toString().trim();
class UpdateEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewEmployee.this,"Updating...","Wait...",false,false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ViewEmployee.this,s,Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... params) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put(Config.KEY_EMP_ID,id);
hashMap.put(Config.KEY_EMP_NAME,name);
hashMap.put(Config.KEY_EMP_DESG,desg);
hashMap.put(Config.KEY_EMP_SAL,salary);
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Config.URL_UPDATE_EMP,hashMap);

8
11
9
12
0
12
1
12
2
12
3
12
4
12
5
12
6
12
7
12
8
12
9
13
0
13
1
13
2
13
3
13
4
13
5
13
6
13
7
13
8
13
9
14
0
14
1
14
2
14
3
14
4
14
5
14
6
14
7
14
8

return s;
}
}
UpdateEmployee ue = new UpdateEmployee();
ue.execute();
}
private void deleteEmployee(){
class DeleteEmployee extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewEmployee.this, "Updating...", "Wait...", false, false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ViewEmployee.this, s, Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Config.URL_DELETE_EMP, id);
return s;
}
}
DeleteEmployee de = new DeleteEmployee();
de.execute();
}
private void confirmDeleteEmployee(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to delete this employee?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
deleteEmployee();
startActivity(new Intent(ViewEmployee.this,ViewAllEmployee.class));
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

14
9
15
0
15
1
15
2
15
3
15
4
15 }
5
15
6
15
7
15
8
15
9
16
0
16
1
16
2
16
3
16
4
16
5
16
6
16
7
16
8
16
9
17
0
17
1
17
2
17
3
17
4
17
5
17
6
17
7
17
8
17

}
@Override
public void onClick(View v) {
if(v == buttonUpdate){
updateEmployee();
}
if(v == buttonDelete){
confirmDeleteEmployee();
}
}

9
18
0
18
1
18
2
18
3
18
4
18
5
18
6
18
7
18
8
18
9
19
0
19
1
19
2
19
3
19
4
19
5
19
6
19
7
19
8
19
9
20
0
20
1
20
2
20
3
20
4
20
5
20
6
20
7
20
8
20
9

21
0

Now try running your application and you will see the following output.
If you need my source code then you can get it from here

Android MySQL Tutorial to Perform Basic CRUD Operation (7174 downloads)


So thats all for this Android MySQL tutorial friends. Share this Android MySQL tutorial
among your friends if you found it useful and Stay tuned for more android tutorials.
Thank You

The array_push() function inserts one or more elements to the end of an array.