com.jamsuni.jamsunicodescan.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.jamsuni.jamsunicodescan.MainActivity.java

Source

package com.jamsuni.jamsunicodescan;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
import com.jamsuni.jamsunicodescan.barcode.MaterialBarcodeScanner;
import com.jamsuni.jamsunicodescan.barcode.MaterialBarcodeScannerBuilder;
import com.jamsuni.jamsunicodescan.common.Utils;
import com.jamsuni.jamsunicodescan.data.BarcodeData;
import com.jamsuni.jamsunicodescan.data.BookInfo;
import com.jamsuni.jamsunicodescan.data.ProductInfo;
import com.jamsuni.jamsunicodescan.database.DbOpenHelper;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    protected static final int MY_PERMISSIONS_REQUEST = 101;

    private static final int RC_BARCODE_CAPTURE = 9001;
    private static final int WEB_CONTENT_VIEW = 9002;
    private static final int HISTORY_CONTENT_VIEW = 9003;
    //private CheckBox autoFocus;
    //private CheckBox useFlash;
    private TextView barcodeValue;
    private String linkURL = "";
    private String urlContent = "";
    private String webTitle = "";
    private String contentString = "";
    private int barcodeType = -1;
    private int barcodeFormat = -1;
    private String valueString;
    private BookInfo mBookInfo;
    private ProductInfo mProductInfo;

    private DbOpenHelper mDbOpenHelper;

    String clientId = "MBu8h92NtyBb89KFwBR8";
    String clientSecret = "XwHWLYm0aD";

    public List<BarcodeData> barcodeItems = new ArrayList<>();

    private static final String TAG = "MainActivity";
    GetBookInfoTask getBookInfoTask;
    GetProductInfoTask getProductInfoTask;

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

        //autoFocus = (CheckBox) findViewById(R.id.auto_focus);
        //useFlash = (CheckBox) findViewById(R.id.use_flash);
        barcodeValue = (TextView) findViewById(R.id.tvScanData);
        //barcodeFormat = (TextView)findViewById(R.id.tvCodeFormat);

        //autoFocus.setChecked(true);

        findViewById(R.id.btnScan).setOnClickListener(this);
        findViewById(R.id.btnHistory).setOnClickListener(this);
        findViewById(R.id.btnContentView).setOnClickListener(this);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
                .detectNetwork().penaltyLog().build());

        //checkPermissionsForAboveMarshmallow();
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnScan) {
            //testTTS("13   ? ?    ??  ?  ? ? ??  ?  ? ?\n");

            Button btContent = (Button) findViewById(R.id.btnContentView);
            btContent.setText("");
            btContent.setVisibility(View.GONE);
            contentString = "";

            barcodeValue.setText("");
            barcodeValue.setVisibility(View.VISIBLE);

            LinearLayout llBookInfo = (LinearLayout) findViewById(R.id.llBookInfo);
            llBookInfo.setVisibility(View.GONE);
            LinearLayout llProductInfo = (LinearLayout) findViewById(R.id.llProductInfo);
            llProductInfo.setVisibility(View.GONE);

            startScan();
            /*
            // launch barcode activity.
            Intent intent = new Intent(this, BarcodeCaptureActivity.class);
            intent.putExtra(BarcodeCaptureActivity.AutoFocus, autoFocus.isChecked());
            intent.putExtra(BarcodeCaptureActivity.UseFlash, useFlash.isChecked());
                
            startActivityForResult(intent, RC_BARCODE_CAPTURE);
            */

        }
        if (v.getId() == R.id.btnHistory) {
            Intent intent = new Intent(this, HistoryActivity.class);
            startActivityForResult(intent, HISTORY_CONTENT_VIEW);
        }
        if (v.getId() == R.id.btnContentView) {
            goURL();
        }

    }

    private void startScan() {
        /**
         * Build a new MaterialBarcodeScanner
         */
        final MaterialBarcodeScanner materialBarcodeScanner = new MaterialBarcodeScannerBuilder()
                .withActivity(MainActivity.this).withEnableAutoFocus(true).withBleepEnabled(true)
                .withBackfacingCamera().withCenterTracker().withText("Scanning...")
                .withResultListener(new MaterialBarcodeScanner.OnResultListener() {
                    @Override
                    public void onResult(Barcode barcode) {
                        displayBarcodeData(barcode);
                        Log.d(TAG, "Barcode read: " + barcode.displayValue);
                    }
                }).build();
        materialBarcodeScanner.startScan();
    }

    /*
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //   
    if (requestCode == RC_BARCODE_CAPTURE) {
        if (resultCode == CommonStatusCodes.SUCCESS) {
            if (data != null) {
        
        
                Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject);
                displayBarcodeData(barcode);
        
                Log.d(TAG, "Barcode read: " + barcode.displayValue);
            } else {
        
                Log.d(TAG, "No barcode captured, intent data is null");
            }
        }
    }
    else {
        super.onActivityResult(requestCode, resultCode, data);
    }
        }
    */
    public void displayBarcodeData(Barcode barcode) {

        int nFormat = barcode.format;
        int valueFormat = barcode.valueFormat;
        barcodeType = valueFormat;
        barcodeFormat = nFormat;
        valueString = barcode.displayValue;

        TextView tvFormat = (TextView) findViewById(R.id.tvFormat);
        TextView tvType = (TextView) findViewById(R.id.tvType);

        tvFormat.setText(getCodeFormatName(nFormat));
        tvType.setText(getValueFormatName(valueFormat));

        //   
        long now = System.currentTimeMillis();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
        Date date = new Date(now);
        String strDate = dateFormat.format(date);
        contentString = "";

        //??? ?(? Context) ? 
        mDbOpenHelper = new DbOpenHelper(this);
        try {
            mDbOpenHelper.open();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        barcodeValue.setVisibility(View.VISIBLE);

        switch (valueFormat) {
        case 1: /* Contact */
            displayBarcodeContact(barcode);
            mDbOpenHelper.insertColumn(barcode.format, barcodeType, barcodeValue.getText().toString(), "", "", "",
                    null, strDate);
            mDbOpenHelper.close();
            break;
        case 10: /* GEO */
            displayBarcodeGeo(barcode);
            mDbOpenHelper.insertColumn(barcode.format, barcodeType, barcodeValue.getText().toString(), "", "", "",
                    null, strDate);
            mDbOpenHelper.close();
            break;
        case 11: /* Calendar */
            displayBarcodeCalendar(barcode);
            mDbOpenHelper.insertColumn(barcode.format, barcodeType, barcodeValue.getText().toString(), "", "", "",
                    null, strDate);
            mDbOpenHelper.close();
            break;
        default:
            displayBarcodeText(barcode);
        }

    }

    public void displayBarcodeText(Barcode barcode) {
        Button btContent = (Button) findViewById(R.id.btnContentView);

        //ISBN ( )
        if (barcodeType == 3) {
            btContent.setVisibility(View.VISIBLE);
            btContent.setText("?  (?)");
            urlContent = barcode.displayValue;
            linkURL = "http://book.naver.com/search/search.nhn?publishStartDay=&publishEndDay=&categoryId=&serviceSm=advbook.basic&ic=service.summary&title=&author=&pblisher=&isbn="
                    + urlContent
                    + "&toc=&subject=&cate1Depth=&cate2Depth=&cate3Depth=&cate4Depth=&publishStartYear=&publishStartMonth=&publishEndYear=&publishEndMonth=&x=20&y=13";
            webTitle = "?  (?)";

            /////
            // ? API  
            getBookInfoTask = new GetBookInfoTask();
            getBookInfoTask.execute(urlContent);

        }
        // Product
        else if (barcodeType == 5) {
            btContent.setVisibility(View.VISIBLE);
            btContent.setText("  (www.koreannet.or.kr)");
            urlContent = barcode.displayValue;
            linkURL = "http://www.koreannet.or.kr/home/hpisSrchGtin.gs1?gtin=" + urlContent;
            webTitle = "  ";
            //barcodeValue.setText(barcode.displayValue);
            //   
            getProductInfoTask = new GetProductInfoTask();
            getProductInfoTask.execute(urlContent);
        } else {
            //   
            long now = System.currentTimeMillis();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                    java.util.Locale.getDefault());
            Date date = new Date(now);
            String strDate = dateFormat.format(date);
            String imageUrl = "";

            // URL
            if (barcodeType == 8) {
                btContent.setVisibility(View.VISIBLE);
                btContent.setText("URL ??");
                linkURL = barcode.displayValue;
                urlContent = "";
                webTitle = "URL ?";
                barcodeValue.setText(barcode.displayValue);
            } else {
                btContent.setText("");
                btContent.setVisibility(View.GONE);
                barcodeValue.setText(barcode.displayValue);
            }

            mDbOpenHelper.insertColumn(barcode.format, barcodeType, barcode.displayValue, contentString, imageUrl,
                    linkURL, null, strDate);
            mDbOpenHelper.close();
        }

    }

    public void goURL() {
        Intent intent = new Intent(this, WebViewActivity.class);
        String title;
        intent.putExtra("URL", linkURL);
        intent.putExtra("TITLE", webTitle);
        intent.putExtra("URLCONTENT", urlContent);

        startActivityForResult(intent, WEB_CONTENT_VIEW);
    }

    //Geo
    public void displayBarcodeGeo(Barcode barcode) {
        double lat = barcode.geoPoint.lat;
        double lng = barcode.geoPoint.lng;

        String msg = String.format("? : %f\n? : %f", lat, lng);
        barcodeValue.setText(msg);
    }

    // Calendar
    public void displayBarcodeCalendar(Barcode barcode) {
        String summary = barcode.calendarEvent.summary;
        String description = barcode.calendarEvent.description;
        String location = barcode.calendarEvent.location;
        String startTime;
        if (barcode.calendarEvent.start.hours < 0)
            startTime = String.format("%4d-%02d-%02d", barcode.calendarEvent.start.year,
                    barcode.calendarEvent.start.month, barcode.calendarEvent.start.day);
        else
            startTime = String.format("%4d-%02d-%02d %02d:%02d:%02d", barcode.calendarEvent.start.year,
                    barcode.calendarEvent.start.month, barcode.calendarEvent.start.day,
                    barcode.calendarEvent.start.hours, barcode.calendarEvent.start.minutes,
                    barcode.calendarEvent.start.seconds);

        String endTime;
        if (barcode.calendarEvent.end.hours < 0)
            endTime = String.format("%4d-%02d-%02d", barcode.calendarEvent.end.year,
                    barcode.calendarEvent.end.month, barcode.calendarEvent.end.day);
        else
            endTime = String.format("%4d-%02d-%02d %02d:%02d:%02d", barcode.calendarEvent.end.year,
                    barcode.calendarEvent.end.month, barcode.calendarEvent.end.day, barcode.calendarEvent.end.hours,
                    barcode.calendarEvent.end.minutes, barcode.calendarEvent.end.seconds);

        String msg = String.format(" : %s\n : %s\n : %s\n : %s\n : %s", summary,
                location, description, startTime, endTime);
        barcodeValue.setText(msg);
    }

    // vCard 
    public void displayBarcodeContact(Barcode barcode) {

        String name = barcode.contactInfo.name.first + " " + barcode.contactInfo.name.middle + " "
                + barcode.contactInfo.name.last;
        //barcode.contactInfo.name.formattedName//
        barcodeValue.setText("Name : " + name);

        for (int i = 0; i < barcode.contactInfo.phones.length; i++) {
            String number = barcode.contactInfo.phones[i].number;
            int type = barcode.contactInfo.phones[i].type;
            String typeName = "";
            switch (type) {
            case 0:
                typeName = "Phone : ";
                break;
            case 1:
                typeName = "Work : ";
                break;
            case 2:
                typeName = "Home : ";
                break;
            case 3:
                typeName = "Fax : ";
                break;
            case 4:
                typeName = "Mobile : ";
                break;
            }

            String msgTemp = barcodeValue.getText().toString();
            String numberString = typeName + number;
            barcodeValue.setText(msgTemp + "\n" + numberString);

        }
        String email = barcode.contactInfo.emails[0].address;
        if (!email.isEmpty()) {
            String msgTemp = barcodeValue.getText().toString();
            barcodeValue.setText(msgTemp + "\nEmail : " + email);
        }
        String url = barcode.contactInfo.urls[0].toString();
        int nUrl = barcode.contactInfo.urls.length;
        if (!url.isEmpty()) {
            String msgTemp = barcodeValue.getText().toString();
            barcodeValue.setText(msgTemp + "\nURL : " + url);
        }

        String company = barcode.contactInfo.organization;
        if (!company.isEmpty()) {
            String msgTemp2 = barcodeValue.getText().toString();
            barcodeValue.setText(msgTemp2 + "\n? : " + company);
        }

        String title = barcode.contactInfo.title;
        if (!title.isEmpty()) {
            String msgTemp4 = barcodeValue.getText().toString();
            barcodeValue.setText(msgTemp4 + "\n? : " + title);
        }

        String msgTemp3 = barcodeValue.getText().toString();
        String address = "";
        for (int index = 0; index < barcode.contactInfo.addresses.length; index++) {
            int nType = barcode.contactInfo.addresses[index].type;
            String typeName = "";
            switch (nType) {
            case 0:
                typeName = " : ";
                break;
            case 1:
                typeName = "Work : ";
                break;
            case 2:
                typeName = "Home : ";
                break;
            }
            String addrString = typeName + barcode.contactInfo.addresses[index].addressLines[0];
            if (addrString.isEmpty())
                continue;
            ;
            address = address + addrString + "\n";
        }
        barcodeValue.setText(msgTemp3 + "\n" + address);
    }

    public String getCodeFormatName(int nFormat) {
        String formatName = "";

        switch (nFormat) {
        case 0:
            formatName = "ALL Formats";
            break;
        case 1:
            formatName = "CODE_128";
            break;
        case 2:
            formatName = "CODE_39";
            break;
        case 4:
            formatName = "CODE_93";
            break;
        case 8:
            formatName = "CODABAR";
            break;
        case 16:
            formatName = "DATA_MATRIX";
            break;
        case 32:
            formatName = "EAN_13";
            break;
        case 64:
            formatName = "EAN_8";
            break;
        case 128:
            formatName = "ITF";
            break;
        case 256:
            formatName = "QR_CODE";
            break;
        case 512:
            formatName = "UPC_A";
            break;
        case 1024:
            formatName = "UPC_E";
            break;
        case 2048:
            formatName = "PDF417";
            break;
        case 4096:
            formatName = "AZTEC";
            break;

        }

        return formatName;
    }

    public String getValueFormatName(int nFormat) {
        String formatName = "";
        switch (nFormat) {
        case 1:
            formatName = "Contact Info";
            break;
        case 2:
            formatName = "EMAIL";
            break;
        case 3:
            formatName = "ISBN";
            break;
        case 4:
            formatName = "PHONE";
            break;
        case 5:
            formatName = "Product";
            break;
        case 6:
            formatName = "SMS";
            break;
        case 7:
            formatName = "Text";
            break;
        case 8:
            formatName = "URL";
            break;
        case 9:
            formatName = "WIFI";
            break;
        case 10:
            formatName = "GEO";
            break;
        case 11:
            formatName = "Calendar Event";
            break;
        case 12:
            formatName = "Driver License";
            break;

        }

        return formatName;
    }

    // ?? ? ?? Task
    private class GetBookInfoTask extends AsyncTask<String, Float, Integer> {

        private String ISBN;
        private ProgressDialog dialog = null;
        private Bitmap bitmap = null;

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

            dialog = ProgressDialog.show(MainActivity.this, "", getString(R.string.book_searching), true);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);

            String displayString = "";
            String imageUrl = "";
            if (mBookInfo == null) {
                displayString = ISBN;
            } else {
                mBookInfo.setIsbn(ISBN);
                displayString = " : " + mBookInfo.getTitle() + "\n? : " + mBookInfo.getAuthor()
                        + "\n? : " + mBookInfo.getPublisher() + "\n : " + mBookInfo.getPrice()
                        + "\nISBN : " + ISBN;
                imageUrl = mBookInfo.getImage();
                displayBookInfo(mBookInfo);

                if (bitmap != null) {
                    ImageView imageView = (ImageView) findViewById(R.id.ivBook);
                    imageView.setImageBitmap(bitmap);
                }

                if (mBookInfo.getLink() != "")
                    linkURL = mBookInfo.getLink();
                else
                    linkURL = "http://book.naver.com/search/search.nhn?serviceSm=advbook.basic&isbn=" + ISBN;
            }

            contentString = displayString;

            //barcodeValue.setText(contentString);

            //   
            long now = System.currentTimeMillis();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                    java.util.Locale.getDefault());
            Date date = new Date(now);
            String strDate = dateFormat.format(date);
            byte[] imageData = null;
            if (bitmap != null)
                imageData = Utils.bitmapToByteArray(bitmap);

            mDbOpenHelper.insertColumn(barcodeFormat, barcodeType, valueString, contentString, imageUrl, linkURL,
                    imageData, strDate);
            mDbOpenHelper.close();

            dialog.dismiss();

        }

        @Override
        protected Integer doInBackground(String... isbns) {
            for (String isbn : isbns) {
                ISBN = isbn;
                mBookInfo = getBookName(isbn);
                String url = mBookInfo.getImage();
                if ((url != null) && (!url.isEmpty()))
                    bitmap = Utils.downloadImageFile(url);
            }

            return null;
        }
    }

    // ? OpenApi ? 
    public BookInfo getBookName(String isbn) {

        String apiURL = "https://openapi.naver.com/v1/search/book_adv.json?d_isbn=" + isbn;

        BookInfo bookInfo = new BookInfo();

        try {
            URL url = new URL(apiURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");

            con.setRequestProperty("X-Naver-Client-Id", clientId);
            con.setRequestProperty("X-Naver-Client-Secret", clientSecret);
            int responseCode = con.getResponseCode();
            BufferedReader br;
            if (responseCode == 200) { // ? 
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            } else { // ? ?
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
            System.out.println(response.toString());
            JSONObject jsonObject = new JSONObject(response.toString());
            JSONArray itemArray = jsonObject.getJSONArray("items");

            for (int i = 0; i < itemArray.length(); i++) {
                JSONObject object = itemArray.getJSONObject(i);
                bookInfo.setTitle(object.getString("title"));
                bookInfo.setIsbn(object.getString("isbn"));
                bookInfo.setAuthor(object.getString("author"));
                bookInfo.setImage(object.getString("image"));
                bookInfo.setPublisher(object.getString("publisher"));
                bookInfo.setDesc(object.getString("description"));
                bookInfo.setPubdate(object.getString("pubdate"));
                bookInfo.setLink(object.getString("link"));
                int nPrice = object.getInt("price");
                bookInfo.setPrice(String.valueOf(nPrice));
            }
        } catch (Exception e) {
            System.out.println(e);
        }

        return bookInfo;
    }

    // ? OpenApi ? 
    public void testTTS(String msg) {

        String apiURL = "https://openapi.naver.com/v1/voice/tts.bin";

        BookInfo bookInfo = new BookInfo();

        try {
            String text = URLEncoder.encode(msg, "UTF-8");

            URL url = new URL(apiURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");

            con.setRequestProperty("X-Naver-Client-Id", clientId);
            con.setRequestProperty("X-Naver-Client-Secret", clientSecret);

            // post request
            String postParams = "speaker=mijin&speed=0&text=" + text;
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(postParams);
            wr.flush();
            wr.close();
            int responseCode = con.getResponseCode();
            BufferedReader br;
            if (responseCode == 200) { // ? 
                InputStream is = con.getInputStream();
                int read = 0;
                byte[] bytes = new byte[1024];
                // ? ? mp3 ? ?
                String tempname = Long.valueOf(new Date().getTime()).toString();
                File f = new File(Environment.getExternalStorageDirectory() + "/" + tempname + ".mp3");
                f.createNewFile();
                OutputStream outputStream = new FileOutputStream(f);
                while ((read = is.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                is.close();
            } else { // ? ?
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = br.readLine()) != null) {
                    response.append(inputLine);
                }
                br.close();
                System.out.println(response.toString());
            }

        } catch (Exception e) {
            System.out.println(e);
        }

        return;
    }

    public void displayBookInfo(BookInfo bookInfo) {

        barcodeValue.setVisibility(View.GONE);

        LinearLayout llBookInfo = (LinearLayout) findViewById(R.id.llBookInfo);
        llBookInfo.setVisibility(View.VISIBLE);
        TextView tvTitle = (TextView) findViewById(R.id.tvBookTitle);
        TextView tvAuthor = (TextView) findViewById(R.id.tvAuthor);
        TextView tvPublisher = (TextView) findViewById(R.id.tvPublisher);
        TextView tvPrice = (TextView) findViewById(R.id.tvPrice);
        TextView tvISBN = (TextView) findViewById(R.id.tvISBN);
        TextView tvPubDate = (TextView) findViewById(R.id.tvPubDate);
        TextView tvDesc = (TextView) findViewById(R.id.tvDesc);
        tvTitle.setText(bookInfo.getTitle());
        tvAuthor.setText(bookInfo.getAuthor());
        tvPublisher.setText(bookInfo.getPublisher());
        tvPrice.setText(bookInfo.getPrice());
        tvPubDate.setText(bookInfo.getPubdate());
        tvISBN.setText(bookInfo.getIsbn());
        tvDesc.setText(bookInfo.getDesc());
    }

    //   TASK
    private class GetProductInfoTask extends AsyncTask<String, Float, Integer> {
        private String Code;
        private ProgressDialog dialog = null;
        private Bitmap bitmap = null;

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

            dialog = ProgressDialog.show(MainActivity.this, "", "  ...", true);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);

            String displayString = "";
            String imageUrl = "";
            TextView tvDesc = (TextView) findViewById(R.id.tvProductDesc);

            if (mProductInfo == null) {
                displayString = Code;
                barcodeValue.setText(displayString);
            } else {
                mProductInfo.setCode(Code);
                if ((mProductInfo.getTitle() == null) || (mProductInfo.getTitle().isEmpty())) {
                    displayString = Code;
                    barcodeValue.setText(displayString);
                } else {
                    displayString = mProductInfo.getTitle();
                    imageUrl = mProductInfo.getImage();
                    displayProductInfo(mProductInfo);

                    if (bitmap != null) {
                        ImageView imageView = (ImageView) findViewById(R.id.ivProduct);
                        imageView.setImageBitmap(bitmap);
                    }
                }

            }

            contentString = displayString;
            //barcodeValue.setText(contentString);

            //   
            long now = System.currentTimeMillis();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                    java.util.Locale.getDefault());
            Date date = new Date(now);
            String strDate = dateFormat.format(date);
            byte[] imageData = null;
            if (bitmap != null)
                imageData = Utils.bitmapToByteArray(bitmap);

            mDbOpenHelper.insertColumn(barcodeFormat, barcodeType, valueString, contentString, imageUrl, linkURL,
                    imageData, strDate);
            mDbOpenHelper.close();

            dialog.dismiss();

        }

        @Override
        protected Integer doInBackground(String... codes) {
            for (String code : codes) {
                Code = code;

                mProductInfo = getProductInfo(code);
                String url = mProductInfo.getImage();
                if ((url != null) && (!url.isEmpty()))
                    bitmap = Utils.downloadImageFile(url);
            }

            return null;
        }
    }

    public ProductInfo getProductInfo(String code) {
        String apiURL = "http://www.koreannet.or.kr/home/hpisSrchGtin.gs1?gtin=" + code;

        ProductInfo productInfo = new ProductInfo();

        Source source;
        try {
            URL url = new URL(apiURL);
            source = new Source(url);

            // 
            List<Element> listDiv = source.getAllElements(HTMLElementName.DIV);
            for (int i = 0; i < listDiv.size(); i++) {
                Element element = listDiv.get(i);
                String attributeValue = element.getAttributeValue("class");
                if (attributeValue != null) {
                    // class ? productTit ?
                    if (attributeValue.equalsIgnoreCase("productTit")) {

                        String title = element.getContent().getTextExtractor().toString();
                        productInfo.setTitle(title);

                    }
                }
            }

            // ??
            List<Element> listImg = source.getAllElements(HTMLElementName.IMG);
            for (int i = 0; i < listImg.size(); i++) {
                Element element = listImg.get(i);
                String attributeValue = element.getAttributeValue("id");
                //detailImage
                if (attributeValue != null) {
                    if (attributeValue.equalsIgnoreCase("detailImage")) {

                        String imgUrl = element.getAttributeValue("src");
                        if (imgUrl != "")
                            productInfo.setImage(imgUrl);

                    }

                }
            }

            //  
            List<Element> listDD = source.getAllElements(HTMLElementName.DD);
            for (int i = 0; i < listDD.size(); i++) {
                Element element = listDD.get(i);
                String attributeValue = element.getAttributeValue("class");
                if (attributeValue != null) {
                    // class ? description ?
                    if (attributeValue.equalsIgnoreCase("description")) {

                        String desc = element.getContent().getTextExtractor().toString();
                        productInfo.setDesc(desc);

                    }

                }
            }

            // ?? 
            List<Element> listDD2 = source.getAllElements(HTMLElementName.DD);
            for (int i = 0; i < listDD2.size(); i++) {
                Element element = listDD2.get(i);
                String attributeValue = element.getAttributeValue("class");
                if (attributeValue != null) {
                    // class ? description ?
                    if (attributeValue.equalsIgnoreCase("lis")) {
                        String content = element.getContent().getTextExtractor().toString();
                        switch (i) {
                        case 3:
                            productInfo.setManufacturer(content);
                            break;
                        case 4:
                            productInfo.setPubdate(content);
                            break;
                        case 5:
                            productInfo.setSeller(content);
                            break;
                        case 8:
                            productInfo.setLink(content);
                            break;
                        }

                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return productInfo;
    }

    public void displayProductInfo(ProductInfo productInfo) {

        barcodeValue.setVisibility(View.GONE);

        LinearLayout llProductInfo = (LinearLayout) findViewById(R.id.llProductInfo);
        llProductInfo.setVisibility(View.VISIBLE);

        TextView tvTitle = (TextView) findViewById(R.id.tvProdutTitle);
        TextView tvManu = (TextView) findViewById(R.id.tvManufacturer);
        TextView tvSeller = (TextView) findViewById(R.id.tvSeller);
        TextView tvPubDate = (TextView) findViewById(R.id.tvProductPubDate);
        TextView tvDesc = (TextView) findViewById(R.id.tvProductDesc);
        tvTitle.setText(productInfo.getTitle());
        tvManu.setText(productInfo.getManufacturer());
        tvSeller.setText(productInfo.getSeller());
        tvPubDate.setText(productInfo.getPubdate());
        tvDesc.setText(productInfo.getDesc());
    }

    public void checkPermissionsForAboveMarshmallow() {
        List<String> listReqPermission = new ArrayList<>();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                listReqPermission.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
            }

            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                listReqPermission.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }

            if (listReqPermission.size() > 0) {
                ActivityCompat.requestPermissions(this,
                        listReqPermission.toArray(new String[listReqPermission.size()]), MY_PERMISSIONS_REQUEST);
            } else {
                // ?  
                return;
            }

        } else {
            // ?  
            return;

        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {

        case MY_PERMISSIONS_REQUEST: {

            // ? ?? 
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // ?  
                return;
            }
            // ? ? ? 
            else {
                Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
                finish();

            }
        }
        }
    }
}