You are on page 1of 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 <?php
2 /*
3
4
5
My Database is androiddb
6
you need to change the database name rest the things are default if you are using wamp or xampp
7
server
8
You may need to change the host user name or password if you have changed the defaults in your
9
server
1
*/
0
1
1 //Defining Constants
1 define('HOST','localhost');
2
1
3
1 define('USER','root');
4 define('PASS','');
1 define('DB','androiddb');
5
1
6 //Connecting to Database
1 $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
7
1
8
 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 <?php
9 if($_SERVER['REQUEST_METHOD']=='POST'){
1
0 //Getting values
1 $name = $_POST['name'];
1 $desg = $_POST['desg'];
1 $sal = $_POST['salary'];
2
1 //Creating an sql query
3 $sql = "INSERT INTO employee (name,designation,salary) VALUES ('$name','$desg','$sal')";
1
4
1 //Importing our db connection script
5 require_once('dbConnect.php');
1
6 //Executing query to database
1 if(mysqli_query($con,$sql)){
7 echo 'Employee Added Successfully';
1 }else{
8 echo 'Could Not Add Employee';
1 }
9
2 //Closing the database
0 mysqli_close($con);
2 }
1
2
2
2
3
2
4
 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 <?php
1 //Importing Database Script
0 require_once('dbConnect.php');
1
1
//Creating sql query
1
$sql = "SELECT * FROM employee";
2
1
3 //getting result
1 $r = mysqli_query($con,$sql);
4
1 //creating a blank array
5 $result = array();
1
6 //looping through all the records fetched
1 while($row = mysqli_fetch_array($r)){
7
1 //Pushing name and id in the blank array created
8 array_push($result,array(
1 "id"=>$row['id'],
9 "name"=>$row['name']
2 ));
0 }
2
1
//Displaying the array in json format
2
echo json_encode(array('result'=>$result));
2
2
3 mysqli_close($con);
2
4
2
5
2
6
2
7
 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 $id = $_GET['id'];
1
2 //Importing database
1 require_once('dbConnect.php');
3
1 //Creating sql query with where clause to get an specific employee
4 $sql = "SELECT * FROM employee WHERE id=$id";
1
5
1 //getting result
6 $r = mysqli_query($con,$sql);
1
7 //pushing result to an array
1 $result = array();
8 $row = mysqli_fetch_array($r);
1 array_push($result,array(
9 "id"=>$row['id'],
2 "name"=>$row['name'],
0 "desg"=>$row['designation'],
2 "salary"=>$row['salary']
1 ));
2
2 //displaying in json format
2 echo json_encode(array('result'=>$result));
3
2 mysqli_close($con);
4
2
5
2
6
2
7
2
8
Now in CRUD we have completed (C-Create (Insert) and R-Read(Fetch)) the next is U-
Update. 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 <?php
2 if($_SERVER['REQUEST_METHOD']=='POST'){
3 //Getting values
4 $id = $_POST['id'];
5 $name = $_POST['name'];
6 $desg = $_POST['desg'];
7 $sal = $_POST['salary'];
8
9 //importing database connection script
1 require_once('dbConnect.php');
0
1
1
1
2
1
3
1
4 //Creating sql query
1 $sql = "UPDATE employee SET name = '$name', designation = '$desg', salary = '$sal' WHERE id =
5 $id;";
1
6
1 //Updating database table
7 if(mysqli_query($con,$sql)){
1 echo 'Employee Updated Successfully';
8 }else{
1 echo 'Could Not Update Employee Try Again';
9 }
2
0 //closing connection
2 mysqli_close($con);
1 }
2
2
2
3
2
4
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 <?php
2 //Getting Id
3 $id = $_GET['id'];
4
5 //Importing database
6 require_once('dbConnect.php');
7
8
//Creating sql query
9
$sql = "DELETE FROM employee WHERE id=$id;";
1
0
1 //Deleting record in database
1 if(mysqli_query($con,$sql)){
1 echo 'Employee Deleted Successfully';
2 }else{
1 echo 'Could Not Delete Employee Try Again';
3 }
1
4 //closing connection
1 mysqli_close($con);
5
1
6
1
7
1
8
1
9
 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.

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


Now create a new java class inside your package named Config. And write the
following code.
1 package net.simplifiedcoding.mysqlcrud;
2
3 /**
4 * Created by Belal on 10/24/2015.
5 */
6 public class Config {
7
8 //Address of our scripts of the CRUD
9 public static final String URL_ADD="http://192.168.94.1/Android/CRUD/addEmp.php";
1 public static final String URL_GET_ALL = "http://192.168.94.1/Android/CRUD/getAllEmp.php";
0 public static final String URL_GET_EMP = "http://192.168.94.1/Android/CRUD/getEmp.php?id=";
1 public static final String URL_UPDATE_EMP =
1 "http://192.168.94.1/Android/CRUD/updateEmp.php";
1 public static final String URL_DELETE_EMP = "http://192.168.94.1/Android/CRUD/deleteEmp.php?
2 id=";
1
3 //Keys that will be used to send the request to php scripts
1 public static final String KEY_EMP_ID = "id";
4 public static final String KEY_EMP_NAME = "name";
1 public static final String KEY_EMP_DESG = "desg";
5 public static final String KEY_EMP_SAL = "salary";
1
6 //JSON Tags
1 public static final String TAG_JSON_ARRAY="result";
7
1
8
1
9
2
0
2
1
2
public static final String TAG_ID = "id";
2
public static final String TAG_NAME = "name";
2
public static final String TAG_DESG = "desg";
3
public static final String TAG_SAL = "salary";
2
4
//employee id to pass with intent
2
public static final String EMP_ID = "emp_id";
5
}
2
6
2
7
2
8
2
9
3
0
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 package net.simplifiedcoding.mysqlcrud;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.InputStreamReader;
6 import java.io.OutputStream;
7 import java.io.OutputStreamWriter;
8 import java.io.UnsupportedEncodingException;
9 import java.net.HttpURLConnection;
10 import java.net.URL;
11 import java.net.URLEncoder;
12 import java.util.HashMap;
13 import java.util.Map;
14
15 import javax.net.ssl.HttpsURLConnection;
16
17
18 public class RequestHandler {
19
20 //Method to send httpPostRequest
21 //This method is taking two arguments
22 //First argument is the URL of the script to which we will send the request
23 //Other is an HashMap with name value pairs containing the data to be send with the request
24 public String sendPostRequest(String requestURL,
25 HashMap<String, String> postDataParams) {
26 //Creating a URL
27 URL url;
28
29 //StringBuilder object to store the message retrieved from the server
30 StringBuilder sb = new StringBuilder();
31 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 package net.simplifiedcoding.mysqlcrud;
2
3 import android.app.ProgressDialog;
4 import android.content.Intent;
5 import android.os.AsyncTask;
6 import android.support.v7.app.AppCompatActivity;
7 import android.os.Bundle;
8 import android.view.Menu;
9 import android.view.MenuItem;
1 import android.view.View;
0 import android.widget.Button;
1 import android.widget.EditText;
1 import android.widget.Toast;
1
2 import java.util.HashMap;
1
3 public class MainActivity extends AppCompatActivity implements View.OnClickListener{
1
4 //Defining views
1 private EditText editTextName;
5 private EditText editTextDesg;
1 private EditText editTextSal;
6
1 private Button buttonAdd;
7 private Button buttonView;
1
8 @Override
1 protected void onCreate(Bundle savedInstanceState) {
9 super.onCreate(savedInstanceState);
2 setContentView(R.layout.activity_main);
0
2 //Initializing views
1 editTextName = (EditText) findViewById(R.id.editTextName);
2 editTextDesg = (EditText) findViewById(R.id.editTextDesg);
2 editTextSal = (EditText) findViewById(R.id.editTextSalary);
2
3 buttonAdd = (Button) findViewById(R.id.buttonAdd);
2 buttonView = (Button) findViewById(R.id.buttonView);
4
2 //Setting listeners to button
5 buttonAdd.setOnClickListener(this);
2 buttonView.setOnClickListener(this);
6 }
2
7
2 //Adding an employee
8 private void addEmployee(){
2
9 final String name = editTextName.getText().toString().trim();
3 final String desg = editTextDesg.getText().toString().trim();
0 final String sal = editTextSal.getText().toString().trim();
3
1 class AddEmployee extends AsyncTask<Void,Void,String>{
3
2 ProgressDialog loading;
3
3 @Override
3 protected void onPreExecute() {
4 super.onPreExecute();
3 loading = ProgressDialog.show(MainActivity.this,"Adding...","Wait...",false,false);
5 }
3
6 @Override
3 protected void onPostExecute(String s) {
7 super.onPostExecute(s);
3 loading.dismiss();
8 Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
3 }
9
4 @Override
0 protected String doInBackground(Void... v) {
4 HashMap<String,String> params = new HashMap<>();
1 params.put(Config.KEY_EMP_NAME,name);
4 params.put(Config.KEY_EMP_DESG,desg);
2 params.put(Config.KEY_EMP_SAL,sal);
4
3 RequestHandler rh = new RequestHandler();
4 String res = rh.sendPostRequest(Config.URL_ADD, params);
4 return res;
4 }
5 }
4
6 AddEmployee ae = new AddEmployee();
4 ae.execute();
7 }
4
8 @Override
4 public void onClick(View v) {
9 if(v == buttonAdd){
5 addEmployee();
0 }
5
1 if(v == buttonView){
5 startActivity(new Intent(this,ViewAllEmployee.class));
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
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 ViewAllEmployee’s 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 package net.simplifiedcoding.mysqlcrud;
2
3 import android.app.ProgressDialog;
4 import android.content.Intent;
5 import android.os.AsyncTask;
6 import android.support.v7.app.AppCompatActivity;
7 import android.os.Bundle;
8 import android.view.Menu;
9 import android.view.MenuItem;
10 import android.view.View;
11 import android.widget.AdapterView;
12 import android.widget.ListAdapter;
13 import android.widget.ListView;
14 import android.widget.SimpleAdapter;
15 import android.widget.Toast;
16
17 import org.json.JSONArray;
18 import org.json.JSONException;
19 import org.json.JSONObject;
20
21 import java.util.ArrayList;
22 import java.util.HashMap;
23
24 public class ViewAllEmployee extends AppCompatActivity implements ListView.OnItemClickListener
25 {
26
27 private ListView listView;
28
29 private String JSON_STRING;
30
31 @Override
32 protected void onCreate(Bundle savedInstanceState) {
33 super.onCreate(savedInstanceState);
34 setContentView(R.layout.activity_view_all_employee);
35 listView = (ListView) findViewById(R.id.listView);
36 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 gj.execute();
10 }
1
10 @Override
2 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
10 Intent intent = new Intent(this, ViewEmployee.class);
3 HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
10 String empId = map.get(Config.TAG_ID).toString();
4 intent.putExtra(Config.EMP_ID,empId);
10 startActivity(intent);
5 }
10 }
6
10
7
 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 package net.simplifiedcoding.mysqlcrud;
2
3 import android.app.ProgressDialog;
4 import android.content.DialogInterface;
5 import android.content.Intent;
6 import android.os.AsyncTask;
7 import android.support.v7.app.AlertDialog;
8 import android.support.v7.app.AppCompatActivity;
9 import android.os.Bundle;
10 import android.view.Menu;
11 import android.view.MenuItem;
12 import android.view.View;
13 import android.widget.Button;
14 import android.widget.EditText;
15 import android.widget.Toast;
16
17 import org.json.JSONArray;
18 import org.json.JSONException;
19 import org.json.JSONObject;
20
21 import java.util.HashMap;
22
23 public class ViewEmployee extends AppCompatActivity implements View.OnClickListener {
24
25 private EditText editTextId;
26 private EditText editTextName;
27 private EditText editTextDesg;
28 private EditText editTextSalary;
29
30 private Button buttonUpdate;
31 private Button buttonDelete;
32
33 private String id;
34
35 @Override
36 protected void onCreate(Bundle savedInstanceState) {
37 super.onCreate(savedInstanceState);
38 setContentView(R.layout.activity_view_employee);
39
40 Intent intent = getIntent();
41
42 id = intent.getStringExtra(Config.EMP_ID);
43
44 editTextId = (EditText) findViewById(R.id.editTextId);
45 editTextName = (EditText) findViewById(R.id.editTextName);
46 editTextDesg = (EditText) findViewById(R.id.editTextDesg);
47 editTextSalary = (EditText) findViewById(R.id.editTextSalary);
48
49 buttonUpdate = (Button) findViewById(R.id.buttonUpdate);
50 buttonDelete = (Button) findViewById(R.id.buttonDelete);
51
52 buttonUpdate.setOnClickListener(this);
53 buttonDelete.setOnClickListener(this);
54
55 editTextId.setText(id);
56
57 getEmployee();
58 }
59
60 private void getEmployee(){
61 class GetEmployee extends AsyncTask<Void,Void,String>{
62 ProgressDialog loading;
63 @Override
64 protected void onPreExecute() {
65 super.onPreExecute();
66 loading = ProgressDialog.show(ViewEmployee.this,"Fetching...","Wait...",false,false);
67 }
68
69 @Override
70 protected void onPostExecute(String s) {
71 super.onPostExecute(s);
72 loading.dismiss();
73 showEmployee(s);
74 }
75
76 @Override
77 protected String doInBackground(Void... params) {
78 RequestHandler rh = new RequestHandler();
79 String s = rh.sendGetRequestParam(Config.URL_GET_EMP,id);
80 return s;
81 }
82 }
83 GetEmployee ge = new GetEmployee();
84 ge.execute();
85 }
86
87 private void showEmployee(String json){
88 try {
89 JSONObject jsonObject = new JSONObject(json);
90 JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
91 JSONObject c = result.getJSONObject(0);
92 String name = c.getString(Config.TAG_NAME);
93 String desg = c.getString(Config.TAG_DESG);
94 String sal = c.getString(Config.TAG_SAL);
95
96 editTextName.setText(name);
97 editTextDesg.setText(desg);
98 editTextSalary.setText(sal);
99
10 } catch (JSONException e) {
0 e.printStackTrace();
10 }
1 }
10
2
10 private void updateEmployee(){
3 final String name = editTextName.getText().toString().trim();
10 final String desg = editTextDesg.getText().toString().trim();
4 final String salary = editTextSalary.getText().toString().trim();
10
5 class UpdateEmployee extends AsyncTask<Void,Void,String>{
10 ProgressDialog loading;
6 @Override
10 protected void onPreExecute() {
7 super.onPreExecute();
10 loading = ProgressDialog.show(ViewEmployee.this,"Updating...","Wait...",false,false);
8 }
10
9 @Override
11 protected void onPostExecute(String s) {
0 super.onPostExecute(s);
11 loading.dismiss();
1 Toast.makeText(ViewEmployee.this,s,Toast.LENGTH_LONG).show();
11 }
2
11 @Override
3 protected String doInBackground(Void... params) {
11 HashMap<String,String> hashMap = new HashMap<>();
4 hashMap.put(Config.KEY_EMP_ID,id);
11 hashMap.put(Config.KEY_EMP_NAME,name);
5 hashMap.put(Config.KEY_EMP_DESG,desg);
11 hashMap.put(Config.KEY_EMP_SAL,salary);
6
11 RequestHandler rh = new RequestHandler();
7
11 String s = rh.sendPostRequest(Config.URL_UPDATE_EMP,hashMap);
8
11 return s;
9 }
12 }
0
12 UpdateEmployee ue = new UpdateEmployee();
1 ue.execute();
12 }
2
12 private void deleteEmployee(){
3 class DeleteEmployee extends AsyncTask<Void,Void,String> {
12 ProgressDialog loading;
4
12 @Override
5 protected void onPreExecute() {
12 super.onPreExecute();
6 loading = ProgressDialog.show(ViewEmployee.this, "Updating...", "Wait...", false, false);
12 }
7
12 @Override
8 protected void onPostExecute(String s) {
12 super.onPostExecute(s);
9 loading.dismiss();
13 Toast.makeText(ViewEmployee.this, s, Toast.LENGTH_LONG).show();
0 }
13
1 @Override
13 protected String doInBackground(Void... params) {
2 RequestHandler rh = new RequestHandler();
13 String s = rh.sendGetRequestParam(Config.URL_DELETE_EMP, id);
3 return s;
13 }
4 }
13
5 DeleteEmployee de = new DeleteEmployee();
13 de.execute();
6 }
13
7 private void confirmDeleteEmployee(){
13 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
8 alertDialogBuilder.setMessage("Are you sure you want to delete this employee?");
13
9 alertDialogBuilder.setPositiveButton("Yes",
14 new DialogInterface.OnClickListener() {
0 @Override
14 public void onClick(DialogInterface arg0, int arg1) {
1 deleteEmployee();
14 startActivity(new Intent(ViewEmployee.this,ViewAllEmployee.class));
2 }
14 });
3
14 alertDialogBuilder.setNegativeButton("No",
4 new DialogInterface.OnClickListener() {
14 @Override
5 public void onClick(DialogInterface arg0, int arg1) {
14
6 }
14 });
7
14 AlertDialog alertDialog = alertDialogBuilder.create();
8 alertDialog.show();
14 }
9
15 @Override
0 public void onClick(View v) {
15 if(v == buttonUpdate){
1 updateEmployee();
15 }
2
15 if(v == buttonDelete){
3 confirmDeleteEmployee();
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
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.

You might also like