Android PHP Delete From MySQL DB Using Volley

By | December 14, 2014

In the previous tutorial we have seen how to update data into MySQL database from android application using php , Here in this tutorial we will see how to delete data from MySQL database using php from android application .


Demo Video

Pre-Requisites 

Firstly you have to set up php server.
Read : Setting PHP And MYSQL Server

After Inserting Data into MySQL database table myorder ( http://www.tutorialsbuzz.com/2014/12/android-php-insert-mysql-db-volley.html )

PHP Script

1 a. DBConfig

file: db_config.php

<?php
$mysql_hostname = “localhost”;
$mysql_user = “root”;
$mysql_password = “”;
$mysql_database = “orders”;

$db = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die(“Opps some thing went wrong”);
mysql_select_db($mysql_database, $db) or die(“Opps some thing went wrong”);

?>

1 b. Delete Script

Php Script to delete data from MySQL database.

file : delete_item.php

<?php
 error_reporting(0);
 include(“db_config.php”);

// array for JSON response
$response = array();
if( isset($_GET[‘id’] ) ) {

    $id=$_GET[‘id’];
    $item=$_GET[‘item’];
  
    $result = mysql_query(“delete from myorder where id=’$id’ “);
  
    $row_count = mysql_affected_rows();

    if($row_count>0){
        $response[“success”] = 1;
        $response[“message”] = “Deleted Sucessfully.”;
       }
    else{
        $response[“success”] = 0;
        $response[“message”] = “Failed To Delete”;
     }
  // echoing JSON response
  echo json_encode($response);

 }
?>

1 c. API URL Call

URL   http://api.tutorialsbuzz.com/Orders/delete_item.php?id=xx  
Request Type    GET
JSON Output On Success

{“success”:1,”message”:”Deleted Successfully.”}

 On Failure

{“success”:0,”message”:”Failed To Delete”}

Android

2 a. Add Network Permission

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

2 b. Build Project With Volley Library

Add the following lines to the dependencies section in your project’s app:module build.grade file and sync . The Highlighted line syncs Volley library .

build.gradle

dependencies {
    compile fileTree(dir: ‘libs’, include: [‘*.jar’])
    testCompile ‘junit:junit:4.12’
    compile ‘com.android.support:appcompat-v7:23.1.0’
    compile ‘com.android.support:design:23.1.0’
    compile ‘com.mcxiaoke.volley:library:1.0.19’

}

2 c. Layout

Create XML Layout

file:update_delete.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout
    xmlns:android=”http://schemas.android.com/apk/res/android”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent” >

    <EditText
        android:id=”@+id/modify_item_et”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_alignParentTop=”true”
        android:layout_centerHorizontal=”true”
        android:layout_marginTop=”48dp”
        android:ems=”10″
        android:inputType=”textPersonName” >

        <requestFocus />
    </EditText>

    <Button
        android:id=”@+id/button1″
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_alignLeft=”@+id/modify_item_et”
        android:layout_below=”@+id/modify_item_et”
        android:layout_marginTop=”48dp”
        android:onClick=”update”
        android:text=”Update” />

    <Button
        android:id=”@+id/button2″
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_alignBaseline=”@+id/button1″
        android:layout_alignBottom=”@+id/button1″
        android:layout_alignRight=”@+id/modify_item_et”
        android:onClick=”delete”
        android:text=”Delete” />

</RelativeLayout>

2 d. Application Object

Create a class MyApplication which extends Application ,this application object represents singleton pattern , the purpose of this class is make volley request available  through out of the application

  • The getInstance method of application class returns application object.
  • The getReqQueue method returns the RequestQueue object.
  • Inside addToReqQueue method we are adding calling add() method upon RequestObject and passing request as paramter to it .
  • The cancelPendingReq is used for cancelling the request.

file : MyApplication.java

package com.pavan.androidphp;

import android.app.Application;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MyApplication extends Application {

    private RequestQueue mRequestQueue;
    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    public RequestQueue getReqQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToReqQueue(Request<T> req, String tag) {

        getReqQueue().add(req);
    }

    public <T> void addToReqQueue(Request<T> req) {

        getReqQueue().add(req);
    }

    public void cancelPendingReq(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

2 e. Activity

Create a class UpdateDeleteData and extend this class to Activity class and set the content of this activity with above defined XML Layout  onclick of delete button construct api url with parameter id and  make json object request to delete data from MySQL database .

file : UpdateDeleteData.java

package com.pavan.androidphp;

import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

public class UpdateDeleteData extends Activity {

    EditText item_name_et;
    String id, item_name;

    ProgressDialog PD;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_delete);

        PD = new ProgressDialog(this);
        PD.setMessage(“please wait…..”);
        PD.setCancelable(false);

        item_name_et = (EditText) findViewById(R.id.modify_item_et);
        Intent i = getIntent();

        HashMap<String, String> item = (HashMap<String, String>) i
                .getSerializableExtra(“item”);

        id = item.get(ReadData.ITEM_ID);
        item_name = item.get(ReadData.ITEM_NAME);

        item_name_et.setText(item_name);

    }

    public void update(View view) {
       //perform update
    }

    public void delete(View view) {
        PD.show();
        String delete_url = “http://api.tutorialsbuzz.com/Orders/delete_item.php?id=”
                + id;

        JsonObjectRequest delete_request = new JsonObjectRequest(delete_url,
                null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            int success = response.getInt(“success”);

                            if (success == 1) {
                                PD.dismiss();
                                Toast.makeText(getApplicationContext(),
                                        “Deleted Successfully”,
                                        Toast.LENGTH_SHORT).show();
                                // redirect to readdata
                                MoveToReadData();
                            } else {
                                PD.dismiss();
                                Toast.makeText(getApplicationContext(),
                                        “failed to delete”, Toast.LENGTH_SHORT)
                                        .show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        // Adding request to request queue
        MyApplication.getInstance().addToReqQueue(delete_request);

    }

    private void MoveToReadData() {
        Intent read_intent = new Intent(UpdateDeleteData.this, ReadData.class)
                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        startActivity(read_intent);

    }
}

Before Delete

During Delete

After Delete


What Next

Also Check Out The Continued Tutorials On Android PHP MYSQL .

Android PHP CRUD

Android PHP Insert
Android PHP Read
Android PHP Update

  • it is saying nullpointer exception at .addrequestqueue plsss help me