Monday, April 15, 2019

Tutorial Membuat Aplikasi Scan Barcode dan QR Code dengan Android Studio

Aplikasi Scan Barcode dan QR Code
Aplikasi Scan Barcode dan QR Code
Halo sobat 48😁 kali ini saya akan membagikan artikel yang membahas tentang Tutorial Membuat Aplikasi Scan Barcode dan QR Code dengan Android Studio. Kalau sebelumnya saya pernah membuatkan Tutorial Membuat Aplikasi Barcode Generator dengan Android Studio, tetapi hanya bisa untuk Scan dan Create Barcode saja. Untuk yang kali ini bisa Scan Barcode dan QR Code juga, tetapi tidak bisa Create Barcode😂 mungkin di lain kesempatan akan saya buatkan semuanya jadi satu, pantau terus ya blog saya ini dengan cara berlangganan di kolom subscribe yang tersedia.

Jika kalian ingin mencoba membuat aplikasi menggunakan sample ini, berikut saya berikan Video Preview-nya:

Jangan lupa subscribe Channel Youtube saya juga ya Azhar Rivaldi, karena disana ada banyak tutorial-tutorial untuk membuat aplikasi lainnya. Adapun fitur yang tersedia di Aplikasi Scan Barcode dan QR Code ini, antara lain:
  1. Scan Barcode dan QR Code
  2. Use SQLite for save data
  3. Tell Code Type (hasil scan akan menunjukkan tipe kode)
  4. Swipe to delete (hapus hasil scan dengan cara geser perlahan ke kiri atau kanan)
  5. On/Off Beep Sound (suara saat scan bisa kalian On/Off)
  6. On/Off Front Camera Scan (bisa scan dengan kamera depan)
  7. Clear All Data (bisa hapus semua hasil scan)
  8. Share Code (kode hasil scan bisa kalian bagikan)
  9. Copy Code (kode hasil scan bisa kalian copy)
  10. Menu About
Jika kalian ingin SOURCE CODE Aplikasi Scan Barcode dan QR Code ini, silahkan download di Github saya DISINI. Tetapi jika kalian ingin tahu cara mengaplikasikannya, silahkan lanjut baca artikel ini sampai selesai😄

Oke langsung saja tanpa basa-basi lagi kita langsung ke langkah pertama :

1. Buat project baru di Android Studio dengan cara klik File ⇒ Project Baru. Ketika diminta untuk memilih Default Activity, pilih Empty Activity dan klik next. Untuk minSDK, disini saya set API 15 ya.

2. Buka build.gradle dan ubah menjadi seperti ini :


dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.journeyapps:zxing-android-embedded:3.4.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'nl.qbusict:cupboard:2.2.0'
    implementation 'com.android.support:preference-v7:28.0.0'
    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'
}

3. Buka AndroidManifest.xml dan ubah menjadi seperti ini :


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

    <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"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

4. Ubah isi MainActivity.java dan activity_main.xml, buat juga content_main.xml dan navigation_bar.xml seperti ini :


package com.azhar.barcodeqr;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.PreferenceManager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.azhar.barcodeqr.adapter.Code;
import com.azhar.barcodeqr.adapter.ListItem;
import com.azhar.barcodeqr.adapter.MyAdapter;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

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

import nl.qbusict.cupboard.QueryResultIterable;

import static nl.qbusict.cupboard.CupboardFactory.cupboard;

/**
 * Created by Azhar Rivaldi on 11/04/2019.
 */

public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    IntentIntegrator scan;
    RecyclerView recyclerView;
    RecyclerView.Adapter adapter;
    List listItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final PracticeDatabaseHelper dbHelper = new PracticeDatabaseHelper(this);
        final SQLiteDatabase db = dbHelper.getWritableDatabase();

        PreferenceManager.setDefaultValues(this, R.xml.settings, false);
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        Boolean beep = sharedPref.getBoolean("beep", true);
        Boolean frontCamera = sharedPref.getBoolean("frontCamera", false);
        int camId;
        if (frontCamera == false)
            camId = 0;
        else
            camId = 1;
        sharedPref.registerOnSharedPreferenceChangeListener(this);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        listItems = new ArrayList<>();
        adapter = new MyAdapter(listItems, this);
        recyclerView.setAdapter(adapter);
        CardView cardView = (CardView) findViewById(R.id.cardView);

        Cursor codes = cupboard().withDatabase(db).query(Code.class).orderBy("_id DESC").getCursor();
        try {
            // Iterate Bunnys
            QueryResultIterable itr = cupboard().withCursor(codes).iterate(Code.class);
            for (Code bunny : itr) {
                // do something with bunny
                ListItem listItem = new ListItem(bunny._id, bunny.name, bunny.type);
                listItems.add(listItem);
                adapter = new MyAdapter(listItems, this);
                recyclerView.setAdapter(adapter);
            }
        } finally {
            // close the cursor
            codes.close();
        }
        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            // Called when a user swipes left or right on a ViewHolder
            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
                final int position = viewHolder.getAdapterPosition();
                ListItem item = listItems.get(position);

                cupboard().withDatabase(db).delete(Code.class, item.get_Id());
                listItems.remove(position);
                adapter.notifyItemRemoved(position);
                adapter.notifyItemRangeChanged(position, listItems.size());

            }
        }).attachToRecyclerView(recyclerView);
        scan = new IntentIntegrator(this);
        scan.setBeepEnabled(beep);
        scan.setCameraId(camId);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scan.initiateScan();
            }
        });

        ImageView imgAbout = findViewById(R.id.action_about);
        imgAbout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent aboutIntent = new Intent(MainActivity.this, About.class);
                startActivity(aboutIntent);
            }
        });

        ImageView imgSettings = findViewById(R.id.action_settings);
        imgSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(settingsIntent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_clearAll) {
            PracticeDatabaseHelper dbHelper = new PracticeDatabaseHelper(this);
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            Cursor codes = cupboard().withDatabase(db).query(Code.class).orderBy("_id DESC").getCursor();
            try {
                if (codes.getCount() > 0) {
                    cupboard().withDatabase(db).delete(Code.class, null);
                    listItems.clear();
                    adapter.notifyDataSetChanged();
                } else {
                    return true;
                }
            } finally {
                codes.close();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {

            if (result.getContents() == null) {
                Snackbar snackbar = Snackbar.make(findViewById(R.id.main), "Result Not Found", Snackbar.LENGTH_LONG);

                snackbar.show();
            } else {

                Code codeObj = new Code(result.getContents(), result.getFormatName());
                PracticeDatabaseHelper dbHelper = new PracticeDatabaseHelper(this);
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                long id = cupboard().withDatabase(db).put(codeObj);
                listItems.clear();
                adapter.notifyDataSetChanged();
                Cursor codes = cupboard().withDatabase(db).query(Code.class).orderBy("_id DESC").getCursor();
                try {
                    // Iterate Bunnys
                    QueryResultIterable itr = cupboard().withCursor(codes).iterate(Code.class);
                    for (Code bunny : itr) {
                        // do something with bunny
                        ListItem listItem = new ListItem(bunny._id, bunny.name, bunny.type);
                        listItems.add(listItem);
                        adapter = new MyAdapter(listItems, this);
                        recyclerView.setAdapter(adapter);
                    }
                } finally {
                    // close the cursor
                    codes.close();
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void cardClick(View card) {
        TextView textView = (TextView) findViewById(R.id.textViewCode);
        String code = textView.getText().toString();
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, code);
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals("beep")) {
            scan.setBeepEnabled(sharedPreferences.getBoolean(key, true));
        }
        if (key.equals("frontCamera")) {
            int camId;
            if (sharedPreferences.getBoolean(key, false) == false)
                camId = 0;
            else
                camId = 1;
            scan.setCameraId(camId);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PreferenceManager.getDefaultSharedPreferences(this)
                .unregisterOnSharedPreferenceChangeListener(this);
    }
}



<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.bottomappbar.BottomAppBar
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/colorPrimary"
        app:fabAlignmentMode="center"
        app:fabCradleRoundedCornerRadius="16dp"
        app:hideOnScroll="true">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="55.0dip"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentBottom="true"
            android:layout_gravity="bottom"
            android:orientation="horizontal">

            <include layout="@layout/navigation_bar" />

        </LinearLayout>

    </android.support.design.bottomappbar.BottomAppBar>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="4dp"
        android:tint="@android:color/white"
        app:fabSize="normal"
        app:layout_anchor="@+id/navigation"
        app:srcCompat="@android:drawable/ic_search_category_default" />

</android.support.design.widget.CoordinatorLayout>



<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="8dp">

    </android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="50.0dip"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="0.0dip"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_marginTop="5.0dip"
        android:layout_weight="1.0"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:layout_width="36.0dip"
            android:layout_height="36.0dip"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_about"
            android:id="@+id/action_about"
            android:tint="#ffffff" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="0.0dip"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1.0"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="invisible" />

    <LinearLayout
        android:layout_width="0.0dip"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_marginTop="5.0dip"
        android:layout_weight="1.0"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:layout_width="36.0dip"
            android:layout_height="36.0dip"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_settings"
            android:id="@+id/action_settings"
            android:tint="#ffffff" />

    </LinearLayout>
</LinearLayout>

5. Buat SettingsActivity.java, settings.xml (taruh di folder xml) dan menu_main.xml (taruh di folder menu) :


package com.azhar.barcodeqr;

import android.os.Bundle;
import android.preference.PreferenceActivity;

/**
 * Created by Azhar Rivaldi on 11/04/2019.
 */

public class SettingsActivity extends PreferenceActivity {

    private final static String TAG = "SettingsAcitivity";

    public SettingsActivity() {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new LocationFragment()).commit();
    }

}



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

    <PreferenceCategory
        android:title="Settings"
        app:key="settings">

        <CheckBoxPreference
            android:defaultValue="true"
            android:key="beep"
            android:summary="Enable beep on code scan"
            android:title="Beep Sound" />

        <CheckBoxPreference
            android:defaultValue="false"
            android:key="frontCamera"
            android:summary="Enable front camera for scanning"
            android:title="Front Camera" />
    </PreferenceCategory>

</PreferenceScreen>



<menu 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"
    tools:context=".MainActivity">
    <item
        android:id="@+id/action_clearAll"
        android:orderInCategory="100"
        android:title="@string/action_clearAll"
        app:showAsAction="always" />

</menu>

6. Buat About.java dan activity_about.xml :


package com.azhar.barcodeqr;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

/**
 * Created by Azhar Rivaldi on 11/04/2019.
 */

public class About extends AppCompatActivity {

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



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".About">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:text="Github"
        android:textSize="20sp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="16dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:autoLink="web"
        android:text="https://github.com/AzharRivaldi"
        android:textSize="16sp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="42dp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/darker_gray"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="76dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:text="Twitter"
        android:textSize="20sp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="16dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:autoLink="web"
        android:text="https://twitter.com/azharrvldi_"
        android:textSize="16sp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="42dp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/darker_gray"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="76dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:text="Website"
        android:textSize="20sp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="16dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:autoLink="web"
        android:text="https://rivaldi48.blogspot.com"
        android:textSize="16sp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="42dp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/darker_gray"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="76dp" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center"
            android:layout_margin="16dp"
            android:text="Designed by Azhar Rivaldi" />

    </FrameLayout>

</LinearLayout>

7. Buat MyAdapter.java dan list_item.xml :


package com.azhar.barcodeqr.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.azhar.barcodeqr.R;

import java.util.List;

/**
 * Created by Azhar Rivaldi on 11/04/2019.
 */

public class MyAdapter extends RecyclerView.Adapter {
    List listItems;
    Context context;

    public MyAdapter(List listItems, Context context) {
        this.listItems = listItems;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        ListItem listItem = listItems.get(position);
        holder.textView_Id.setText(String.valueOf(listItem.get_Id()));
        holder.textViewCode.setText(listItem.getCode());
        holder.textViewType.setText(listItem.getType());
        Linkify.addLinks(holder.textViewCode, Linkify.ALL);
    }

    @Override
    public int getItemCount() {
        return listItems.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        public TextView textView_Id;
        public TextView textViewCode;
        public TextView textViewType;

        public TextView getTextView_Id() {
            return textView_Id;
        }

        public ViewHolder(View itemView) {
            super(itemView);
            textView_Id = (TextView)itemView.findViewById(R.id.textView_Id);
            textViewCode = (TextView)itemView.findViewById(R.id.textViewCode);
            textViewType = (TextView)itemView.findViewById(R.id.textViewType);
        }
    }
}




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        app:cardCornerRadius="5dp"
        app:cardElevation="4dp"
        android:paddingStart="8dp"
        android:paddingLeft="8dp"
        android:paddingBottom="8dp">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="8dp"
            android:paddingBottom="8dp">

            <TextView

                android:id="@+id/textViewCode"
                android:layout_width="306dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginTop="16dp"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:textIsSelectable="true"
                android:textSize="20sp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                tools:text="code" />

            <TextView
                android:id="@+id/textViewType"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginTop="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textViewCode"
                tools:text="type" />

            <TextView
                android:id="@+id/textView_Id"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:visibility="gone"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                tools:text="id" />

            <TextView
                android:id="@+id/textViewShare"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginRight="4dp"
                android:layout_marginBottom="8dp"
                android:background="@drawable/button_background"
                android:clickable="true"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:onClick="cardClick"
                android:paddingLeft="6dp"
                android:paddingTop="8dp"
                android:paddingRight="6dp"
                android:paddingBottom="8dp"
                android:text="SHARE"
                android:textColor="@android:color/white"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:textSize="15sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

8. Buat PracticeDatabaseHelper.java :


package com.azhar.barcodeqr;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.azhar.barcodeqr.adapter.Code;

import static nl.qbusict.cupboard.CupboardFactory.cupboard;

/**
 * Created by Azhar Rivaldi on 11/04/2019.
 */

public class PracticeDatabaseHelper  extends SQLiteOpenHelper{
    private static final String DATABASE_NAME = "scanqrbarcode.db";
    private static final int DATABASE_VERSION = 1;

    public PracticeDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    static {
        // register our models
        cupboard().register(Code.class);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // this will ensure that all tables are created
        cupboard().withDatabase(db).createTables();
        // add indexes and other database tweaks in this method if you want

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // this will upgrade tables, adding columns and new tables.
        // Note that existing columns will not be converted
        cupboard().withDatabase(db).upgradeTables();
        // do migration work if you have an alteration to make to your schema here

    }

}

9. Buat LocationFragment.java :


package com.azhar.barcodeqr;

import android.os.Bundle;
import android.preference.PreferenceFragment;

/**
 * Created by Azhar Rivaldi on 11/04/2019.
 */

public class LocationFragment extends PreferenceFragment {

    private final static String beep = "beep";
    private final static String frontCamera = "frontCamera";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.settings);
    }

}

10. Buat ListItem.java dan Code.java :


package com.azhar.barcodeqr.adapter;

/**
 * Created by Azhar Rivaldi on 11/04/2019.
 */

public class ListItem {
    private long _id;
    private String code;
    private String type;

    public ListItem(long _id, String code, String type) {
        this._id = _id;
        this.code = code;
        this.type = type;
    }

    public long get_Id() {
        return _id;
    }

    public String getCode() {
        return code;
    }

    public String getType() {
        return type;
    }
}



package com.azhar.barcodeqr.adapter;

/**
 * Created by Azhar Rivaldi on 11/04/2019.
 */

public class Code {

    public Long _id; // for cupboard
    public String name; // bunny name
    public String type;

    public Code() {
        this.name = "noName";
        this.type = "noType";
    }

    public Code(String name, String type) {
        this.name = name;
        this.type = type;
    }

}

Jika sudah selesai, silahkan kalian RUN dengan emulator bawaan Android Studio atau langsung melalui Device. Untuk hasil outputnya seperti ini:
Aplikasi Scan Barcode dan QR Code
Aplikasi Scan Barcode dan QR Code
Aplikasi Scan Barcode dan QR Code
Aplikasi Scan Barcode dan QR Code
Aplikasi Scan Barcode dan QR Code
Aplikasi Scan Barcode dan QR Code
Kalau kalian mengikuti langkah-langkah diatas dengan baik, pasti aplikasi yang kalian buat akan berjalan sebagaimana mestinya. Namun jika mengalami Error, silahkan berikan komentar dan kita diskusikan bersama.

Demikian informasi yang saya bagikan untuk kalian. Jangan lupa bagikan artikel ini ke teman-teman kalian agar ikut membaca Tutorial Membuat Aplikasi Scan Barcode dan QR Code dengan Android Studio ini. Subscribe juga 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...

14 comments

  1. Trimakasih boz tutor nya..saya mengikuti sc nya namun punya kendala ketika kita klik share pilihannya cuma via email aja..mohon bantuannya boz

    ReplyDelete
  2. Terima kasih ilmunya, mau tanya seandainya merubah scan menggunakan kamera depan, kira kira gimana ya?

    ReplyDelete
    Replies
    1. source code ini udah support scan kamera depan kok

      Delete
  3. ijin download dan kembangkan ya gan. terima kasih banyak sebelumnya

    ReplyDelete
  4. kanda ini sudah bisa scan semua Qrcode?

    ReplyDelete
  5. makasih ya ka bermanfaat sekali semoga bisa membuat aplikasi yang lebih menarik lagi sukses teruuussss

    ReplyDelete
  6. Assalamualaikum mas makasih atas ilmunya, dan saya izin untuk mengupload aplikasinya ke PlayStore ya mas_/\_ apknya telah saya modifikasi sedemikian rupa. Jadi ndak mirip lagi kayak apk punya mas. Terima kasih Semoga Allah memudahhkan segala hajat mas_/\_

    ReplyDelete
  7. Hallo bro, sekarang udah pake androidx. semua bro, jadi agak repot untuk download2 librarynya.

    ReplyDelete
    Replies
    1. ini kan tutorial lama, kalo dirasa repot ya dicompare aja jangan dicopas

      Delete

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