글 목록

최신 글과 검색 결과
DEVELOPMENT/MobileAppDev

안드로이드스튜디오, 명함관리 수정 및 삭제 기능 구현하기

간지뽕빨리턴님

이 글의 목차

    반응형

    모바일앱개발,안드로이드스튜디오,수정,삭제,업데이트,insert,update확인,패치,삭제,delete

    안드로이드 스튜디오, 명함관리 최종 마무리? 수정 및 삭제 기능 구현하기 !

    과제일시 : 06 - 20

    저장과 검색 기능 까지는 구현이 되었고, 이제 수정과 삭제의 기능을 구현 할 차례가 되었습니다. 이번에는 생각보다 쉽게 구현이 되었습니다. 많이 부족한만큼 열심히 하겠습니다.

     

    [ 실행화면 ]

     

    [ 소스 코드 ]

    * MainActivity.java
    package com.example.sqltest;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.annotation.SuppressLint;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.Handler;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    
    
    public class MainActivity extends AppCompatActivity {
        Handler handler = new Handler();
        EditText etName, etTelNo, email, etLoad;
        Button btnSave,btnsrch, btndelete, btnupdate;
        String[] result;
        private static String IP_ADDRESS = "10.0.2.2";
        //private static String IP_ADDRESS = "123";
        private static String serverIP = "http://" + IP_ADDRESS + "/andtest.php";
        private static String TAG = "phptest";
        @SuppressLint("WrongViewCast")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            etName = (EditText)findViewById(R.id.editText);
            etTelNo = (EditText)findViewById(R.id.editText2);
            email = (EditText)findViewById(R.id.editText3);
            btnSave = (Button)findViewById(R.id.button);
            etLoad = (EditText)findViewById(R.id.editText4);
            btnSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String name = etName.getText().toString();
                    String telNo = etTelNo.getText().toString();
                    String email = MainActivity.this.email.getText().toString();
    
                    new Task().execute(serverIP, name, telNo, email);
    
    //                etName.setText("");
    //                etTelNo.setText("");
    
                }
            });
            btnsrch = (Button)findViewById(R.id.button2);
            btnsrch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dataSelect();
                }
            });
            btndelete = (Button) findViewById(R.id.button3);
            btnupdate = (Button) findViewById(R.id.button4);
            btndelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dataDelete();
                }
            });
    
            btnupdate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dataUpdate();
                }
            });
    
    
        }
    
        public void dataSelect() {
    
            new Thread() {
    
                public void run() {
    
                    try {
                        String key = etLoad.getText().toString();
                        URL url = new URL("Http://10.0.2.2/selectSerach.php");
                        HttpURLConnection http = (HttpURLConnection) url.openConnection();
                        http.setDefaultUseCaches(false);
                        http.setDoInput(true);
                        http.setRequestMethod("POST");
                        http.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                        StringBuffer buffer = new StringBuffer();
                        buffer.append("key").append("=").append(key);
                        OutputStreamWriter osw = new OutputStreamWriter(http.getOutputStream(), "utf-8");
                        osw.write(buffer.toString());
                        osw.flush();
    
                        InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "utf-8");
                        BufferedReader reader = new BufferedReader(tmp);
                        StringBuilder builder = new StringBuilder();
                        String str;
    
                        while ((str = reader.readLine()) != null) {
                            builder.append(str + "\n");
                        }
    
                        String resultData = builder.toString();
                        final String[] sResult = resultData.split("/");
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
    
                                etName.setText(sResult[0]);
                                etTelNo.setText(sResult[1]);
                                email.setText(sResult[2]);
    
                            }
                        });
    
                        etName.setText(str);
    
                    } catch (Exception e) {
                        Log.e("", "Error", e);
                    }
                }
            }.start();
        }
        public void dataDelete(){
            new Thread(){
                public void run(){
                    try
                    {
                        final String key = etName.getText().toString();
                        URL url = new URL("Http://10.0.2.2/delete.php/");
                        HttpURLConnection http = (HttpURLConnection)url.openConnection();
                        http.setDefaultUseCaches(false);
                        http.setDoInput(true);
                        http.setRequestMethod("POST");
                        http.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                        StringBuffer buffer = new StringBuffer();
                        buffer.append("name").append("=").append(key);
    
                        OutputStreamWriter osw = new OutputStreamWriter(http.getOutputStream(),"euc-kr");
                        osw.write(buffer.toString());
                        osw.flush();
    
                        InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "euc-kr");
                        BufferedReader reader = new BufferedReader(tmp);
                        StringBuilder builder = new StringBuilder();
                        String resultData = builder.toString();
                        String[] Result = resultData.split("/");
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this,key+"정보 삭제",Toast.LENGTH_SHORT).show();
                            }
                        });
    
                    } catch (Exception e){
                        Log.e("","Error",e);
                    }
    
                }
            }.start();
        }
        public void dataUpdate(){
            new Thread(){
                public void run(){
                    try
                    {
                        String sname = etName.getText().toString();
                        String scall = etTelNo.getText().toString();
                        String smail = email.getText().toString();
    
                        URL url = new URL("Http://10.0.2.2/update.php/");
                        HttpURLConnection http = (HttpURLConnection)url.openConnection();
                        http.setDefaultUseCaches(false);
                        http.setDoInput(true);
                        http.setRequestMethod("POST");
                        http.setRequestProperty("content-type", "application/x-www-form-urlencoded");
    
                        StringBuffer buffer = new StringBuffer();
                        buffer.append("ins").append("=").append(sname).append("/").append(scall).append("/").append(smail);
    
                        OutputStreamWriter osw = new OutputStreamWriter(http.getOutputStream(),"euc-kr");
                        osw.write(buffer.toString());
                        osw.flush();
    
                        InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "euc-kr");
                        BufferedReader reader = new BufferedReader(tmp);
                        StringBuilder builder = new StringBuilder();
                        String str;
                        while ((str=reader.readLine())!=null){
                            builder.append(str);
                            builder.append("\n");
                        }
                        String resultData = builder.toString();
                        final String sResult[] = resultData.split("/");
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this,"수정완료",Toast.LENGTH_SHORT).show();
                            }
                        });
    
    
                    } catch (Exception e){
                        Log.e("","Error",e);
                    }
    
                }
            }.start();
        }
    
        class Task extends AsyncTask<String,Void,String> {
            String sendMsg,receiveMsg;
    
            protected void onPreExcute(){
                super.onPreExecute();
            }
            @Override
            protected String doInBackground(String... strings) {
                try{
    
                    String str;
                    String serverIp = (String)strings[0];
                    String name = (String)strings[1];
                    String telNo = (String)strings[2];
                    String email = (String)strings[3];
    
                    Log.d("doinBackground", name);
    
                    URL url=new URL(serverIp);
                    HttpURLConnection conn=(HttpURLConnection)url.openConnection();
                    Log.d("network", serverIp);
                    //conn.setRequestProperty("Content-type","application/x-www-form-rlencoded");
                    conn.setRequestMethod("POST");
                    conn.connect();
    
                    OutputStreamWriter osw=new OutputStreamWriter(conn.getOutputStream());
                    sendMsg= "name=" + name + "&telNo=" + telNo + "&email=" + email;
                    osw.write(sendMsg);
                    Log.d("check OutputStream", sendMsg);
                    osw.flush();   osw.close();
    
                    if(conn.getResponseCode()==conn.HTTP_OK){
                        InputStreamReader tmp=new InputStreamReader(conn.getInputStream(),"UTF-8");
                        BufferedReader reader=new BufferedReader(tmp);
                        StringBuffer buffer=new StringBuffer();
                        while((str=reader.readLine()) != null){
                            buffer.append(str);
                        }
                        receiveMsg=buffer.toString();
                        Log.d("check InputStream", receiveMsg);
                    }
                    else {
                        Log.d(TAG, "Insert Error");
                    }
                }catch (Exception e){
                    Log.d("Error", "DoInBackground");
                }
                return  receiveMsg;
            }
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
    
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    * activity_main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.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=".MainActivity">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    
            <EditText
                android:id="@+id/editText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="이름을 입력하세요."
                android:inputType="textPersonName" />
    
            <EditText
                android:id="@+id/editText2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="전화번호를 입력하세요."
                android:inputType="textPersonName" />
    
            <EditText
                android:id="@+id/editText3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="이메일을 입력하세요."
                android:inputType="textPersonName" />
    
            <Button
                android:id="@+id/button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="저장" />
    
            <Button
                android:id="@+id/button3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="삭제" />
    
            <Button
                android:id="@+id/button4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="수정" />
    
            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="검색창" />
    
            <EditText
                android:id="@+id/editText4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="이름으로 검색하세요"
                android:inputType="textPersonName" />
    
            <Button
                android:id="@+id/button2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="검색" />
    
        </LinearLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    * update.php
    <?
     $ins = $_POST["ins"];
     
     $connect = mysqli_connect("localhost","root","apmsetup","company");
     mysqli_select_db($connect, "company");
    
     $arrUp = explode("/", $ins);
     $updateSQL = "update customer set telno = '$arrUp[1]', email = '$arrUp[2]' where name = '$arrUp[0]'";
     
     mysqli_query( $connect,$updateSQL);
    ?>
    
    * delete.php
    <?
    $key = $_POST["name"];
    
    $connect = mysqli_connect("localhost","root","apmsetup","company");
    mysqli_select_db($connect, "company");
    
    $sqlDelete = "delete  from customer where name = '$key'";
    
    mysqli_query($connect, $sqlDelete);
    
    ?>
    
    
    

    감사합니다

    Thank you !