Android/활용

안드로이드 - QR코드 스캔하여 Firebase Realtime Database에 저장하기 (QR스캐너)

섭섭입니다 2020. 9. 7. 17:29

프로젝트 중 QR코드를 스캔하는 기능이 필요해 구글링 해보던 중 QR 코드 스캔을 할 수 있는 라이브러리가 있다는 것 을 알고 블로그를 참고 하였다.

 

firebase의 데이터베이스와 연동하는 것은 지난 글에 있으므로 생략했다.

 

 

 

프로젝트 생성 후 앱을 빌드한 후 firebase와 연동하여 데이터베이스를 쓸 것이다.

 

 

 

QR코드를 찍어서 txt 데이터를 json 형태로 받은 후에 그것을 firebase database에 저장 할 것이다.

 

QR코드 만드는 사이트는 다음과 같다. text형태로 만들었다.

 

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

 

구현 영상.

 

 

필요한 정보 학과, 학번, 이름의 데이터가 담긴 큐알코드를 만들고, 그것을 이용하여 찍으면 EditText에 데이터가 담기는데 그것을 버튼을 통하여 데이터베이스에 저장되게 된다.

 

 

큐알의 text는 다음과 같은 형태로 입력하였다. 

 

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

 

 

<MainActivity.java>

package com.example.qrscan;

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

import android.os.Bundle;
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.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

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

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;
    int a = 0;

    //qr code scanner object
    private IntentIntegrator qrScan;
    private DatabaseReference mDatabase;

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


        btn_save = findViewById(R.id.button);


        mDatabase = FirebaseDatabase.getInstance().getReference();

        readUser();

        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String getUserName = textViewName.getText().toString();
                String getUserPassword = textViewAddress.getText().toString();
                String getUserNumber = textViewResult.getText().toString();

                //hashmap 만들기
                HashMap result = new HashMap<>();
                result.put("학과", getUserPassword);
                result.put("학번", getUserNumber);
                result.put("이름",getUserName);

                a = a+1;
                writeNewUser(a,getUserPassword,getUserNumber,getUserName);

            }
        });

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

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

    //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"));
                } 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);
        }
    }

    private void writeNewUser(int userId, String userName, String userPassword, String userNumber) {
        user user = new user(userName, userPassword, userNumber);

        mDatabase.child("users").child(String.valueOf(userId)).setValue(user)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        // Write was successful!
                        Toast.makeText(MainActivity.this, "저장을 완료했습니다.", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        // Write failed
                        Toast.makeText(MainActivity.this, "저장을 실패했습니다.", Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private void readUser(){
        mDatabase.child("users").child("1").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                // Get Post object and use the values to update the UI
                if(dataSnapshot.getValue(user.class) != null){
                    user post = dataSnapshot.getValue(user.class);
                    Log.w("FireBaseData", "getData" + post.toString());
                } else {
                    Toast.makeText(MainActivity.this, "데이터 없음...", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // Getting Post failed, log a message
                Log.w("FireBaseData", "loadPost:onCancelled", databaseError.toException());
            }
        });
    }








}

 

 

class 추가

 

 

<user.java>

package com.example.qrscan;

public class user {

    public String userName;
    public String userNumber;
    public String userPassword;

    public user() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public user(String userName, String userNumber, String userPassword) {
        this.userName = userName;
        this.userNumber = userNumber;
        this.userPassword = userPassword;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserNumber() {
        return userNumber;
    }

    public void setUserNumber(String userNumber) {
        this.userNumber = userNumber;
    }
    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    @Override
    public String toString() {
        return "user{" +
                "userPassword ='" + userPassword + '\'' +
                ", userNumber ='" + userNumber + '\'' +
                ", userName ='" + userName + '\'' +
                '}';
    }
}

 

 

<activity_main.xml>

<?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:paddingBottom="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="50dp"
    android:paddingTop="50dp"
    tools:context="MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="vertical">



        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="학번" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/textViewName"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="학과" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/textViewPassword"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="이름" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/textViewResult"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />

    </LinearLayout>

    <Button
        android:text="SCAN QR CODE"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="12dp"
        android:id="@+id/buttonScan" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="163dp"
        android:text="저장하기" />


</RelativeLayout>

 

 

 

 

참고 글 :  (QR 스캔) m.blog.naver.com/cosmosjs/220937443111