주) 현재 동작하지 않습니다.

이 글을 읽기 전에 다음 3개의 글을 읽어주세요.
"안드로이드 DB CRUD(쓰기, 읽기, 수정, 삭제) 1 - 프로세스" - http://ilbbang.tistory.com/34
"안드로이드 DB CRUD(쓰기, 읽기, 수정, 삭제) 2 - MariaDB 설정하기" - http://ilbbang.tistory.com/45
"안드로이드 DB CRUD(쓰기, 읽기, 수정, 삭제) 3 - PHP로 MySQL에 접근하기" - http://ilbbang.tistory.com/47
제가 따라해 볼 원문을 다시 확인해 보겠습니다.(출처)
http://freeprojectcode.com/android/android-mysql-basic-crud-operation-tutorial-for-android-studio-project/
(글 게시자가 홈페이지를 초기화 해서 해당 글을 더이상 볼 수 없습니다.)
이제 안드로이드에서 화면 및 구동이 가능하도록 프로그래밍을 해보겠습니다.
화면은 3개를 만들 예정입니다.
1. 쓰기 - 이름, 직책, 급여 입력란에 값을 입력하고 버튼을 클릭하면 DB에 작성 후에 "2. 읽기"으로 이동합니다. 입력하지 않아도 "2. 읽기" 화면으로 이동할 수도 있습니다.
2. 읽기 - 전체 목록을 출력합니다. 특정 목록을 클릭하면 "3.수정 및 삭제" 화면으로 이동합니다. "1. 쓰기" 화면으로 이동할 수도 있습니다.
3. 수정 및 삭제 - "2. 읽기"에서 출력된 목록 중 선택된 항목에 대한 정보를 수정할 수 있는 페이지 입니다. 내용을 변경 후에 버튼을 클릭하면 수정된 내용으로 DB를 update한 후에 "2. 읽기" 화면으로 이동합니다.. 수정하지 않고 "2. 읽기" 화면으로 이동할 수도 있습니다. 삭제 버튼을 클릭하면 선택된 항목을 삭제할 수도 있습니다.
그리고 구동에 필요한 별도의 자바 클래스를 4개 만들 예정입니다.
1. Constant - PHP 파일 주소 목록을 설정합니다.
2. PostRequestHandler - Post 방식의 Requset를 보내기 위한 클래스 입니다. 네트워크 관련 처리기 때문에 별도의 스래드(3. BackgroundWorker)를 생성하여 수행합니다.
3. BackgroundWorker - Background 에서 수행할 매서드가 있는 클래스입니다. Post로 보내기 및 받기 매서드가 있습니다.
4. JsonParser - Json으로 받은 내용을 안드로이드 화면에 출력하기 위해 변환하는 매서드가 있습니다.
안드로이드 스튜디오에서 새로운 프로젝트를
우선 클래스 부터 만들어 보겠습니다. 클래스를 만드는 방법은 아래 그림과 같이 탐색기에서 app 폴더에 마우스를 올린 후에 오른쪽 마우스 버튼을 클릭하고 New - Java Class를 클릭하고 클래스 이름을 입력하고 OK 버튼을 클릭하면 됩니다. 그럼 파일 별 코드를 보겠습니다.

1. Constant.java

public class Constant {      private static final String BASE_PATH = "php파일이있는폴더(마지막에/으로끝냄)";      public static final String CREATE_URL = BASE_PATH + "addEmp.php";     public static final String READ = BASE_PATH + "getAllEmp.php";     public static final String UPDATE = BASE_PATH + "updateEmp.php";     public static final String DELETE = BASE_PATH + "deleteEmp.php";      public static final String GET_METHOD = "GET";     static final String POST_METHOD = "POST"; } 

2. PostRequestHandler.java

import android.os.AsyncTask;  import java.io.UnsupportedEncodingException; import java.util.HashMap;  public class PostRequestHandler extends AsyncTask<Void, Void, String> {     // php URL 주소     String url;     // Key, Value 값     HashMap<String, String> requestedParams;      PostRequestHandler(String url, HashMap<String, String> params){         this.url = url;         this.requestedParams = params;     }      @Override     protected void onPreExecute() {         super.onPreExecute();     }      @Override     protected String doInBackground(Void... voids) {          // post request 보냄         BackgroundWorker backgroundWorker = new BackgroundWorker();         try {             String s = backgroundWorker.postRequestHandler(url, requestedParams);             return s.toString();         } catch (UnsupportedEncodingException e) {             e.printStackTrace();         }          return null;     }      @Override     protected void onPostExecute(String s) {         super.onPostExecute(s);     } } 

3. BackgroundWorker.java

import android.util.Log;  import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map;  public class BackgroundWorker {      // Make a POST Request Handler     public String postRequestHandler(String requestUrl, HashMap<String, String> requestedDataParams) throws UnsupportedEncodingException {          // Set an Empty URL obj in system         URL url;           // Set a String Builder to store result as string         StringBuilder stringBuilder = new StringBuilder();          try {             // Now Initialize URL             url = new URL(requestUrl);              // Make a HTTP url connection             HttpURLConnection connection = (HttpURLConnection) url.openConnection();              // Set Method Type             connection.setRequestMethod(Constant.POST_METHOD);             // Set Connection Time             connection.setConnectTimeout(10000);             connection.setReadTimeout(10000);             // set Input output ok             connection.setDoInput(true);             connection.setDoOutput(true);             // Remove Caches             //connection.setUseCaches(false);             //connection.setDefaultUseCaches(false);               // Creating a url as String with params             StringBuilder url_string = new StringBuilder();              boolean ampersand = false;             for (Map.Entry<String, String> params : requestedDataParams.entrySet() ){                 if (ampersand)                     url_string.append("&");                 else                     ampersand = true;                  url_string.append(URLEncoder.encode(params.getKey(), "UTF-8"));                 url_string.append("=");                 url_string.append(URLEncoder.encode(params.getValue(), "UTF-8"));             }             Log.d("Final Url===", url_string.toString());                //Creating an output stream             OutputStream outputStream = connection.getOutputStream();              // Write Output Steam             BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));             bufferedWriter.write(url_string.toString());              bufferedWriter.flush();             bufferedWriter.close();             outputStream.close();              //        Log.d("Response===", connection.getResponseMessage());              if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));                  // Local String                 String result;                 while ((result = bufferedReader.readLine()) != null) {                     stringBuilder.append(result);                 }                 //            Log.d("Result===", result);              }         } catch (MalformedURLException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         }          return stringBuilder.toString();     }      // Get Request Handler     public String getRequestHandler(String requestUrl){         // To Store response         StringBuilder stringBuilder = new StringBuilder();          try {             URL url = new URL(requestUrl);             // Open Connection             HttpURLConnection connection = (HttpURLConnection) url.openConnection();             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));              // Local             String result;             while ((result = bufferedReader.readLine()) != null) {                 stringBuilder.append(result + "\n");             }          } catch (MalformedURLException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         }          return null;     }  } 

4. JsonParser.java

import android.util.Log;  import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL;  public class JsonParser {     private static final String TAG = JsonParser.class.getSimpleName();      public String convertJson(String reqUrl) {         String response = null;         try {             URL url = new URL(reqUrl);             HttpURLConnection conn = (HttpURLConnection) url.openConnection();             conn.setRequestMethod("GET");             // read the response             InputStream in = new BufferedInputStream(conn.getInputStream());             response = convertStreamToString(in);         } catch (MalformedURLException e) {             Log.e(TAG, "MalformedURLException: " + e.getMessage());         } catch (ProtocolException e) {             Log.e(TAG, "ProtocolException: " + e.getMessage());         } catch (IOException e) {             Log.e(TAG, "IOException: " + e.getMessage());         } catch (Exception e) {             Log.e(TAG, "Exception: " + e.getMessage());         }         return response;     }      private String convertStreamToString(InputStream is) {         BufferedReader reader = new BufferedReader(new InputStreamReader(is));         StringBuilder sb = new StringBuilder();          String line;         try {             while ((line = reader.readLine()) != null) {                 sb.append(line).append('\n');             }         } catch (IOException e) {             e.printStackTrace();         } finally {             try {                 is.close();             } catch (IOException e) {                 e.printStackTrace();             }         }         return sb.toString();     } } 

이제 위 클래스를 포함한 화면을 만들어 보겠습니다. 추가 화면을를 만드는 방법은 아래 그림과 같이 탐색기에서 app 폴더에 마우스를 올린 후에 오른쪽 마우스 버튼을 클릭하고 New - Java Class를 클릭하고 클래스 이름을 입력하고 OK 버튼을 클릭하면 됩니다. 그럼 파일 별 코드를 보겠습니다.

위 방법으로 "ViewActivity"와 "EditActivity"를 프로젝트에 추가합니다.
이제부터 Activity의 외형 및 코드를 아래와 같이 작성합니다.
화면1. activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:padding="22dp"     tools:context=".MainActivity">      <LinearLayout         android:layout_width="match_parent"         android:layout_height="match_parent"         android:orientation="vertical"         android:padding="11dp">          <TextView             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:text="Android PHP MySQL CRUD"             android:textAlignment="center"             android:textColor="#e21ace41"             android:textSize="22dp" />          <TextView             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:text="FreeProjectCode.com"             android:textAlignment="center"             android:textColor="#e2f209df"             android:textSize="20dp" />          <EditText             android:id="@+id/name"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:hint="Name" />          <EditText             android:id="@+id/designation"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:hint="Designation" />          <EditText             android:id="@+id/salary"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:hint="Salary" />          <Button             android:id="@+id/btn_add"             android:onClick="createEmployee"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:textColor="#fff"             android:background="#e21ace41"             android:text="Add Employee"/>         <Button             android:id="@+id/btn_list"             android:onClick="employeeList"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:textColor="#fff"             android:layout_marginTop="11dp"             android:background="#e2152099"             android:text="Employee List"/>     </LinearLayout>  </android.support.constraint.ConstraintLayout> 

java코드1. MainActivity.java

import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;  import java.util.HashMap;  public class MainActivity extends AppCompatActivity {      private EditText mName, mDesignation, mSalary;     private Button mBtnAdd;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // Initialize EditText View         mName = (EditText) findViewById(R.id.name);         mDesignation = (EditText) findViewById(R.id.designation);         mSalary = (EditText) findViewById(R.id.salary);          mBtnAdd = (Button) findViewById(R.id.btn_add);     }      // Create     public void createEmployee(View view){          String name = mName.getText().toString();         String designation = mDesignation.getText().toString();         String salary = mSalary.getText().toString();          HashMap<String, String> requestedParams = new HashMap<>();         requestedParams.put("name", name);         requestedParams.put("designation", designation);         requestedParams.put("salary", salary);         Log.d("HashMap", requestedParams.get("name"));         Toast.makeText(getApplicationContext(), "Success!!! Employee Added Name: " + requestedParams.get("name"), Toast.LENGTH_LONG).show();          PostRequestHandler postRequestHandler = new PostRequestHandler(Constant.CREATE_URL, requestedParams);         postRequestHandler.execute();          employeeList(view);     }      public void employeeList(View view) {         Intent intent = new Intent(MainActivity.this, ViewActivity.class);         startActivity(intent);     }  } 

화면2. activity_view.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ViewActivity">  <RelativeLayout     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical">     <Button         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginBottom="11dp"         android:layout_marginTop="11dp"         android:background="#e21bd721"         android:onClick="addEmployee"         android:text="Add New Employee"         android:layout_alignParentBottom="true"         android:textColor="#fff" />      <ListView         android:id="@+id/list"         android:layout_width="match_parent"         android:layout_height="wrap_content" />  </RelativeLayout>  </RelativeLayout > 

여기서 ListView에 단순하게 택스트로 보여줄 수도 있지만 보기 좋은 형식으로 보여주려면 별도의 레이아웃 xml 파일을 만들어 줘야 합니다. 레이아웃을 만드는 방법은 아래 그림과 같이 탐색기에서 app 폴더에 마우스를 올린 후에 오른쪽 마우스 버튼을 클릭하고 New - Android Resource File을 클릭하고 Resource type를 Layout으로 선택한 다음 파일이름, Root element 등을 입력하고 OK 버튼을 클릭하면 됩니다.

위 방법으로 list_item.xml 파일를 프로젝트에 추가합니다.

화면2-1. list_item.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">      <TextView         android:id="@+id/id"         android:layout_width="0dp"         android:layout_height="0dp"         android:visibility="invisible"/>      <TextView         android:id="@+id/name"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:paddingBottom="2dip"         android:paddingTop="6dip"         android:textColor="@color/colorPrimaryDark"         android:textSize="16sp"         android:textStyle="bold" />      <TextView         android:id="@+id/designation"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:paddingBottom="2dip"         android:textColor="@color/colorAccent" />      <TextView         android:id="@+id/salary"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:textColor="#5d5d5d"         android:textStyle="bold" />  </LinearLayout> 

java코드2. ViewActivity.java

import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast;  import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;  import java.util.ArrayList; import java.util.HashMap;  public class ViewActivity extends AppCompatActivity {      private String TAG = MainActivity.class.getSimpleName();      private ProgressDialog pDialog;     private ListView lv;      // URL to get contacts JSON     //private static String url = "http://shapon.website/android/CRUD/getAllEmp.php";      ArrayList<HashMap<String, String>> contactList;      private String id, name, designation, salary;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_view);          contactList = new ArrayList<>();          lv = (ListView) findViewById(R.id.list);          new Handler().execute();          // OnItem Click         lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {             @Override             public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {                 //Employee employee = (Employee) adapterView.getItemAtPosition(i);                 Intent intent = new Intent(ViewActivity.this, EditActivity.class);                  id = ((TextView) view.findViewById(R.id.id)).getText().toString();                 name = ((TextView) view.findViewById(R.id.name)).getText().toString();                 designation = ((TextView) view.findViewById(R.id.designation)).getText().toString();                 salary = ((TextView) view.findViewById(R.id.salary)).getText().toString();     //                String id = employee.getId(); //                String name = employee.getName(); //                String designation = employee.getDesignation(); //                String salary = employee.getSalary();                  intent.putExtra("ID", id);                 intent.putExtra("NAME", name);                 intent.putExtra("DESIGNATION", designation);                 intent.putExtra("SALARY", salary);                  startActivity(intent);             }         });     }      public void addEmployee(View view) {         Intent intent = new Intent(ViewActivity.this, MainActivity.class);         startActivity(intent);     }      /**      * Async task class to get json by making HTTP call      */     private class Handler extends AsyncTask<Void, Void, Void> {          private ListAdapter adapter;          @Override         protected void onPreExecute() {             super.onPreExecute();             // Showing progress dialog             pDialog = new ProgressDialog(ViewActivity.this);             pDialog.setMessage("Please wait...");             pDialog.setCancelable(false);             pDialog.show();          }          @Override         protected Void doInBackground(Void... arg0) {             JsonParser sh = new JsonParser();              // Making a request to url and getting response             String jsonStr = sh.convertJson(Constant.READ);              Log.e(TAG, "Response from url: " + jsonStr);              if (jsonStr != null) {                 try {                     JSONObject jsonObj = new JSONObject(jsonStr);                      // Getting JSON Array node                     JSONArray employeeArray = jsonObj.getJSONArray("result");                      // looping through All Contacts                     for (int i = 0; i < employeeArray.length(); i++) {                         JSONObject c = employeeArray.getJSONObject(i);                          String id = c.getString("id");                         String name = c.getString("name");                         String designation = c.getString("designation");                         String salary = c.getString("salary");                          // Phone node is JSON Object //                        JSONObject phone = c.getJSONObject("phone"); //                        String mobile = phone.getString("mobile"); //                        String home = phone.getString("home"); //                        String office = phone.getString("office");                          // tmp hash map for single contact                         HashMap<String, String> employee = new HashMap<>();                          // adding each child node to HashMap key => value                         employee.put("id", id);                         employee.put("name", name);                         employee.put("designation", designation);                         employee.put("salary", salary);                          // adding contact to contact list                         contactList.add(employee);                     }                 } catch (final JSONException e) {                     Log.e(TAG, "Json parsing error: " + e.getMessage());                     runOnUiThread(new Runnable() {                         @Override                         public void run() {                             Toast.makeText(getApplicationContext(),                                     "Json parsing error: " + e.getMessage(),                                     Toast.LENGTH_LONG)                                     .show();                         }                     });                  }             } else {                 Log.e(TAG, "Couldn't get json from server.");                 runOnUiThread(new Runnable() {                     @Override                     public void run() {                         Toast.makeText(getApplicationContext(),                                 "Couldn't get json from server. Check LogCat for possible errors!",                                 Toast.LENGTH_LONG)                                 .show();                     }                 });              }              return null;         }          @Override         protected void onPostExecute(Void result) {             super.onPostExecute(result);             // Dismiss the progress dialog             if (pDialog.isShowing())                 pDialog.dismiss();             /**              * Updating parsed JSON data into ListView              * */             ListAdapter adapter = new SimpleAdapter(                     ViewActivity.this, contactList,                     R.layout.list_item, new String[]{"id", "name", "designation",                     "salary"}, new int[]{R.id.id, R.id.name,                     R.id.designation, R.id.salary});              lv.setAdapter(adapter);           }      }  } 

화면3. activity_edit.xml

<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".EditActivity">      <LinearLayout         android:layout_width="match_parent"         android:layout_height="match_parent"         android:orientation="vertical"         android:padding="11dp">          <TextView             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:text="Android PHP MySQL CRUD"             android:textAlignment="center"             android:textColor="#e21ace41"             android:textSize="22dp" />          <TextView             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:text="FreeProjectCode.com"             android:textAlignment="center"             android:textColor="#e2f209df"             android:textSize="20dp" />           <EditText             android:id="@+id/id"             android:layout_width="0dp"             android:layout_height="0dp"             android:hint="Id"             android:visibility="invisible" />          <EditText             android:id="@+id/name"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:hint="Name" />          <EditText             android:id="@+id/designation"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:hint="Designation" />          <EditText             android:id="@+id/salary"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:hint="Salary" />          <Button             android:id="@+id/btn_update"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:background="#e21ace41"             android:onClick="updateEmployee"             android:text="Edit Employee"             android:textColor="#fff" />          <Button             android:id="@+id/btn_list"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_marginTop="11dp"             android:background="#c28c27a6"             android:onClick="listEmployee"             android:text="Show Employee List"             android:textColor="#fff" />          <Button             android:id="@+id/btn_delete"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_marginTop="11dp"             android:background="#e2d11527"             android:onClick="deleteEmployee"             android:text="Delete Employee"             android:textColor="#fff" />        </LinearLayout>  </android.support.constraint.ConstraintLayout> 

java코드3. EditActivity.java

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


import java.util.HashMap; public class EditActivity extends AppCompatActivity { private EditText mId, mName, mDesignation, mSalary; private Button mBtnAdd; //private String mId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit); // Initialize EditText View mId = (EditText) findViewById(R.id.id); mName = (EditText) findViewById(R.id.name); mDesignation = (EditText) findViewById(R.id.designation); mSalary = (EditText) findViewById(R.id.salary); mBtnAdd = (Button) findViewById(R.id.btn_add); Intent intent = getIntent(); Bundle bundle = intent.getExtras(); if (bundle != null){ mId.setText(bundle.getString("ID")); mName.setText(bundle.getString("NAME")); mDesignation.setText(bundle.getString("DESIGNATION")); mSalary.setText(bundle.getString("SALARY")); } } public void updateEmployee(View view) { String id = mId.getText().toString(); String name = mName.getText().toString(); String designation = mDesignation.getText().toString(); String salary = mSalary.getText().toString(); HashMap<String, String> requestedParams = new HashMap<>(); requestedParams.put("id", id); requestedParams.put("name", name); requestedParams.put("designation", designation); requestedParams.put("salary", salary); Log.d("HashMap", requestedParams.get("id")); Toast.makeText(getApplicationContext(), "Success!! Employee Updated ID : " + requestedParams.get("id"), Toast.LENGTH_LONG).show(); PostRequestHandler postRequestHandler = new PostRequestHandler(Constant.UPDATE, requestedParams); postRequestHandler.execute(); listEmployee(view); } public void deleteEmployee(View view) { String id = mId.getText().toString(); // String name = mName.getText().toString(); // String designation = mDesignation.getText().toString(); // String salary = mSalary.getText().toString(); HashMap<String, String> requestedParams = new HashMap<>(); requestedParams.put("id", id); // requestedParams.put("name", name); // requestedParams.put("designation", designation); // requestedParams.put("salary", salary); Log.d("HashMap", requestedParams.get("id")); Toast.makeText(getApplicationContext(), "Success!! Employee Deleted ID : " + requestedParams.get("id"), Toast.LENGTH_LONG).show(); PostRequestHandler postRequestHandler = new PostRequestHandler(Constant.DELETE, requestedParams); postRequestHandler.execute(); listEmployee(view); } public void listEmployee(View view) { Intent intent = new Intent(EditActivity.this, ViewActivity.class); startActivity(intent); } }

이제 빌드 후 앱을 실행해 보겠습니다.
안드로이드 DB CRUD 1 - 쓰기
앱을 실행하면 처음 화면이 나타납니다. 이름. 직책, 급여를 입력하고 ADD EMPLOYEE 버튼을 클릭하면 DB에 저장되고 전체 목록을 보여줍니다.

 

안드로이드 DB CRUD 2 - 읽기
DB에 저장된 전체 목록을 불러온 화면입니다. 항목을 클릭하면 해당 항목만 불러와 수정, 삭제를 할 수 있습니다.

안드로이드 DB CRUD 3 - 수정
알바생의 급여를 수정한 후에 EDIT EMPLOYEE 버튼을 클릭하면 DB에 내용이 수정되고 수정된 내용이 포함된 전체 목록을 출력합니다.

 

안드로이드 DB CRUD 4 - 삭제
알바생을 선택한 후에 DELETE EMPLOYEE 버튼을 클릭하면 DB에서 알바생을 삭제하고 업데이트 된 전체 목록을 출력합니다.

 

감사합니다.


+ Recent posts