Android PHP Update Into MySQL DB Using Volley

By | December 14, 2014

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

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. Update Script

Php Script to update data into MySQL database.

file : update_item.php

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

  // array for JSON response
  $response = array();

if( isset($_POST[‘id’] ) && isset($_POST[‘item’]) ) {
    $id=$_POST[‘id’];
    $item=$_POST[‘item’];

    $result = mysql_query(“update myorder set item=’$item’ where id=’$id’ “) or die(mysql_error());

    $row_count = mysql_affected_rows();

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

1 c. API URL Call

URL     http://api.tutorialsbuzz.com/Orders/update_item.php   
Request Type    GET
JSON Output On Success

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

 On Failure

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

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:text=”Update”
        android:onClick=”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:text=”Delete”
        android:onClick=”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 : MyApplicaton.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. CustomRequest

file:CustomRequest.java

package com.tutorialsbuzz.androidphp;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject>{

    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomRequest(String url, Map<String, String> params,
                         Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomRequest(int method, String url, Map<String, String> params,
                         Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    @Override
    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected void deliverResponse(JSONObject response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

}

2 f. 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 update button construct api url with parameter id and item and make JSONObjectRequest to update data into 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) {
        PD.show();
        item_name = item_name_et.getText().toString();

        String update_url = “http://api.tutorialsbuzz.com/Orders/update_item.php”;
     
        Map<String, String> params = new HashMap<String, String>();
        params.put(“id“, id);
        params.put(“item“,item_name);

        CustomRequest update_request = new CustomRequest(update_url,
                params, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {

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

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

                            } else {
                                PD.dismiss();
                                Toast.makeText(getApplicationContext(),
                                        “failed to update”, 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(update_request);
    }

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

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

        startActivity(read_intent);

    }
}

Before Update

During Update

After Update

What Next

Also Check Out The Continued Tutorials On Android PHP MYSQL .

Android PHP CRUD

Android PHP Insert
Android PHP Read
Android PHP Delete
  • This code is very helpful but i need data insert and update on database its not work properly.please give hint on that code.

  • @Amruta

    I have Updated the article ,in what next section you can the find link to insert , read ,delete operations

  • Hi Pawan- Thanks for your excellent tutorial. I have downloaded the project. Everything is working fine except update. While updating, Please wait dialog is displayed. No success or failure toast is displayed. What am I
    doing wrong Please help

  • Dear Pawan – Thanks for sharing your project. It helps me to learn Volley. I have one issue, I have used your downloaded code. All the database operation are working perfectly except update method. It is very difficult to debug when using Volley. After entering log statement, I have found that error occurs in the method parseNetworkResponse of class CustomRequest. It is having JSONException. In your site, all the screenshot show update is working properly. But in my case, it is giving error. I did not change anything of your code, what could be the reason.

  • Dear Pawan. Thanks for your reply. I have used your url and inserted one record – Noodles. It is inserted. Then I tried to update from Noodles to Veg Noodles, but it is not updated. Control remains in the same screen and it does not display any error.

    In the site following code is used
    CustomRequest update_request = new CustomRequest(update_url,
    params, new Response.Listener() {

    and in the downloaded code following code is used
    CustomRequest update_request = new CustomRequest(Request.Method.POST, update_url, params, new Response.Listener() {

    I have tried both the codes, none works.

  • @Sudipta

    Thanks for pointing out error there was a mismatch in request parameter name

    It should be
    params.put("item",item_name);
    instead of
    params.put("item_name",item_name);

    I have updated the article

    And Use this url "http://androidphp.16mb.com/Orders/update_item.php&quot;

    Still if you face any issue let me know

  • what is readData on your code