혁신을 이룹니다, 오딘박스(OdinBOX)

언제나 어디서나 오딘박스와 함께!

안드로이드스튜디오, DB기능을 활용하여 명함관리 검색/저장 기능 구현

간지뽕빨리턴님 2020. 6. 17. 21:36
반응형

안드로이드스튜디오(안스),모바일앱개발,API,DB,PHP,SQL,MYSQL,localhost,명함관리,검색,기능,저장,애플,아이폰,신제품출시

명함관리, 검색과 저장기능을 구현

과제 일시 : 2020 - 06 - 17

저번 시간과 비슷하지만 이번에는 검색을 할 수 있는 기능을 만들어보았습니다. 처음 시작부터 조금 시간이 걸렸지만 저번에 했던 경험이 있어 이번에 조금 더 빨리 시간을 단축할 수 있었습니다.

 

< 실행화면 >

 

< 소스 코드 >

* MainActivity.java
package com.example.sqltest;

import androidx.appcompat.app.AppCompatActivity;

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;
    String[] result;
    private static String IP_ADDRESS = "10.0.2.2";
    //private static String IP_ADDRESS = "203.237.245.188"; 에뮬레이터와 서버 pc 가 다를 때
    private static String serverIP = "http://" + IP_ADDRESS + "/andtest.php";
    private static String TAG = "phptest";
    @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();
            }
        });
    }

    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();
    }

    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();

//osw로 sendMsg의 값을 받아서 인터넷의 파라매타로 보냄
//전송이 완료되면 서버에서 처리한 결값을 받는다
                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);

            //receiveMsg가 파라매타로 s값으로 가져옴
            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="저장" />

        <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>

* selectSearch.php
<?

$key = $_POST["key"];


 

$connect = mysql_connect("localhost","root","apmsetup");
mysql_select_db("company",$connect);

 

$sqlSelect = "select * from customer where name = '$key'";


$selectResult = mysql_query($sqlSelect);

while($row = mysql_fetch_assoc($selectResult)){

echo $row["name"];

echo "/";

echo $row["telNo"];

echo "/";

echo $row["eMail"];


}
mysql_close($connect);
?>

<html>
     <body>
         <form action = "<?php $PHP_SELF ?>" method = "POST">
             Name: <input type = "text" name = "name" />
             
             <input type = "submit" />
         </form>
     </body>
</html>

 

실행 좋고, 소스 좋다!