Professional Documents
Culture Documents
Android Mysql Tutorial To Perform Basic Crud Operation
Android Mysql Tutorial To Perform Basic Crud Operation
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)
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.
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.
The array_push() function inserts one or more elements to the end of an array.