Wednesday, March 6, 2019

Tutorial Membuat Aplikasi Barcode Generator dengan Android Studio

Barcode Generator
Barcode Generator
Halo sobat 48😁 kali ini admin akan membagikan sebuah tutorial dengan tema Tutorial Membuat Aplikasi Barcode Generator dengan Android Studio. Untuk WhatsApp Mod saya skip dulu ya gan😂. Oh ya, aplikasi Barcode Generator ini berfungsi bisa untuk Scan Barcode, membuat QR code dan membuat Barcode. Kalian cukup memilih Tab yang ada untuk membuka menu-menu tersebut.

VIDEO PREVIEW:

Gimana setelah melihat vide preview diatas? Untuk SOURCE CODE kalian bisa download DISINI. Apa kalian tertarik untuk membuatnya sendiri? Kalau ya, berikut admin akan jelaskan langkah-langkah untuk membuat Aplikasi Barcode Generator:

1. Buat Project Baru
  • Pastikan kalian sudah instal Android Studio
  • Buat Project baru, disini saya memberi nama Barcode Generator
2. Tambahkan Gradle


    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'me.dm7.barcodescanner:zbar:1.9.8'
    implementation 'me.dm7.barcodescanner:zxing:1.9.8'

3. Buat activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@color/colorPrimary"
        android:foreground="?android:attr/selectableItemBackground"
        app:itemBackground="@color/colorPrimary"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"
        app:menu="@menu/menu_bottom" />

<RelativeLayout>

4. Buat fragment_custom_dialog.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:padding="10dp">

        <TextView
            android:id="@+id/heading"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Scanned Item"
            android:textColor="#000"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/editTextNewContent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/heading"
            android:layout_marginTop="20dp"
            android:background="@null"
            android:editable="false"
            android:focusable="false"
            android:lines="6"
            android:textColor="#000" />

        <TextView
            android:id="@+id/action_ok"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_marginRight="20dp"
            android:text="Ok"
            android:textColor="#33bbff"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/action_cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_marginRight="20dp"
            android:text="Cancel"
            android:textColor="#33bbff"
            android:textSize="18sp" />

    </RelativeLayout>

</RelativeLayout>

5. Buat fragment_generate_barcode.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:text="Generate Barcode"
        android:textSize="20sp"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/textView"
        android:fillViewport="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <RelativeLayout
                android:id="@+id/inputLayout"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_margin="20dp"
                android:background="@drawable/input">

                <EditText
                    android:id="@+id/inputText"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_centerHorizontal="true"
                    android:layout_centerVertical="true"
                    android:background="@android:color/transparent"
                    android:hint="Type here.."
                    android:imeOptions="actionDone"
                    android:inputType="text"
                    android:lines="1"
                    android:maxLines="1"
                    android:paddingStart="20dp"
                    android:paddingLeft="50dp" />

            </RelativeLayout>


            <ImageView
                android:id="@+id/outputBitmap"
                android:layout_width="match_parent"
                android:layout_height="280dp"
                android:layout_below="@+id/inputLayout"
                android:layout_marginTop="5dp"
                android:padding="10dp"
                android:scaleType="fitCenter"
                android:src="@drawable/ic_placeholder" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/outputBitmap"
                android:layout_marginRight="5dp"
                android:layout_marginTop="5dp"
                android:gravity="end"
                android:orientation="horizontal">

                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/save"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="20dp"
                    android:src="@drawable/ic_save"
                    app:elevation="3dp" />

                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/share"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="20dp"
                    android:src="@drawable/ic_share"
                    app:elevation="3dp" />

            </LinearLayout>

        </RelativeLayout>

    </ScrollView>

</RelativeLayout>

6. Buat fragment_generate_qrcode.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:text="Generate QR Code"
        android:textSize="20sp"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/textView"
        android:fillViewport="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <RelativeLayout
                android:id="@+id/inputLayout"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_margin="20dp"
                android:background="@drawable/input">

                <EditText
                    android:id="@+id/inputText"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_centerHorizontal="true"
                    android:layout_centerVertical="true"
                    android:background="@android:color/transparent"
                    android:hint="Type here.."
                    android:imeOptions="actionDone"
                    android:inputType="text"
                    android:lines="1"
                    android:maxLines="1"
                    android:paddingLeft="50dp"
                    android:paddingStart="20dp" />

            </RelativeLayout>


            <ImageView
                android:id="@+id/outputBitmap"
                android:layout_width="match_parent"
                android:layout_height="280dp"
                android:layout_below="@+id/inputLayout"
                android:layout_marginTop="5dp"
                android:padding="10dp"
                android:scaleType="fitCenter"
                android:src="@drawable/ic_placeholder" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/outputBitmap"
                android:layout_marginRight="5dp"
                android:layout_marginTop="5dp"
                android:gravity="end"
                android:orientation="horizontal">

                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/save"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="20dp"
                    android:src="@drawable/ic_save"
                    app:elevation="3dp" />

                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/share"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="20dp"
                    android:src="@drawable/ic_share"
                    app:elevation="3dp" />

            </LinearLayout>

        </RelativeLayout>

    </ScrollView>

</RelativeLayout>

7. Buat fragment_scan.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

8. Buat folder menu, dan isikan didalamnya menu_bottom.xml


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/navigation_scan"
        android:icon="@drawable/ic_scan"
        android:title="Scan" />

    <item
        android:id="@+id/navigation_generate_barcode"
        android:icon="@drawable/ic_generate"
        android:title="Barcode" />

    <item
        android:id="@+id/navigation_generate_qrcode"
        android:icon="@drawable/ic_generate"
        android:title="QR" />

</menu>

9. Buat MainActivity.java


package com.azhar.barcodegenerator;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

import com.azhar.barcodegenerator.fragments.GenerateBarcodeFragment;
import com.azhar.barcodegenerator.fragments.GenerateQRcodeFragment;
import com.azhar.barcodegenerator.fragments.ScanFragment;

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView mBottomNavigationView;

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

        mBottomNavigationView = findViewById(R.id.bottomNavigationView);
        mBottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content_frame, new ScanFragment());
        transaction.commit();
    }

    public static boolean hasPermissions(Context context, String... permissions) {
        if (context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    private void checkPermission() {
        int PERMISSION_ALL = 1;
        String[] PERMISSIONS = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        };

        if (!hasPermissions(this, PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
        }
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_scan:
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.content_frame, new ScanFragment());
                    transaction.commit();
                    return true;
                case R.id.navigation_generate_barcode:
                    FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();
                    transaction2.replace(R.id.content_frame, new GenerateBarcodeFragment());
                    transaction2.commit();
                    return true;
                case R.id.navigation_generate_qrcode:
                    FragmentTransaction transaction3 = getSupportFragmentManager().beginTransaction();
                    transaction3.replace(R.id.content_frame, new GenerateQRcodeFragment());
                    transaction3.commit();
                    return true;
            }
            return false;
        }
    };
}

10. Buat folder fragment lalu buat CustomDialogFragment.java, GenerateBarcodeFragment.java, GenerateQRcodeFragment.java, MessageDialogFragment.java dan ScanFragment.java


package com.azhar.barcodegenerator.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.azhar.barcodegenerator.R;

public class CustomDialogFragment extends DialogFragment {

    private TextView mActionOk, mActionCancel;
    private EditText editTextNewContent;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_custom_dialog, container, false);

        mActionCancel = view.findViewById(R.id.action_cancel);
        mActionOk = view.findViewById(R.id.action_ok);
        editTextNewContent = view.findViewById(R.id.editTextNewContent);

        if (getArguments() != null) {
            if (getArguments().containsKey("content")) {
                editTextNewContent.setText(getArguments().getString("content"));
            }
        }

        mActionCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getDialog().dismiss();
            }
        });

        mActionOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getDialog().dismiss();
            }
        });

        return view;
    }
}



package com.azhar.barcodegenerator.fragments;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.azhar.barcodegenerator.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;

public class GenerateBarcodeFragment extends Fragment {

    private EditText mInputText;
    private ImageView mImageView;
    private FloatingActionButton mSave;
    private Activity mActivity;
    private Bitmap generatedBitmap;
    private String fileName;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_generate_barcode, container, false);
        mActivity = getActivity();

        mInputText = view.findViewById(R.id.inputText);
        mImageView = view.findViewById(R.id.outputBitmap);
        mSave = view.findViewById(R.id.save);


        mInputText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() == 0) {
                    mImageView.setImageResource(R.drawable.ic_placeholder);
                } else {
                    generateBarcode(charSequence.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveImage(generatedBitmap);
            }
        });

        return view;
    }

    private void saveImage(Bitmap generatedBitmap) {
        FileOutputStream out = null;
        File file = new File(Environment.getExternalStorageDirectory().getPath(), "QRCodeBarcode");
        if (!file.exists()) {
            file.mkdirs();
        }
        if (fileName.contains("/")) {
            fileName = fileName.replace("/", "\\");
        }
        String filePath = (file.getAbsolutePath() + "/" + fileName + ".png");
        try {
            out = new FileOutputStream(filePath);
            generatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Toast.makeText(mActivity, "File saved at\n" + filePath, Toast.LENGTH_SHORT).show();
    }

    private void generateBarcode(String s) {
        fileName = s;
        MultiFormatWriter writer = new MultiFormatWriter();
        String finalData = Uri.encode(s);

        // Use 1 as the height of the matrix as this is a 1D Barcode.
        BitMatrix bm = null;
        try {
            bm = writer.encode(finalData, BarcodeFormat.CODE_128, 1080, 1);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        int bmWidth = bm.getWidth();

        Bitmap imageBitmap = Bitmap.createBitmap(bmWidth, 640, Bitmap.Config.ARGB_8888);

        for (int i = 0; i < bmWidth; i++) {
            // Paint columns of width 1
            int[] column = new int[640];
            Arrays.fill(column, bm.get(i, 0) ? Color.BLACK : Color.WHITE);
            imageBitmap.setPixels(column, 0, 1, i, 0, 1, 640);
        }

        generatedBitmap = imageBitmap;

        mImageView.setImageBitmap(imageBitmap);
    }
}



package com.azhar.barcodegenerator.fragments;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.azhar.barcodegenerator.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.io.File;
import java.io.FileOutputStream;

import static android.graphics.Color.BLACK;
import static android.graphics.Color.WHITE;

public class GenerateQRcodeFragment extends Fragment {

    private EditText mInputText;
    private ImageView mImageView;
    private FloatingActionButton mSave;
    private Activity mActivity;
    private Bitmap generatedBitmap;
    private String fileName;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_generate_qrcode, container, false);

        mActivity = getActivity();

        mInputText = view.findViewById(R.id.inputText);
        mImageView = view.findViewById(R.id.outputBitmap);
        mSave = view.findViewById(R.id.save);


        mInputText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() == 0) {
                    mImageView.setImageResource(R.drawable.ic_placeholder);
                } else {
                    try {
                        generateQRcode(charSequence.toString());
                    } catch (WriterException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveImage(generatedBitmap);
            }
        });

        return view;
    }

    private void generateQRcode(String s) throws WriterException {
        fileName = s;
        BitMatrix result;
        result = new MultiFormatWriter().encode(s, BarcodeFormat.QR_CODE, 1080, 1080, null);
        int w = result.getWidth();
        int h = result.getHeight();
        int[] pixels = new int[w * h];
        for (int y = 0; y < h; y++) {
            int offset = y * w;
            for (int x = 0; x < w; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, 1080, 0, 0, w, h);
        generatedBitmap = bitmap;
        mImageView.setImageBitmap(bitmap);
    }

    private void saveImage(Bitmap generatedBitmap) {
        FileOutputStream out = null;
        File file = new File(Environment.getExternalStorageDirectory().getPath(), "QRCodeBarcode");
        if (!file.exists()) {
            file.mkdirs();
        }
        if (fileName.contains("/")) {
            fileName = fileName.replace("/", "\\");
        }
        String filePath = (file.getAbsolutePath() + "/" + fileName + ".png");
        try {
            out = new FileOutputStream(filePath);
            generatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Toast.makeText(mActivity, "File saved at\n" + filePath, Toast.LENGTH_SHORT).show();
    }
}



package com.azhar.barcodegenerator.fragments;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

public class MessageDialogFragment extends DialogFragment {

    public interface MessageDialogListener {
        public void onDialogPositiveClick(DialogFragment dialog);
    }

    private String mTitle;
    private String mMessage;
    private MessageDialogListener mListener;

    public void onCreate(Bundle state) {
        super.onCreate(state);
        setRetainInstance(true);
    }

    public static MessageDialogFragment newInstance(String title, String message, MessageDialogListener listener) {
        MessageDialogFragment fragment = new MessageDialogFragment();
        fragment.mTitle = title;
        fragment.mMessage = message;
        fragment.mListener = listener;
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(mMessage)
                .setTitle(mTitle);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                if (mListener != null) {
                    mListener.onDialogPositiveClick(MessageDialogFragment.this);
                }
            }
        });

        return builder.create();
    }
}



package com.azhar.barcodegenerator.fragments;

import android.app.Activity;
import android.content.Context;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.azhar.barcodegenerator.R;

import java.util.ArrayList;
import java.util.List;

import me.dm7.barcodescanner.zbar.BarcodeFormat;
import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;

public class ScanFragment extends Fragment implements ZBarScannerView.ResultHandler, MessageDialogFragment.MessageDialogListener {

    private Activity mActivity;
    private Context mContext;
    private ZBarScannerView zBarScannerView;
    private boolean mFlash;
    private boolean mAutoFocus;
    private ArrayList mSelectedIndices;
    private int mCameraId = -1;
    private static final String FLASH_STATE = "FLASH_STATE";
    private static final String AUTO_FOCUS_STATE = "AUTO_FOCUS_STATE";
    private static final String SELECTED_FORMATS = "SELECTED_FORMATS";
    private static final String CAMERA_ID = "CAMERA_ID";
    private ViewGroup contentFrame;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();
        zBarScannerView = new ZBarScannerView(mActivity);
        setupFormats();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_scan, container, false);
        contentFrame = view.findViewById(R.id.content_frame);
        zBarScannerView = new ZBarScannerView(mActivity);
        if (savedInstanceState != null) {
            mFlash = savedInstanceState.getBoolean(FLASH_STATE, false);
            mAutoFocus = savedInstanceState.getBoolean(AUTO_FOCUS_STATE, true);
            mSelectedIndices = savedInstanceState.getIntegerArrayList(SELECTED_FORMATS);
            mCameraId = savedInstanceState.getInt(CAMERA_ID, -1);
        } else {
            mFlash = false;
            mAutoFocus = true;
            mSelectedIndices = null;
            mCameraId = -1;
        }
        setupFormats();
        contentFrame.addView(zBarScannerView);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        zBarScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
        zBarScannerView.startCamera(mCameraId);          // Start camera on resume
        zBarScannerView.setFlash(mFlash);
        zBarScannerView.setAutoFocus(mAutoFocus);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(FLASH_STATE, mFlash);
        outState.putBoolean(AUTO_FOCUS_STATE, mAutoFocus);
        outState.putIntegerArrayList(SELECTED_FORMATS, mSelectedIndices);
        outState.putInt(CAMERA_ID, mCameraId);
    }

    @Override
    public void onPause() {
        super.onPause();
        zBarScannerView.stopCamera(); // Stop camera on stop
        closeMessageDialog();
    }

    public void setupFormats() {
        List formats = new ArrayList();
        if (mSelectedIndices == null || mSelectedIndices.isEmpty()) {
            mSelectedIndices = new ArrayList();
            for (int i = 0; i < BarcodeFormat.ALL_FORMATS.size(); i++) {
                mSelectedIndices.add(i);
            }
        }

        for (int index : mSelectedIndices) {
            formats.add(BarcodeFormat.ALL_FORMATS.get(index));
        }
        if (zBarScannerView != null) {
            zBarScannerView.setFormats(formats);
        }
    }

    @Override
    public void handleResult(Result rawResult) {
        try {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(getActivity().getApplicationContext(), notification);
            r.play();
        } catch (Exception e) {
        }
        showMessageDialog(rawResult.getContents());
    }

    public void showMessageDialog(String message) {
        DialogFragment fragment = MessageDialogFragment.newInstance("Scan Results", message, this);
        fragment.show(getActivity().getSupportFragmentManager(), "scan_results");
    }

    public void closeMessageDialog() {
        closeDialog("scan_results");
    }

    public void closeDialog(String dialogName) {
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        DialogFragment fragment = (DialogFragment) fragmentManager.findFragmentByTag(dialogName);
        if (fragment != null) {
            fragment.dismiss();
        }
    }

    @Override
    public void onDialogPositiveClick(DialogFragment dialog) {
        // Resume the camera
        zBarScannerView.resumeCameraPreview(this);
    }
}


11. Ubah Android Manifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.azhar.barcodegenerator">

    <!-- camera permission -->
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

12. Untuk file yang kurang seperti icon drawable dan values (string, colors dan style) silahkan download melalui link Github saya DISINI.

13. Jika sudah selesai mengikuti langkah-langkah diatas, sekarang kalian Run di emulator bawaan Android Studio atau langsung ke Device kalian. Jika kalian mengalami error, silahkan ketik di kolom komentar, sebisa mungkin admin bantu😊.

Demikian informasi yang saya bagikan untuk kalian. Jangan lupa bagikan artikel ini ke teman-teman kalian agar ikut membaca Tutorial Membuat Aplikasi Barcode Generator dengan Android Studio ini. Subscribe juga di blog Rivaldi 48 ini agar kalian mendapatkan notifikasi saat Admin update artikel terbaru. Follow Instagram Admin @azhardvls_. Semoga kalian lebih nyaman dan mudah dalam mengakses Blog Rivaldi 48 dimanapun kalian berada. Terima Kasih...

9 comments

  1. mau nanya mas, kalau hasil scannya bisa gak ya ada pilihan direct langsung ke browser? mohon petunjuknya mas

    ReplyDelete
  2. mau nanya bro, itu databasenya bisa nggk pake mysql ?

    ReplyDelete
  3. Tutorial yang bagus gan, sangat membantu sekali. Mantap dah

    ReplyDelete
  4. Mas saya mau tanya kenapa saya mengalami eror saat di bagian <android.support.design.widget.BottomNavigationView ya? Dan Terima kasih sudah membuat tutorial yang sangat membantu untuk saya yang baru belajar

    ReplyDelete
  5. gans saya mau nanya itu tombol share codingannya apa, saya udah pake banyak kodingan tapi salah teruss

    ReplyDelete

Silahkan tinggalkan komentar jika Anda punya saran, kritik, atau pertanyaan seputar topik pembahasan. Gunakan bahasa yang bijak dan santun. Terima Kasih.
EmoticonEmoticon