Android PHP Add Edit Delete View Select Using App To MySQL Database Server

How to implement online run time server records update feature with Insert, Show, Update, Delete and select feature to send data from app to MySQL database using PHP.

What we are doing in this project :- In this project we would going to create an android application which would consist the real time app to server record updating feature, Means all the data is send directly through app to MySQL database online server. So here is the complete step by step tutorial for Android PHP Add Edit Delete View Select Using App To MySQL Database.

Features in this project :

  1. Send User Registration data to online MySQL database using PHP.
  2. Show all the students record on screen inside a dynamic custom ListView arrived from server.
  3. Implementing setOnItemClickListener() on ListView to get selected Item from ListView.
  4. Sending the selected item to next activity using intent.
  5. Display the selected Student record on activity directly from server.
  6. Delete the only selected already open record and also delete the record on server.
  7. Edit – Update the selected record online.

Main Features in this application project :-

  1. User Registration.
  2. Show All registered record.
  3. Open selected record.
  4. Delete selected record.
  5. Edit Selected record.

Project File Structure :

List of Activities files in this project :-

  1. MainActivity.java
  2. ShowAllStudentsActivity.java
  3. ShowSingleRecordActivity.java
  4. UpdateActivity.java

List of JAVA files in this project :-

  1. HttpParse.java
  2. HttpServicesClass.java
  3. ListAdapterClass.java
  4. Student.java

List of layout files in this project :-

  1. activity_main.xml
  2. activity_show_all_students.xml
  3. activity_show_single_record.xml
  4. activity_update.xml
  5. listview_item.xml

List of All PHP Files in this project :-

  1. DatabaseConfig.php
  2. AllStudentData.php
  3. StudentRegister.php
  4. FilterStudentData.php
  5. UpdateStudent.php
  6. DeleteStudent.php

Contents in this project Android PHP Add Edit Delete View Select Using App To MySQL Database :

  1. Watch live demo to see how the app works.
  2. Create a database including table on your server.
  3. Create and upload PHP files to perform various operations.
  4. Star a new android application development project.
  5. Add Org.Apache.Http.Legacy library in your project
  6. Add internet permission to your project.
  7. Start Coding.

1. Watch the live demo of this application.

2. Create a database including table on your server :

Create a database on your server and then inside that database create a fresh table named as StudentTable . Inside that table create 4 different columns id, name, phone_number, class like i did in below screenshot .

3. Create and upload PHP files to perform various operations :

There are 6 different type of PHP files present in this project and each file has its own work to do.

  1. DatabaseConfig.php :- This files holds server configuration like server hostname, server password, server username and server database name.
  2. AllStudentData.php :- This files parse all the student table records into JSON.
  3. StudentRegister.php :- This file receive the student registration details coming from android application and insert into MySQL database.
  4. FilterStudentData.php :- This file would filter the student data with SQL query and return the result as JSON from.
  5. UpdateStudent.php :- This file receive the student edited record and replace them with previous records.
  6. DeleteStudent.php :- This file would delete the selected student record with student ID.

PHP Files Coding Start from here :-

Code for DatabaseConfig.php file.

<?php

//Define your host here.
$HostName = "localhost";

//Define your database username here.
$HostUser = "id632449_androidjson";

//Define your database password here.
$HostPass = "kdfjdfdskljomew9ry3873";

//Define your database name here.
$DatabaseName = "id632449_androidjson";

?>

Code for AllStudentData.php file.

<?php
include 'DatabaseConfig.php';

// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

if ($conn->connect_error) {
 
 die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM StudentTable";

$result = $conn->query($sql);

if ($result->num_rows >0) {
 
 
 while($row[] = $result->fetch_assoc()) {
 
 $tem = $row;
 
 $json = json_encode($tem);
 
 
 }
 
} else {
 echo "No Results Found.";
}
 echo $json;
$conn->close();
?>

Code for StudentRegister.php file.

 <?php
if($_SERVER['REQUEST_METHOD']=='POST'){

include 'DatabaseConfig.php';

 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);

 $S_name = $_POST['StudentName'];
 $S_Phone = $_POST['StudentPhone'];
 $S_Class = $_POST['StudentClass'];

$Sql_Query = "INSERT INTO StudentTable (name,phone_number,class) values ('$S_name','$S_Phone','$S_Class')";

 if(mysqli_query($con,$Sql_Query))
{
 echo 'Student Registered Successfully';
}
else
{
 echo 'Something went wrong';
 }
 }
 mysqli_close($con);
?>

Code for FilterStudentData.php file.

 <?php

if($_SERVER['REQUEST_METHOD']=='POST'){

include 'DatabaseConfig.php';

 $StudentID= $_POST['StudentID'];

// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

if ($conn->connect_error) {
 
 die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM StudentTable where id = '$StudentID'" ;

$result = $conn->query($sql);

if ($result->num_rows >0) {
 
 
 while($row[] = $result->fetch_assoc()) {
 
 $tem = $row;
 
 $json = json_encode($tem);
 
 }
 
} else {
 echo "No Results Found.";
}
 echo $json;

$conn->close();
}
?>

Code for UpdateStudent.php file.

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){

include 'DatabaseConfig.php';

 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);

 $id = $_POST['StudentID'];
 $S_name = $_POST['StudentName'];
 $S_Phone = $_POST['StudentPhone'];
 $S_Class = $_POST['StudentClass'];

$Sql_Query = "UPDATE StudentTable SET name= '$S_name', phone_number = '$S_Phone', class = '$S_Class' WHERE id = $id";

 if(mysqli_query($con,$Sql_Query))
{
 echo 'Record Updated Successfully';
}
else
{
 echo 'Something went wrong';
 }
 }
 mysqli_close($con);
?>

Code for DeleteStudent.php file.

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){

include 'DatabaseConfig.php';

 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);

 $ID = $_POST['StudentID'];

$Sql_Query = "DELETE FROM StudentTable WHERE id = '$ID'";

 if(mysqli_query($con,$Sql_Query))
{
 echo 'Record Deleted Successfully';
}
else
{
 echo 'Something went wrong';
 }
 }
 mysqli_close($con);
?>

4. Star a new android application development project .

5. Add Org.Apache.Http.Legacy library in your project :

Open your project’s build.gradle(Module:app) file .

Inside the android scope put useLibrary ‘org.apache.http.legacy’ like i did in below screenshot.

6. Add internet permission to your project :

Open your project’s AndroidManifest.xml file and paste below internet permission inside it. You can file AndroidManifest.xml file all source code at the bottom of this page along with all application source code.

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

 7. App Coding Start From Here for Android PHP Add Edit Delete View Select Using App To MySQL Database :

Code for MainActivity.java file.

package com.androidjson.serverupdate_androidjsoncom;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    EditText StudentName, StudentPhoneNumber, StudentClass;
    Button RegisterStudent, ShowStudents;
    String StudentNameHolder, StudentPhoneHolder, StudentClassHolder;
    Boolean CheckEditText ;
    ProgressDialog progressDialog;
    String finalResult ;
    HashMap<String,String> hashMap = new HashMap<>();
    HttpParse httpParse = new HttpParse();
    String HttpURL = "https://androidjsonblog.000webhostapp.com/Student/StudentRegister.php";

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

        StudentName = (EditText)findViewById(R.id.editName);
        StudentPhoneNumber = (EditText)findViewById(R.id.editPhoneNumber);
        StudentClass = (EditText)findViewById(R.id.editClass);

        RegisterStudent = (Button)findViewById(R.id.buttonSubmit);
        ShowStudents = (Button)findViewById(R.id.buttonShow);

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

                // Checking whether EditText is Empty or Not
                CheckEditTextIsEmptyOrNot();

                if(CheckEditText){

                    // If EditText is not empty and CheckEditText = True then this block will execute.

                    StudentRegistration(StudentNameHolder,StudentPhoneHolder, StudentClassHolder);

                }
                else {

                    // If EditText is empty then this block will execute .
                    Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }

            }
        });

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


                Intent intent = new Intent(getApplicationContext(),ShowAllStudentsActivity.class);

                startActivity(intent);

            }
        });
     }

    public void StudentRegistration(final String S_Name, final String S_Phone, final String S_Class){

        class StudentRegistrationClass extends AsyncTask<String,Void,String> {

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

                progressDialog = ProgressDialog.show(MainActivity.this,"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog.dismiss();

                Toast.makeText(MainActivity.this,httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            }

            @Override
            protected String doInBackground(String... params) {

                hashMap.put("StudentName",params[0]);

                hashMap.put("StudentPhone",params[1]);

                hashMap.put("StudentClass",params[2]);

                finalResult = httpParse.postRequest(hashMap, HttpURL);

                return finalResult;
            }
        }

        StudentRegistrationClass studentRegistrationClass = new StudentRegistrationClass();

        studentRegistrationClass.execute(S_Name,S_Phone,S_Class);
    }


    public void CheckEditTextIsEmptyOrNot(){

        StudentNameHolder = StudentName.getText().toString();
        StudentPhoneHolder = StudentPhoneNumber.getText().toString();
        StudentClassHolder = StudentClass.getText().toString();

        if(TextUtils.isEmpty(StudentNameHolder) || TextUtils.isEmpty(StudentPhoneHolder) || TextUtils.isEmpty(StudentClassHolder))
        {

            CheckEditText = false;

        }
        else {

            CheckEditText = true ;
        }

    }
}

Code for ShowAllStudentsActivity.java file.

package com.androidjson.serverupdate_androidjsoncom;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;

public class ShowAllStudentsActivity extends AppCompatActivity {

    ListView StudentListView;
    ProgressBar progressBar;
    String HttpUrl = "https://androidjsonblog.000webhostapp.com/Student/AllStudentData.php";
    List<String> IdList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_show_all_students);

        StudentListView = (ListView)findViewById(R.id.listview1);

        progressBar = (ProgressBar)findViewById(R.id.progressBar);

        new GetHttpResponse(ShowAllStudentsActivity.this).execute();

        //Adding ListView Item click Listener.
        StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // TODO Auto-generated method stub

                Intent intent = new Intent(ShowAllStudentsActivity.this,ShowSingleRecordActivity.class);

                // Sending ListView clicked value using intent.
                intent.putExtra("ListViewValue", IdList.get(position).toString());

                startActivity(intent);

                //Finishing current activity after open next activity.
                finish();

            }
        });
    }

    // JSON parse class started from here.
    private class GetHttpResponse extends AsyncTask<Void, Void, Void>
    {
        public Context context;

        String JSonResult;

        List<Student> studentList;

        public GetHttpResponse(Context context)
        {
            this.context = context;
        }

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

        @Override
        protected Void doInBackground(Void... arg0)
        {
            // Passing HTTP URL to HttpServicesClass Class.
            HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
            try
            {
                httpServicesClass.ExecutePostRequest();

                if(httpServicesClass.getResponseCode() == 200)
                {
                    JSonResult = httpServicesClass.getResponse();

                    if(JSonResult != null)
                    {
                        JSONArray jsonArray = null;

                        try {
                            jsonArray = new JSONArray(JSonResult);

                            JSONObject jsonObject;

                            Student student;

                            studentList = new ArrayList<Student>();

                            for(int i=0; i<jsonArray.length(); i++)
                            {
                                student = new Student();

                                jsonObject = jsonArray.getJSONObject(i);

                                // Adding Student Id TO IdList Array.
                                IdList.add(jsonObject.getString("id").toString());

                                //Adding Student Name.
                                student.StudentName = jsonObject.getString("name").toString();

                                studentList.add(student);

                            }
                        }
                        catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                else
                {
                    Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)

        {
            progressBar.setVisibility(View.GONE);

            StudentListView.setVisibility(View.VISIBLE);

            ListAdapterClass adapter = new ListAdapterClass(studentList, context);

            StudentListView.setAdapter(adapter);

        }
    }
}

Code for ShowSingleRecordActivity.java file.

package com.androidjson.serverupdate_androidjsoncom;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;

public class ShowSingleRecordActivity extends AppCompatActivity {

    HttpParse httpParse = new HttpParse();
    ProgressDialog pDialog;

    // Http Url For Filter Student Data from Id Sent from previous activity.
    String HttpURL = "https://androidjsonblog.000webhostapp.com/Student/FilterStudentData.php";

    // Http URL for delete Already Open Student Record.
    String HttpUrlDeleteRecord = "https://androidjsonblog.000webhostapp.com/Student/DeleteStudent.php";

    String finalResult ;
    HashMap<String,String> hashMap = new HashMap<>();
    String ParseResult ;
    HashMap<String,String> ResultHash = new HashMap<>();
    String FinalJSonObject ;
    TextView NAME,PHONE_NUMBER,CLASS;
    String NameHolder, NumberHolder, ClassHolder;
    Button UpdateButton, DeleteButton;
    String TempItem;
    ProgressDialog progressDialog2;

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

        NAME = (TextView)findViewById(R.id.textName);
        PHONE_NUMBER = (TextView)findViewById(R.id.textPhone);
        CLASS = (TextView)findViewById(R.id.textClass);

        UpdateButton = (Button)findViewById(R.id.buttonUpdate);
        DeleteButton = (Button)findViewById(R.id.buttonDelete);

        //Receiving the ListView Clicked item value send by previous activity.
        TempItem = getIntent().getStringExtra("ListViewValue");

        //Calling method to filter Student Record and open selected record.
        HttpWebCall(TempItem);


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

                Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

                // Sending Student Id, Name, Number and Class to next UpdateActivity.
                intent.putExtra("Id", TempItem);
                intent.putExtra("Name", NameHolder);
                intent.putExtra("Number", NumberHolder);
                intent.putExtra("Class", ClassHolder);

                startActivity(intent);

                // Finishing current activity after opening next activity.
                finish();

            }
        });

        // Add Click listener on Delete button.
        DeleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Calling Student delete method to delete current record using Student ID.
                StudentDelete(TempItem);

            }
        });

    }

    // Method to Delete Student Record
    public void StudentDelete(final String StudentID) {

        class StudentDeleteClass extends AsyncTask<String, Void, String> {

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

                progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog2.dismiss();

                Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

                finish();

            }

            @Override
            protected String doInBackground(String... params) {

                // Sending STUDENT id.
                hashMap.put("StudentID", params[0]);

                finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

                return finalResult;
            }
        }

        StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

        studentDeleteClass.execute(StudentID);
    }


    //Method to show current record Current Selected Record
    public void HttpWebCall(final String PreviousListViewClickedItem){

        class HttpWebCallFunction extends AsyncTask<String,Void,String> {

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

                pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                pDialog.dismiss();

                //Storing Complete JSon Object into String Variable.
                FinalJSonObject = httpResponseMsg ;

                //Parsing the Stored JSOn String to GetHttpResponse Method.
                new GetHttpResponse(ShowSingleRecordActivity.this).execute();

            }

            @Override
            protected String doInBackground(String... params) {

                ResultHash.put("StudentID",params[0]);

                ParseResult = httpParse.postRequest(ResultHash, HttpURL);

                return ParseResult;
            }
        }

        HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

        httpWebCallFunction.execute(PreviousListViewClickedItem);
    }


    // Parsing Complete JSON Object.
    private class GetHttpResponse extends AsyncTask<Void, Void, Void>
    {
        public Context context;

        public GetHttpResponse(Context context)
        {
            this.context = context;
        }

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

        @Override
        protected Void doInBackground(Void... arg0)
        {
            try
            {
                if(FinalJSonObject != null)
                {
                    JSONArray jsonArray = null;

                    try {
                        jsonArray = new JSONArray(FinalJSonObject);

                        JSONObject jsonObject;

                        for(int i=0; i<jsonArray.length(); i++)
                        {
                            jsonObject = jsonArray.getJSONObject(i);

                            // Storing Student Name, Phone Number, Class into Variables.
                            NameHolder = jsonObject.getString("name").toString() ;
                            NumberHolder = jsonObject.getString("phone_number").toString() ;
                            ClassHolder = jsonObject.getString("class").toString() ;

                        }
                    }
                    catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {

            // Setting Student Name, Phone Number, Class into TextView after done all process .
            NAME.setText(NameHolder);
            PHONE_NUMBER.setText(NumberHolder);
            CLASS.setText(ClassHolder);

        }
    }

}

Code for UpdateActivity.java file.

package com.androidjson.serverupdate_androidjsoncom;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.HashMap;

public class UpdateActivity extends AppCompatActivity {

    String HttpURL = "https://androidjsonblog.000webhostapp.com/Student/UpdateStudent.php";
    ProgressDialog progressDialog;
    String finalResult ;
    HashMap<String,String> hashMap = new HashMap<>();
    HttpParse httpParse = new HttpParse();
    EditText StudentName, StudentPhoneNumber, StudentClass;
    Button UpdateStudent;
    String IdHolder, StudentNameHolder, StudentPhoneHolder, StudentClassHolder;

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

        StudentName = (EditText)findViewById(R.id.editName);
        StudentPhoneNumber = (EditText)findViewById(R.id.editPhoneNumber);
        StudentClass = (EditText)findViewById(R.id.editClass);

        UpdateStudent = (Button)findViewById(R.id.UpdateButton);

        // Receive Student ID, Name , Phone Number , Class Send by previous ShowSingleRecordActivity.
        IdHolder = getIntent().getStringExtra("Id");
        StudentNameHolder = getIntent().getStringExtra("Name");
        StudentPhoneHolder = getIntent().getStringExtra("Number");
        StudentClassHolder = getIntent().getStringExtra("Class");

        // Setting Received Student Name, Phone Number, Class into EditText.
        StudentName.setText(StudentNameHolder);
        StudentPhoneNumber.setText(StudentPhoneHolder);
        StudentClass.setText(StudentClassHolder);

        // Adding click listener to update button .
        UpdateStudent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Getting data from EditText after button click.
                GetDataFromEditText();

                // Sending Student Name, Phone Number, Class to method to update on server.
                StudentRecordUpdate(IdHolder,StudentNameHolder,StudentPhoneHolder, StudentClassHolder);

            }
        });


    }

    // Method to get existing data from EditText.
    public void GetDataFromEditText(){

        StudentNameHolder = StudentName.getText().toString();
        StudentPhoneHolder = StudentPhoneNumber.getText().toString();
        StudentClassHolder = StudentClass.getText().toString();

    }

    // Method to Update Student Record.
    public void StudentRecordUpdate(final String ID, final String S_Name, final String S_Phone, final String S_Class){

        class StudentRecordUpdateClass extends AsyncTask<String,Void,String> {

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

                progressDialog = ProgressDialog.show(UpdateActivity.this,"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog.dismiss();

                Toast.makeText(UpdateActivity.this,httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            }

            @Override
            protected String doInBackground(String... params) {

                hashMap.put("StudentID",params[0]);

                hashMap.put("StudentName",params[1]);

                hashMap.put("StudentPhone",params[2]);

                hashMap.put("StudentClass",params[3]);

                finalResult = httpParse.postRequest(hashMap, HttpURL);

                return finalResult;
            }
        }

        StudentRecordUpdateClass studentRecordUpdateClass = new StudentRecordUpdateClass();

        studentRecordUpdateClass.execute(ID,S_Name,S_Phone,S_Class);
    }
}

Code for HttpParse.java file.

package com.androidjson.serverupdate_androidjsoncom;
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;

/**
 * Created by Juned on 3/3/2017.
 */

public class HttpParse {

    String FinalHttpData = "";
    String Result ;
    BufferedWriter bufferedWriter ;
    OutputStream outputStream ;
    BufferedReader bufferedReader ;
    StringBuilder stringBuilder = new StringBuilder();
    URL url;

    public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {

        try {
            url = new URL(HttpUrlHolder);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setReadTimeout(14000);

            httpURLConnection.setConnectTimeout(14000);

            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setDoInput(true);

            httpURLConnection.setDoOutput(true);

            outputStream = httpURLConnection.getOutputStream();

            bufferedWriter = new BufferedWriter(

                    new OutputStreamWriter(outputStream, "UTF-8"));

            bufferedWriter.write(FinalDataParse(Data));

            bufferedWriter.flush();

            bufferedWriter.close();

            outputStream.close();

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                bufferedReader = new BufferedReader(
                        new InputStreamReader(
                                httpURLConnection.getInputStream()
                        )
                );
                FinalHttpData = bufferedReader.readLine();
            }
            else {
                FinalHttpData = "Something Went Wrong";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return FinalHttpData;
    }

    public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {

        for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){

            stringBuilder.append("&");

            stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));

            stringBuilder.append("=");

            stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));

        }

        Result = stringBuilder.toString();

        return Result ;
    }
}

Code for HttpServicesClass.java file.

package com.androidjson.serverupdate_androidjsoncom;

/**
 * Created by Juned on 3/4/2017.
 */

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;

public class HttpServicesClass {
    public int responseCode;

    public String message;

    public String response;

    public ArrayList<NameValuePair> ArrayListParams;

    public ArrayList <NameValuePair> headers;

    public String UrlHolder;

    public String getResponse()
    {
        return response;
    }

    public String getErrorMessage()
    {
        return message;
    }

    public int getResponseCode()
    {
        return responseCode;
    }

    public HttpServicesClass(String url)
    {
        HttpServicesClass.this.UrlHolder = url;

        ArrayListParams = new ArrayList<NameValuePair>();

        headers = new ArrayList<NameValuePair>();
    }

    public void AddParam(String name, String value)
    {
        ArrayListParams.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }

    public void ExecuteGetRequest() throws Exception
    {
        String MixParams = "";

        if(!ArrayListParams.isEmpty())
        {
            MixParams += "?";

            for(NameValuePair p : ArrayListParams)
            {
                String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");

                if(MixParams.length() > 1)
                {
                    MixParams  +=  "&" + paramString;
                }
                else
                {
                    MixParams += paramString;
                }
            }
        }

        HttpGet httpGet = new HttpGet(UrlHolder + MixParams);

        for(NameValuePair h : headers)
        {
            httpGet.addHeader(h.getName(), h.getValue());
        }

        executeRequest(httpGet, UrlHolder);
    }

    public void ExecutePostRequest() throws Exception
    {
        HttpPost httpPost = new HttpPost(UrlHolder);
        for(NameValuePair h : headers)
        {
            httpPost.addHeader(h.getName(), h.getValue());
        }

        if(!ArrayListParams.isEmpty())
        {
            httpPost.setEntity(new UrlEncodedFormEntity(ArrayListParams, HTTP.UTF_8));
        }

        executeRequest(httpPost, UrlHolder);
    }

    private void executeRequest(HttpUriRequest request, String url)
    {
        HttpParams httpParameters = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);

        HttpConnectionParams.setSoTimeout(httpParameters, 10000);

        HttpClient httpClient = new DefaultHttpClient(httpParameters);

        HttpResponse httpResponse;
        try
        {
            httpResponse = httpClient.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();
            if (entity != null)
            {
                InputStream inputStream = entity.getContent();

                response = convertStreamToString(inputStream);

                inputStream.close();
            }
        }
        catch (ClientProtocolException e)
        {
            httpClient.getConnectionManager().shutdown();
            e.printStackTrace();
        }
        catch (IOException e)
        {
            httpClient.getConnectionManager().shutdown();
            e.printStackTrace();
        }
    }

    private String convertStreamToString(InputStream is)
    {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

        StringBuilder stringBuilder = new StringBuilder();

        String line = null;
        try
        {
            while ((line = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(line + "\n");
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                is.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

}

Code for ListAdapterClass.java file.

package com.androidjson.serverupdate_androidjsoncom;

/**
 * Created by Juned on 3/4/2017.
 */
import android.content.Context;
import java.util.List;
import android.app.Activity;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ListAdapterClass extends BaseAdapter {

    Context context;
    List<Student> valueList;

    public ListAdapterClass(List<Student> listValue, Context context)
    {
        this.context = context;
        this.valueList = listValue;
    }

    @Override
    public int getCount()
    {
        return this.valueList.size();
    }

    @Override
    public Object getItem(int position)
    {
        return this.valueList.get(position);
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ViewItem viewItem = null;

        if(convertView == null)
        {
            viewItem = new ViewItem();

            LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

            convertView = layoutInfiater.inflate(R.layout.listview_item, null);

            viewItem.TextViewStudentName = (TextView)convertView.findViewById(R.id.textView1);

            convertView.setTag(viewItem);
        }
        else
        {
            viewItem = (ViewItem) convertView.getTag();
        }

        viewItem.TextViewStudentName.setText(valueList.get(position).StudentName);

        return convertView;
    }
}

class ViewItem
{
    TextView TextViewStudentName;

}

Code for Student.java file.

package com.androidjson.serverupdate_androidjsoncom;

/**
 * Created by Juned on 3/4/2017.
 */

public class Student {

    public String StudentName ;

}

Code for activity_main.xml layout file.

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp"
    tools:context="com.androidjson.serverupdate_androidjsoncom.MainActivity"
    android:background="#FF5722">

    <TextView
        android:text="Student Registration Form"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:textSize="20dp"
        android:textStyle="bold"
        android:textColor="#fff"
        android:layout_marginTop="40dp"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:textColor="#000"
        android:background="#fff"
        android:inputType="textPersonName"
        android:gravity="center"
        android:hint="Enter Student Name"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/editName" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:textColor="#000"
        android:background="#fff"
        android:inputType="textPersonName"
        android:gravity="center"
        android:hint="Enter Student Phone Number"
        android:ems="10"
        android:layout_below="@+id/editName"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/editPhoneNumber" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:textColor="#000"
        android:background="#fff"
        android:inputType="textPersonName"
        android:gravity="center"
        android:hint="Enter Student Class"
        android:ems="10"
        android:layout_below="@+id/editPhoneNumber"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/editClass" />

    <Button
        android:text="Register"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_below="@+id/editClass"
        android:id="@+id/buttonSubmit" />
    <Button
        android:text="Show All Records"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="7dp"
        android:layout_below="@+id/buttonSubmit"
        android:id="@+id/buttonShow" />

</RelativeLayout>

Code for activity_show_all_students.xml layout file.

<?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:id="@+id/activity_show_all_students"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidjson.serverupdate_androidjsoncom.ShowAllStudentsActivity"
    >

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/listview1"/>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="visible"
        />
</RelativeLayout>

Code for activity_show_single_record.xml layout file.

<?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:id="@+id/activity_show_single_record"
    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="com.androidjson.serverupdate_androidjsoncom.ShowSingleRecordActivity"
    android:background="#FF5722">

    <TextView
        android:text="Name = "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="20dp"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        />

    <TextView
        android:text="Name Show Here"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="20dp"
        android:id="@+id/textName"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/textView"
        android:layout_toEndOf="@+id/textView" />

    <TextView
        android:text="Phone Number = "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="20dp"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="20dp"
        android:id="@+id/textView3" />

    <TextView
        android:text="Phone Show Here"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="20dp"
        android:id="@+id/textPhone"
        android:layout_alignBaseline="@+id/textView3"
        android:layout_alignBottom="@+id/textView3"
        android:layout_toRightOf="@+id/textView3"
        android:layout_toEndOf="@+id/textView3" />

    <TextView
        android:text="Class = "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="20dp"
        android:id="@+id/textView5"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="20dp"/>

    <TextView
        android:text="Class Show Here "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="20dp"
        android:id="@+id/textClass"
        android:layout_alignBaseline="@+id/textView5"
        android:layout_alignBottom="@+id/textView5"
        android:layout_toRightOf="@+id/textView"
        android:layout_toEndOf="@+id/textView" />

    <Button
        android:text="Edit This Record"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textClass"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="34dp"
        android:id="@+id/buttonUpdate" />

    <Button
        android:text="Delete This Record"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/buttonUpdate"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="7dp"
        android:id="@+id/buttonDelete" />

</RelativeLayout>

Code for activity_update.xml layout file.

<?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:id="@+id/activity_update"
    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="com.androidjson.serverupdate_androidjsoncom.UpdateActivity"
    android:background="#FF5722">

    <TextView
        android:text="Update Record Form"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="20dp"
        android:textColor="#fff"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:textColor="#000"
        android:background="#fff"
        android:inputType="textPersonName"
        android:gravity="center"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/editName" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:textColor="#000"
        android:background="#fff"
        android:inputType="textPersonName"
        android:gravity="center"
        android:ems="10"
        android:layout_below="@+id/editName"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/editPhoneNumber" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:textColor="#000"
        android:background="#fff"
        android:inputType="textPersonName"
        android:gravity="center"
        android:ems="10"
        android:layout_below="@+id/editPhoneNumber"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/editClass" />

    <Button
        android:text="Update"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_below="@+id/editClass"
        android:id="@+id/UpdateButton" />

</RelativeLayout>

Code for listview_item.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FF5722"
    android:padding="15dp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="24dp"
        android:text="Items"
        android:padding="10dp"

        />

</LinearLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjson.serverupdate_androidjsoncom">

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

    <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=".ShowAllStudentsActivity" />
        <activity android:name=".ShowSingleRecordActivity" />
        <activity android:name=".UpdateActivity"></activity>
    </application>

</manifest>

Screenshots :

Android PHP Add Edit Delete View Select Using App Example Tutorial

Download Code

Leave a Reply

Your email address will not be published. Required fields are marked *