Android/활용

안드로이드 - QR코드 리더기 만들기 (mysql, php 활용편) 데이터 저장 구현

섭섭입니다 2020. 9. 10. 23:23

저번엔 firebase에 저장해 봤지만 이번엔 아파치 서버를 이용해서 데이터를 저장해 볼 것이다 

 

 

 

 

그리고, 전에는 QR코드를 찍고 화면이 전환된 뒤 EditText에 데이터가 적혀진 뒤에 그것을 저장버튼을 이용

 

해서 firebase에 저장했다면,  이번에는 EditText에 옮겨진 것을 바로 mysql에 저장하게 끔 한뒤에 바로 다시

 

큐알을 스캔하는 함수를 이용해 바로 다시 QR을 스캔하게끔 코드를 구현해봤다.

 

 

 

구현 영상.

 

 

QR code Generator 사이트이다.

 

goqr.me

 

QR Code Generator – create QR codes for free (Logo, T-Shirt, vCard, EPS)

Information about our QR code generator You can generate free QR codes on this website. A QR code is a two dimensional barcode that stores information in black and white dots (called data pixels or “QR code modules”). Besides the black and white versio

goqr.me

 

 

 

 

추가한 QR의 데이터 내용은 다음과 같다.

 

 

1. 첫 번째 QR code

 

{"userNumber":"01002341","userPassword":"정보통신공학과","userName":"김홍길"}

 

2. 두 번째 QR code

 

{"userNumber":"12341234","userPassword":"컴퓨터공학과","userName":"내이름"}

 

 

 

위와 같이 Qr를 스캔하면 아래의 사진에서 볼 수 있듯 바로 추가되는 것을 볼 수 있다.

 

 

 

저장되는 시간을 추가하는 것은 PHP 문 안에서 value 를 "NOW()"를 이용하여 저장되는 시간을 측정하여 넣을 수 있게 끔 하였다.

 

 

 

화면이 전환되고, 저장버튼을 누르는 수고스러움을 덜었다.

 

 

 

 

 

코드는 다음과 같다.

 

 

< dbcon.php >

<?php

    $host = 'localhost';
    $username = 'root'; # MySQL 계정 아이디
    $password = 'qwe123'; # MySQL 계정 패스워드
    $dbname = 'capston';  # DATABASE 이름


    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');

    try {

        $con = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8",$username, $password);
    } catch(PDOException $e) {

        die("Failed to connect to the database: " . $e->getMessage());
    }


    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
        function undo_magic_quotes_gpc(&$array) {
            foreach($array as &$value) {
                if(is_array($value)) {
                    undo_magic_quotes_gpc($value);
                }
                else {
                    $value = stripslashes($value);
                }
            }
        }

        undo_magic_quotes_gpc($_POST);
        undo_magic_quotes_gpc($_GET);
        undo_magic_quotes_gpc($_COOKIE);
    }

    header('Content-Type: text/html; charset=utf-8');
    #session_start();
?>

 

 

 

< insert.php >

<?php

    error_reporting(0);
    //error_reporting(E_ALL);
    //ini_set('display_errors',1);

    include('dbcon.php');


    $android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");


    if( (($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['submit'])) || $android )
    {

        // 안드로이드 코드의 postParameters 변수에 적어준 이름을 가지고 값을 전달 받습니다.

        $userName=$_POST['userName'];
        $userPassword=$_POST['userPassword'];
        $userNumber=$_POST['userNumber'];
        $userTemperature=$_POST['userTemperature'];

        if(empty($userName)){
            $errMSG = "이름을 입력하세요.";
        }
        else if(empty($userPassword)){
            $errMSG = "학과를 입력하세요.";
        }
        else if(empty($userNumber)){
            $errMSG = "학번을 입력하세요.";
        }



        if(!isset($errMSG)) // 이름과 나라 모두 입력이 되었다면
        {
            try{
                // SQL문을 실행하여 데이터를 MySQL 서버의 person 테이블에 저장합니다.
                $stmt = $con->prepare('INSERT INTO topic(userName, userPassword, userNumber, userTime) 
                VALUES(:userName, :userPassword, :userNumber, NOW())');
                
                $stmt->bindParam(':userName', $userName);
                $stmt->bindParam(':userPassword', $userPassword);
                $stmt->bindParam(':userNumber', $userNumber);



                if($stmt->execute())
                {
                    $successMSG = "새로운 사용자를 추가했습니다.";
                }
                else
                {
                    $errMSG = "사용자 추가 에러";
                }

            } catch(PDOException $e) {
                die("Database error: " . $e->getMessage());
            }
        }

    }

?>


<?php
    if (isset($errMSG)) echo $errMSG;
    if (isset($successMSG)) echo $successMSG;

	$android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");

    if( !$android )
    {
?>
    <html>
       <body>

            <form action="<?php $_PHP_SELF ?>" method="POST">
                userName: <input type = "text" name = "userName" />
                userPassword: <input type = "text" name = "userPassword" />
                userNumber: <input type = "text" name = "userNumber" />
                userTemperature: <input type = "text" name = "userTemperature" />
                <input type = "submit" name = "submit" />
            </form>

       </body>
    </html>

<?php
    }
?>

 

 

< MainActivity.java >

package com.example.qrscan;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;

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.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import static java.security.AccessController.getContext;


public class MainActivity extends AppCompatActivity {
    //view Objects
    private Button buttonScan,btn_save;
    private TextView textViewName, textViewAddress, textViewResult, temperature,dateNow;
    int a = 0;
    int count =0;
    int num =1;

    // mysql 접속
    private static String IP_ADDRESS = "192.168.0.26";
    private static String TAG = "phptest";
    private TextView mTextViewResult;
    long now = System.currentTimeMillis();

    Date date = new Date(now);
    SimpleDateFormat sdfNow = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    String formatDate =sdfNow.format(date);

    //qr code scanner object
    private IntentIntegrator qrScan;


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


        //mTextViewResult = findViewById(R.id.mTextViewResult);


        //View Objects
        buttonScan = (Button) findViewById(R.id.buttonScan);
        textViewName = (TextView) findViewById(R.id.textViewName);
        textViewAddress = (TextView) findViewById(R.id.textViewPassword);
        textViewResult = (TextView)  findViewById(R.id.textViewResult);
        temperature=(TextView)  findViewById(R.id.temperature);


        //intializing scan object
        qrScan = new IntentIntegrator(this);

        //button onClick
        buttonScan.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //scan option

                    qrScan.setPrompt("Scanning...");
                    //qrScan.setOrientationLocked(false);
                    qrScan.initiateScan();

            }
        });

    }

    class InsertData extends AsyncTask<String, Void, String>{
        ProgressDialog progressDialog;

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

            progressDialog = ProgressDialog.show(MainActivity.this,
                    "Please Wait", null, true, true);
        }


        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            progressDialog.dismiss();
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
            Log.d(TAG, "POST response  - " + result);
        }


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

            String userName = (String)params[1];
            String userPassword = (String)params[2];
            String userNumber = (String)params[3];
            String userTemperature = (String)params[4];

            String serverURL = (String)params[0];

            String postParameters = "userName=" + userName + "&userPassword=" + userPassword + "&userNumber=" + userNumber + "&userTemperature=" + userTemperature;


            try {

                URL url = new URL(serverURL);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();


                httpURLConnection.setReadTimeout(5000);
                httpURLConnection.setConnectTimeout(5000);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.connect();


                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(postParameters.getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();


                int responseStatusCode = httpURLConnection.getResponseCode();
                Log.d(TAG, "POST response code - " + responseStatusCode);

                InputStream inputStream;
                if(responseStatusCode == HttpURLConnection.HTTP_OK) {
                    inputStream = httpURLConnection.getInputStream();
                }
                else{
                    inputStream = httpURLConnection.getErrorStream();
                }


                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                StringBuilder sb = new StringBuilder();
                String line = null;

                while((line = bufferedReader.readLine()) != null){
                    sb.append(line);
                }


                bufferedReader.close();


                return sb.toString();


            } catch (Exception e) {

                Log.d(TAG, "InsertData: Error ", e);

                return new String("Error: " + e.getMessage());
            }

        }
    }


    //Getting the scan results
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){

        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            //qrcode 가 없으면
            if (result.getContents() == null) {
                Toast.makeText(MainActivity.this, "취소!", Toast.LENGTH_SHORT).show();
            } else {
                //qrcode 결과가 있으면
                Toast.makeText(MainActivity.this, "스캔완료!", Toast.LENGTH_SHORT).show();
                try {
                    //data를 json으로 변환
                    JSONObject obj = new JSONObject(result.getContents());
                    textViewAddress.setText(obj.getString("userPassword"));
                    textViewName.setText(obj.getString("userNumber"));
                    textViewResult.setText(obj.getString("userName"));

                    String userName = textViewName.getText().toString();
                    String userPassword = textViewAddress.getText().toString();
                    String userNumber = textViewResult.getText().toString();
                    String userTemperature = temperature.getText().toString();
                    InsertData task = new InsertData();
                    task.execute("http://" + IP_ADDRESS + "/QRtest/insert.php", userNumber,userPassword,userName,userTemperature);


                    textViewName.setText("");
                    textViewAddress.setText("");
                    textViewResult.setText("");
                    temperature.setText("");

                    qrScan.setPrompt("Scanning...");
                    //qrScan.setOrientationLocked(false);
                    qrScan.initiateScan();


                } catch (JSONException e) {
                    e.printStackTrace();
                    //Toast.makeText(MainActivity.this, result.getContents(), Toast.LENGTH_LONG).show();
                    textViewResult.setText(result.getContents());
                }
            }

        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }





}

 

 

 

 

참고 블로그 : webnautes.tistory.com/828 ,

                  m.blog.naver.com/cosmosjs/220937443111