• No results found

Android MySQL Tutorial to Perform Basic CRUD Operation

N/A
N/A
Protected

Academic year: 2021

Share "Android MySQL Tutorial to Perform Basic CRUD Operation"

Copied!
24
0
0

Loading.... (view fulltext now)

Full text

(1)

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)

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

(3)

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 2 3

<?php

(4)

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

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

(5)

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

(6)

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 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 that will be used to send the request to php scripts public static final String KEY_EMP_ID = "id";

public static final String KEY_EMP_NAME = "name"; public static final String KEY_EMP_DESG = "desg"; public static final String KEY_EMP_SAL = "salary"; //JSON Tags

(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 static final String TAG_ID = "id";

public static final String TAG_NAME = "name"; public static final String TAG_DESG = "desg"; public static final String 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 java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import 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();

(8)

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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 //Initializing Url

url = new URL(requestURL); //Creating an httmlurl connection

HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //Configuring connection properties

conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true);

conn.setDoOutput(true); //Creating an output stream

OutputStream os = conn.getOutputStream();

//Writing parameters to the request

//We are using a method getPostDataString which is defined below BufferedWriter writer = new BufferedWriter(

new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush();

writer.close(); os.close();

int responseCode = conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {

BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

sb = new StringBuilder(); String response;

//Reading server response

while ((response = br.readLine()) != null){ sb.append(response); } } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); }

public String sendGetRequest(String requestURL){ StringBuilder sb =new StringBuilder();

try {

URL url = new URL(requestURL);

HttpURLConnection con = (HttpURLConnection) url.openConnection(); BufferedReader bufferedReader = new BufferedReader(new

InputStreamReader(con.getInputStream())); String s; while((s=bufferedReader.readLine())!=null){ sb.append(s+"\n"); } }catch(Exception e){ } return sb.toString(); }

(9)

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 8 11 9 12 0 12 1 12 2 12 3 12 4 12 5 12 6

public String sendGetRequestParam(String requestURL, String id){ StringBuilder sb =new StringBuilder();

try {

URL url = new URL(requestURL+id);

HttpURLConnection con = (HttpURLConnection) url.openConnection(); BufferedReader bufferedReader = new BufferedReader(new

InputStreamReader(con.getInputStream())); String s; while((s=bufferedReader.readLine())!=null){ sb.append(s+"\n"); } }catch(Exception e){ } return sb.toString(); }

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {

StringBuilder result = new StringBuilder(); boolean first = true;

for (Map.Entry<String, String> entry : params.entrySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } }

(10)

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 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 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" 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="Employee Name" /> <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="Designation" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editTextDesg" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Salary" />

(11)

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 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 <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editTextSalary" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Add Employee" android:id="@+id/buttonAdd" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="View Employee" android:id="@+id/buttonView" /> </LinearLayout>

(12)

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 android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import 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); }

(13)

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

(14)

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

(15)

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 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="net.simplifiedcoding.mysqlcrud.ViewAllEmployee"> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/listView" /> </LinearLayout>

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.

(16)

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

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 android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import 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);

(17)

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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 }

private void showEmployee(){ JSONObject jsonObject = null;

ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>(); try {

jsonObject = new JSONObject(JSON_STRING);

JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY); for(int i = 0; i<result.length(); i++){

JSONObject jo = result.getJSONObject(i); String id = jo.getString(Config.TAG_ID);

String name = jo.getString(Config.TAG_NAME);

HashMap<String,String> employees = new HashMap<>(); employees.put(Config.TAG_ID,id); employees.put(Config.TAG_NAME,name); list.add(employees); } } catch (JSONException e) { e.printStackTrace(); }

ListAdapter adapter = new SimpleAdapter( ViewAllEmployee.this, list, R.layout.list_item, new String[]{Config.TAG_ID,Config.TAG_NAME}, new int[]{R.id.id, R.id.name});

listView.setAdapter(adapter); }

private void getJSON(){

class GetJSON extends AsyncTask<Void,Void,String>{ ProgressDialog loading;

@Override

protected void onPreExecute() { super.onPreExecute();

loading = ProgressDialog.show(ViewAllEmployee.this,"Fetching Data","Wait...",false,false);

}

@Override

protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); JSON_STRING = s; showEmployee(); } @Override

protected String doInBackground(Void... params) { RequestHandler rh = new RequestHandler();

String s = rh.sendGetRequest(Config.URL_GET_ALL); return s;

} }

(18)

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 android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText;

(19)

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 org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap;

public class ViewEmployee extends AppCompatActivity implements View.OnClickListener { private EditText editTextId;

private EditText editTextName; private EditText editTextDesg; private EditText 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); }

(20)

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

(21)

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

(22)

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

(23)

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

(24)

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 �

References

Related documents