add following code into dependencies{} compile 'me.dm7.barcodescanner:zxing:1.9'
Here we are using ZXing library. You can also use ZBar library.
Step 3: Updating AndroidManifest.xml file
add camera permission between…. tag.
Step 4: Updating activity_main.xml file:
Copy following code into android_main.xml file:
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.exampledemo.parsaniahardik.scanzxingdemonuts.MainActivity">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="Scan Barcode or QR code" />
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tvresult"
android:textColor="#000"
android:layout_marginTop="10dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Result will be here"/>
I have taken one button and one textview in the main layout file.
When the user clicks on the button, system will open a Scan activity.
Unique id from the barcode will appear in the textview after successful scanning.
Step 5: Updating MainActivity.java file:
Update MainActivity.java as per below code:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public static TextView tvresult;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvresult = (TextView) findViewById(R.id.tvresult);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivity(intent);
}
});
}
}
Here we will open ScanActivity on the button’s click.
We will set up the logic for the scanning task in ScanActivity.