Google Sheet As DATABASE for your Android Application Part – 3 | [CRUD] Create, Read, Update, Delete operation on Google Sheets from Android App

Previously I have posted about Insert and Fetching data from Google Sheet to Android app. So here I am covering complete CRUD operation in a single App so that it can be helpful for those who need it completely.

I recommend using this code to everyone instead of Part-1 and Part -2,

 

Here It consists of 2 Parts,

  1. Google App Script Part (Back End)
  2. Android Part (Front End)

Source Code

 

1.Google App Script Part

Step 1 : Create new app script project. Click here to create App Script.

Step 2 : Copy and paste the below script which handles two attributes (id,name). You can change the logic, attributes as required.

 

function doGet(e) {

    var op = e.parameter.action;

    var ss = SpreadsheetApp.openByUrl("Your Spread Sheet URL");
    var sheet = ss.getSheetByName("Sheet1");



    if (op == "insert")
        return insert_value(e, sheet);

    //Make sure you are sending proper parameters 
    if (op == "read")
        return read_value(e, sheet);

    if (op == "update")
        return update_value(e, sheet);

    if (op == "delete")
        return delete_value(e, sheet);

    if (op == "readAll")
        return read_all_value(e, ss);

}

//Recieve parameter and pass it to function to handle




function insert_value(request, sheet) {


    var id = request.parameter.id;
    var country = request.parameter.name;

    var flag = 1;
    var lr = sheet.getLastRow();
    for (var i = 1; i <= lr; i++) {
        var id1 = sheet.getRange(i, 2).getValue();
        if (id1 == id) {
            flag = 0;
            var result = "Id already exist..";
        }
    }
    //add new row with recieved parameter from client
    if (flag == 1) {
        var d = new Date();
        var currentTime = d.toLocaleString();
        var rowData = sheet.appendRow([currentTime, id, country]);


        var result = "Insertion successful";
    }
    result = JSON.stringify({

        "result": result

    });

    return ContentService
        .createTextOutput(result)
        .setMimeType(ContentService.MimeType.JAVASCRIPT);
}




function read_all_value(request, ss) {


    var output = ContentService.createTextOutput(),
        data = {};
    //Note : here sheet is sheet name , don't get confuse with other operation 
    var sheet = "sheet1";

    data.records = readData_(ss, sheet);

    var callback = request.parameters.callback;

    if (callback === undefined) {
        output.setContent(JSON.stringify(data));
    } else {
        output.setContent(callback + "(" + JSON.stringify(data) + ")");
    }
    output.setMimeType(ContentService.MimeType.JAVASCRIPT);

    return output;
}


function readData_(ss, sheetname, properties) {

    if (typeof properties == "undefined") {
        properties = getHeaderRow_(ss, sheetname);
        properties = properties.map(function(p) {
            return p.replace(/\s+/g, '_');
        });
    }

    var rows = getDataRows_(ss, sheetname),
        data = [];

    for (var r = 0, l = rows.length; r < l; r++) {
        var row = rows[r],
            record = {};

        for (var p in properties) {
            record[properties[p]] = row[p];
        }

        data.push(record);

    }
    return data;
}



function getDataRows_(ss, sheetname) {
    var sh = ss.getSheetByName(sheetname);

    return sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
}


function getHeaderRow_(ss, sheetname) {
    var sh = ss.getSheetByName(sheetname);

    return sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
}


//update function

function update_value(request, sheet) {

    var output = ContentService.createTextOutput();
    var id = request.parameter.id;
    var flag = 0;
    var country = request.parameter.name;
    var lr = sheet.getLastRow();
    for (var i = 1; i <= lr; i++) {
        var rid = sheet.getRange(i, 2).getValue();
        if (rid == id) {
            sheet.getRange(i, 3).setValue(country);
            var result = "value updated successfully";
            flag = 1;
        }
    }
    if (flag == 0)
        var result = "id not found";

    result = JSON.stringify({
        "result": result
    });

    return ContentService
        .createTextOutput(result)
        .setMimeType(ContentService.MimeType.JAVASCRIPT);


}




function delete_value(request, sheet) {

    var output = ContentService.createTextOutput();
    var id = request.parameter.id;
    var country = request.parameter.name;
    var flag = 0;



    var lr = sheet.getLastRow();
    for (var i = 1; i <= lr; i++) {
        var rid = sheet.getRange(i, 2).getValue();
        if (rid == id) {
            sheet.deleteRow(i);
            var result = "value deleted successfully";
            flag = 1;
        }

    }

    if (flag == 0)
        var result = "id not found";



    result = JSON.stringify({
        "result": result
    });

    return ContentService
        .createTextOutput(result)
        .setMimeType(ContentService.MimeType.JAVASCRIPT);

}


function read_value(request, sheet) {

    var id = request.parameter.id;
    var name;
    var record = {};
    //var place = request.parameter.place;

    var flag = 1;
    var lr = sheet.getLastRow();
    for (var i = 1; i <= lr; i++) {
        var id1 = sheet.getRange(i, 2).getValue();
        if (id1 == id) {
            flag = 0;

            name = sheet.getRange(i, 3).getValue();



            var result = JSON.stringify({
                "user": {
                    "id": id,
                    "name": name
                }

            });


        }

    }
    return ContentService
        .createTextOutput(result)
        .setMimeType(ContentService.MimeType.JAVASCRIPT);


}

Step 3: Change the url of the spread sheet. Make sure sheet is shared .[anyone with the link can view]

Step 4: Go to Publish -> Deploy as web app. A window pop up, here ->Who has access to the app: ->  Anyone, even Anonymous

Publish/Update. Copy the published URL and store it.

 

 

2. Android Part

Step 1: Create new Android App from Android Studio

Step 2: Go to build.gradle[module: app] and add following dependencies.

note: If you are downloading the source code and modifying. Please make sure build tool version and compileSdk Version in build.gradle[module: dependancyapp] are compatible with your phone. If you are developing from the scratch then no issues, just dependency,

dependencies {
.....................
..................... 
   compile 'com.squareup.okhttp:okhttp:2.4.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
}

Step 3: Let’s add all layout files.

 

  1. activity_main.xml  This holds the button of CRUD operation.
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="androidlabs.crud.MainActivity">
    
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Create / Insert"
            android:id="@+id/insert_btn"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete"
            android:id="@+id/delete_btn"
            android:layout_below="@+id/read_all_btn"
            android:layout_alignLeft="@+id/read_all_btn"
            android:layout_alignStart="@+id/read_all_btn"
            android:layout_alignRight="@+id/read_all_btn"
            android:layout_alignEnd="@+id/read_all_btn" />
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Read"
            android:id="@+id/read_btn"
            android:layout_below="@+id/insert_btn"
            android:layout_alignLeft="@+id/insert_btn"
            android:layout_alignStart="@+id/insert_btn"
            android:layout_alignRight="@+id/insert_btn"
            android:layout_alignEnd="@+id/insert_btn" />
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Read All"
            android:id="@+id/read_all_btn"
            android:layout_below="@+id/update_btn"
            android:layout_alignLeft="@+id/update_btn"
            android:layout_alignStart="@+id/update_btn"
            android:layout_alignRight="@+id/update_btn"
            android:layout_alignEnd="@+id/update_btn" />
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="update"
            android:id="@+id/update_btn"
            android:layout_below="@+id/read_btn"
            android:layout_alignLeft="@+id/read_btn"
            android:layout_alignStart="@+id/read_btn"
            android:layout_alignRight="@+id/read_btn"
            android:layout_alignEnd="@+id/read_btn" />
    
    
    </RelativeLayout>
    

     

  2. insert_data.xml  This Contains the View of 2 Text fields and Insert Button
    <?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:layout_width="match_parent"
            android:layout_height="40dp"
            android:id="@+id/uid"
            android:hint="User Id"
            android:layout_marginTop="54dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
    
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Insert"
            android:id="@+id/insert_btn"
            android:layout_marginTop="45dp"
            android:layout_below="@+id/name"
            android:layout_centerHorizontal="true" />
    
        <EditText
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:id="@+id/name"
            android:hint="Name"
            android:layout_below="@+id/uid"
            android:layout_centerHorizontal="true" />
    </RelativeLayout>

     

  3. read_data.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:layout_width="match_parent"
            android:layout_height="40dp"
            android:id="@+id/uid"
            android:hint="User ID"
            android:layout_marginTop="54dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
    
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Find"
            android:id="@+id/insert_btn"
            android:layout_marginTop="45dp"
            android:layout_centerHorizontal="true"
            android:layout_below="@+id/uid" />
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/id_v"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/insert_btn"
            android:layout_toEndOf="@+id/insert_btn" />
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/id_l"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@+id/insert_btn"
            android:layout_toStartOf="@+id/insert_btn" />
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/name_l"
            android:layout_marginTop="31dp"
            android:layout_below="@+id/id_l"
            android:layout_alignLeft="@+id/id_l"
            android:layout_alignStart="@+id/id_l" />
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/name_v"
            android:layout_alignTop="@+id/name_l"
            android:layout_alignLeft="@+id/id_v"
            android:layout_alignStart="@+id/id_v" />
    
    </RelativeLayout>

     

  4. update_data.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:layout_width="match_parent"
            android:layout_height="40dp"
            android:id="@+id/uid"
            android:hint="User ID"
            android:layout_marginTop="54dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
    
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Update"
            android:id="@+id/update_btn1"
            android:layout_marginTop="45dp"
            android:layout_below="@+id/name"
            android:layout_centerHorizontal="true" />
    
        <EditText
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:id="@+id/name"
            android:hint="Name"
            android:layout_below="@+id/uid"
            android:layout_centerHorizontal="true" />
    </RelativeLayout>

     

  5. delete_data,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:layout_width="match_parent"
            android:layout_height="40dp"
            android:id="@+id/uid"
            android:hint="User ID"
            android:layout_marginTop="54dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
    
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete"
            android:id="@+id/delete_btn"
            android:layout_marginTop="45dp"
            android:layout_centerHorizontal="true"
            android:layout_below="@+id/uid" />
    
    
    </RelativeLayout>

     

  6. read_all.xml
    <?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"
        android:weightSum="1">
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Read All"
            android:id="@+id/readAll_btn1"
            android:layout_gravity="center_horizontal" />
    
        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/listView"
            android:layout_gravity="center_horizontal" />
    </LinearLayout>

     

  7. layout_row_view.xml
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        xmlns:fresco="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_centerVertical="true"
            android:layout_height="wrap_content"
            >
            <TextView
                android:id="@+id/textViewId"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:textAppearance="?android:textAppearanceLarge"
                tools:text="TextView" />
    
            <TextView
                android:id="@+id/textViewName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:textAppearance="?android:textAppearanceMedium"
                tools:text="TextView" />
    
        </LinearLayout>
    </RelativeLayout>

     

Step 4 : Now Let’s Add Java Class Files Which handles and Controles the operation.

 

1 Controller.java

package androidlabs.crud;

import android.support.annotation.NonNull;
import android.util.Log;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;


public class Controller {



    public static final String TAG = "TAG";

    public static final String WAURL="Your Script Web APP URL";
// EG : https://script.google.com/macros/s/AKfycbwXXXXXXXXXXXXXXXXX/exec?
//Make Sure '?' Mark is present at the end of URL
    private static Response response;

    public static JSONObject readAllData() {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(WAURL+"action=readAll")
                    .build();
            response = client.newCall(request).execute();
            return new JSONObject(response.body().string());
        } catch (@NonNull IOException | JSONException e) {
            Log.e(TAG, "" + e.getLocalizedMessage());
        }
        return null;
    }


    public static JSONObject insertData(String id, String name) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(WAURL+"action=insert&id="+id+"&name="+name)
                    .build();
            response = client.newCall(request).execute();
        //    Log.e(TAG,"response from gs"+response.body().string());
            return new JSONObject(response.body().string());


        } catch (@NonNull IOException | JSONException e) {
            Log.e(TAG, "recieving null " + e.getLocalizedMessage());
        }
        return null;
    }

    public static JSONObject updateData(String id, String name) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(WAURL+"action=update&id="+id+"&name="+name)
                    .build();
            response = client.newCall(request).execute();
            //    Log.e(TAG,"response from gs"+response.body().string());
            return new JSONObject(response.body().string());


        } catch (@NonNull IOException | JSONException e) {
            Log.e(TAG, "recieving null " + e.getLocalizedMessage());
        }
        return null;
    }

    public static JSONObject readData(String id) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(WAURL+"action=read&id="+id)
                    .build();
            response = client.newCall(request).execute();
               // Log.e(TAG,"response from gs"+response.body().string());
            return new JSONObject(response.body().string());


        } catch (@NonNull IOException | JSONException e) {
            Log.e(TAG, "recieving null " + e.getLocalizedMessage());
        }
        return null;
    }

    public static JSONObject deleteData(String id) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(WAURL+"action=delete&id="+id)
                    .build();
            response = client.newCall(request).execute();
            // Log.e(TAG,"response from gs"+response.body().string());
            return new JSONObject(response.body().string());


        } catch (@NonNull IOException | JSONException e) {
            Log.e(TAG, "recieving null " + e.getLocalizedMessage());
        }
        return null;
    }


}

2. InsertData.java

 

package androidlabs.crud;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by ADJ on 5/14/2017.
 */
public class InsertData extends AppCompatActivity {

 private Button insert;
 String id;
 String name;
 private EditText uid1ET, uid2, nameET;


 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.insert_data);
  insert = (Button) findViewById(R.id.insert_btn);
  uid1ET = (EditText) findViewById(R.id.uid);
  nameET = (EditText) findViewById(R.id.name);

  insert.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {

    id = uid1ET.getText().toString();
    name = nameET.getText().toString();
    new InsertDataActivity().execute();
   }
  });
 }



 class InsertDataActivity extends AsyncTask < Void, Void, Void > {

  ProgressDialog dialog;
  int jIndex;
  int x;

  String result = null;


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

   dialog = new ProgressDialog(InsertData.this);
   dialog.setTitle("Hey Wait Please...");
   dialog.setMessage("Inserting your values..");
   dialog.show();

  }

  @Nullable
  @Override
  protected Void doInBackground(Void...params) {
   JSONObject jsonObject = Controller.insertData(id, name);
   Log.i(Controller.TAG, "Json obj ");

   try {
    /**
     * Check Whether Its NULL???
     */
    if (jsonObject != null) {

     result = jsonObject.getString("result");

    }
   } catch (JSONException je) {
    Log.i(Controller.TAG, "" + je.getLocalizedMessage());
   }
   return null;
  }
  @Override
  protected void onPostExecute(Void aVoid) {
   super.onPostExecute(aVoid);
   dialog.dismiss();
   Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
  }
 }
}

3. ReadSingleData.java

package androidlabs.crud;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by ADJ on 5/14/2017.
 */
public class ReadSingleData extends AppCompatActivity {

 private Button read;
 String id;
 String name;
 private EditText uid1ET;
 private TextView id_l, name_l, id_v, name_v;


 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.read_data);
  read = (Button) findViewById(R.id.insert_btn);
  uid1ET = (EditText) findViewById(R.id.uid);

  id_l = (TextView) findViewById(R.id.id_l);
  name_l = (TextView) findViewById(R.id.name_l);
  id_v = (TextView) findViewById(R.id.id_v);
  name_v = (TextView) findViewById(R.id.name_v);


  read.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {

    id = uid1ET.getText().toString();

    new ReadDataActivity().execute();
   }
  });
 }


 class ReadDataActivity extends AsyncTask < Void, Void, Void > {

  ProgressDialog dialog;
  int jIndex;
  int x;


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

   dialog = new ProgressDialog(ReadSingleData.this);
   dialog.setTitle("Hey Wait Please...");
   dialog.setMessage("Fetching your values");
   dialog.show();

  }

  @Nullable
  @Override
  protected Void doInBackground(Void...params) {
   Log.i(Controller.TAG, "IDVALUE" + id);
   JSONObject jsonObject = Controller.readData(id);
   Log.i(Controller.TAG, "Json obj " + jsonObject);

   try {
    /**
     * Check Whether Its NULL???
     */
    if (jsonObject != null) {

     JSONObject user = jsonObject.getJSONObject("user");
     name = user.getString("name");

    }
   } catch (JSONException je) {
    Log.i(Controller.TAG, "" + je.getLocalizedMessage());
   }
   return null;
  }

  @Override
  protected void onPostExecute(Void aVoid) {
   super.onPostExecute(aVoid);
   dialog.dismiss();
   if (name != null) {
    id_l.setText("ID");
    name_l.setText("NAME");
    id_v.setText(id);
    name_v.setText(name);

   } else
    Toast.makeText(getApplicationContext(), "ID not found", Toast.LENGTH_LONG).show();
  }
 }
}

4. UpdateData.java

package androidlabs.crud;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by ADJ on 5/14/2017.
 */
public class UpdateData extends AppCompatActivity{

    private Button update;
    String id;
    String name;
    private EditText uid1ET,uid2,nameET;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_data);
        update=(Button)findViewById(R.id.update_btn1);
        uid1ET=(EditText)findViewById(R.id.uid);
        nameET=(EditText)findViewById(R.id.name);

        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                 id=uid1ET.getText().toString();
                 name=nameET.getText().toString();
                new UpdateDataActivity().execute();
            }
        });
    }



    class UpdateDataActivity extends AsyncTask<Void, Void, Void> {

        ProgressDialog dialog;
        int jIndex;
        int x;

        String result=null;


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

            dialog = new ProgressDialog(UpdateData.this);
            dialog.setTitle("Hey Wait Please..."+x);
            dialog.setMessage("I am getting your JSON");
            dialog.show();

        }

        @Nullable
        @Override
        protected Void doInBackground(Void... params) {
            JSONObject jsonObject = Controller.updateData(id,name);
            Log.i(Controller.TAG, "Json obj ");

            try {
                /**
                 * Check Whether Its NULL???
                 */
                if (jsonObject != null) {

                     result=jsonObject.getString("result");

                }
            } catch (JSONException je) {
                Log.i(Controller.TAG, "" + je.getLocalizedMessage());
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.dismiss();
           Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
        }
    }
}

5. DeleteData.java

package androidlabs.crud;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by ADJ on 5/14/2017.
 */
public class DeleteData extends AppCompatActivity{

    private Button delete;
    String id;
    String name;
    private EditText uid1ET;



    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.delete_data);
        delete=(Button)findViewById(R.id.delete_btn);
        uid1ET=(EditText)findViewById(R.id.uid);



        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                id=uid1ET.getText().toString();

                new DeleteDataActivity().execute();
            }
        });
    }



    class DeleteDataActivity extends AsyncTask<Void, Void, Void> {

        ProgressDialog dialog;
        int jIndex;
        int x;
        String result=null;



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

            dialog = new ProgressDialog(DeleteData.this);
            dialog.setTitle("Hey Wait Please...");
            dialog.setMessage("Deleting... ");
            dialog.show();

        }

        @Nullable
        @Override
        protected Void doInBackground(Void... params) {
           Log.i(Controller.TAG,"IDVALUE"+id);
            JSONObject jsonObject = Controller.deleteData(id);
            Log.i(Controller.TAG, "Json obj "+jsonObject);

            try {
                /**
                 * Check Whether Its NULL???
                 */
                if (jsonObject != null) {

                    result=jsonObject.getString("result");


                }
            } catch (JSONException je) {
                Log.i(Controller.TAG, "" + je.getLocalizedMessage());
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.dismiss();
            Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();

        }
    }
}

Step 4: To View All the data I am using Array Adapter and list

1 MyArrayAdapter.java

package androidlabs.crud;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

public class MyArrayAdapter extends ArrayAdapter < MyDataModel > {

 List < MyDataModel > modelList;
 Context context;
 private LayoutInflater mInflater;

 // Constructors
 public MyArrayAdapter(Context context, List < MyDataModel > objects) {
  super(context, 0, objects);
  this.context = context;
  this.mInflater = LayoutInflater.from(context);
  modelList = objects;
 }

 @Override
 public MyDataModel getItem(int position) {
  return modelList.get(position);
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  final ViewHolder vh;
  if (convertView == null) {
   View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
   vh = ViewHolder.create((RelativeLayout) view);
   view.setTag(vh);
  } else {
   vh = (ViewHolder) convertView.getTag();
  }

  MyDataModel item = getItem(position);

  vh.textViewId.setText(item.getId());
  vh.textViewName.setText(item.getName());


  return vh.rootView;
 }



 private static class ViewHolder {
  public final RelativeLayout rootView;

  public final TextView textViewId;
  public final TextView textViewName;


  private ViewHolder(RelativeLayout rootView, TextView textViewName, TextView textViewId) {
   this.rootView = rootView;
   this.textViewId = textViewId;
   this.textViewName = textViewName;

  }

  public static ViewHolder create(RelativeLayout rootView) {
   TextView textViewId = (TextView) rootView.findViewById(R.id.textViewId);
   TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);

   return new ViewHolder(rootView, textViewName, textViewId);
  }
 }
}

2.MyDataModel.java

package androidlabs.crud;



public class MyDataModel {

    private String name;

    private String id;



    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setCountry(String id) {
        this.id=id;
    }



}

3.ReadAllData.java

package androidlabs.crud;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by ADJ on 5/17/2017.
 */
public class ReadAllData extends AppCompatActivity {

 private ListView listView;
 private ArrayList < MyDataModel > list;
 private MyArrayAdapter adapter;
 private Button readAll;


 @Override

 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.read_all);

  readAll = (Button) findViewById(R.id.readAll_btn1);
  list = new ArrayList < > ();
  adapter = new MyArrayAdapter(this, list);
  listView = (ListView) findViewById(R.id.listView);
  listView.setAdapter(adapter);

  readAll.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    new ReadData1().execute();
   }
  });



 }


 class ReadData1 extends AsyncTask < Void, Void, Void > {

  ProgressDialog dialog;
  int jIndex;
  int x;

  @Override
  protected void onPreExecute() {
   super.onPreExecute();
   /**
    * Progress Dialog for User Interaction
    */

   x = list.size();

   if (x == 0)
    jIndex = 0;
   else
    jIndex = x;

   dialog = new ProgressDialog(ReadAllData.this);
   dialog.setTitle("Hey Wait Please..." + x);
   dialog.setMessage("Fetching all the Values");
   dialog.show();
  }

  @Nullable
  @Override
  protected Void doInBackground(Void...params) {
   JSONObject jsonObject = Controller.readAllData();
   try {
    /**
     * Check Whether Its NULL???
     */
    if (jsonObject != null) {
     /**
      * Check Length...
      */
     if (jsonObject.length() > 0) {
      /**
       * Getting Array named "records" From MAIN Json Object
       */
      JSONArray array = jsonObject.getJSONArray("records");

      /**
       * Check Length of Array...
       */


      int lenArray = array.length();
      if (lenArray > 0) {
       for (; jIndex < lenArray; jIndex++) {

        /**
         * Creating Every time New Object
         * and
         * Adding into List
         */
        MyDataModel model = new MyDataModel();

        /**
         * Getting Inner Object from contacts array...
         * and
         * From that We will get Name of that Contact
         *
         */
        JSONObject innerObject = array.getJSONObject(jIndex);

        String id = innerObject.getString("ID");
        String name = innerObject.getString("NAME");
        //  String image = innerObject.getString(Keys.KEY_IMAGE);
        /**
         * Getting Object from Object "phone"
         */
        //JSONObject phoneObject = innerObject.getJSONObject(Keys.KEY_PHONE);
        //String phone = phoneObject.getString(Keys.KEY_MOBILE);

        model.setName(name);
        model.setCountry(id);
        //                              model.setImage(image);

        /**
         * Adding name and phone concatenation in List...
         */
        list.add(model);
       }
      }
     }
    } else {

    }
   } catch (JSONException je) {
    Log.i(Controller.TAG, "" + je.getLocalizedMessage());
   }
   return null;
  }

  @Override
  protected void onPostExecute(Void aVoid) {
   super.onPostExecute(aVoid);
   dialog.dismiss();
   /**
    * Checking if List size if more than zero then
    * Update ListView
    */
   if (list.size() > 0) {
    adapter.notifyDataSetChanged();
   } else {
    Toast.makeText(getApplicationContext(), "No data found", Toast.LENGTH_LONG).show();
   }
  }
 }
}

Step 5 : Add MainActivity.java

package androidlabs.crud;

//MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;







public class MainActivity extends AppCompatActivity {


 private Button read, readAll, insert, delete, update;




 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);




  read = (Button) findViewById(R.id.read_btn);
  readAll = (Button) findViewById(R.id.read_all_btn);
  insert = (Button) findViewById(R.id.insert_btn);
  update = (Button) findViewById(R.id.update_btn);
  delete = (Button) findViewById(R.id.delete_btn);




  readAll.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {

    if (InternetConnection.checkConnection(getApplicationContext())) {
     Intent intent = new Intent(getApplicationContext(), ReadAllData.class);
     startActivity(intent);

    } else {
     Toast.makeText(getApplicationContext(), "Check your internet connection", Toast.LENGTH_LONG).show();
    }





   }
  });


  insert.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {

    if (InternetConnection.checkConnection(getApplicationContext())) {
     Intent intent = new Intent(getApplicationContext(), InsertData.class);
     startActivity(intent);


    } else {
     Toast.makeText(getApplicationContext(), "Check your internet connection", Toast.LENGTH_LONG).show();
    }





   }
  });


  update.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {


    if (InternetConnection.checkConnection(getApplicationContext())) {
     Intent intent = new Intent(getApplicationContext(), UpdateData.class);
     startActivity(intent);


    } else {
     Toast.makeText(getApplicationContext(), "Check your internet connection", Toast.LENGTH_LONG).show();
    }




   }
  });


  read.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {

    if (InternetConnection.checkConnection(getApplicationContext())) {
     Intent intent = new Intent(getApplicationContext(), ReadSingleData.class);
     startActivity(intent);


    } else {
     Toast.makeText(getApplicationContext(), "Check your internet connection", Toast.LENGTH_LONG).show();
    }




   }
  });

  delete.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {

    if (InternetConnection.checkConnection(getApplicationContext())) {
     Intent intent = new Intent(getApplicationContext(), DeleteData.class);
     startActivity(intent);


    } else {
     Toast.makeText(getApplicationContext(), "Check your internet connection", Toast.LENGTH_LONG).show();
    }



   }
  });




 }

}

Step 6 : Change Manifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="androidlabs.crud">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".InsertData"/>
        <activity android:name=".UpdateData"/>
       <activity android:name=".ReadSingleData"/>
       <activity android:name=".DeleteData"/>
        <activity android:name=".ReadAllData"/>
    </application>

</manifest>

 

Now Run The Code

 

Source Code