How to navigate from QR Code Reader to Paticular URL? - java

Project is working fine But my problem is How to navigate from QR Code Reader to Particular URL. what is code to navigate please anyone tell me and help me.
AndroidBarcodeQrExample.java
public class AndroidBarcodeQrExample extends Activity {
static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void scanQR(View v) {
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
} catch (Exception e) {
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format, Toast.LENGTH_LONG);
toast.show();
}
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="#ffffff"
android:orientation="vertical" >
<Button
android:id="#+id/scanner"
android:layout_width="250dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:layout_margin="10dp"
android:gravity="center"
android:onClick="scanQR"
android:text="QR Code"
android:textSize="18dp" >
</Button>
</LinearLayout>

The code to open url in browser is as follow:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("Your url here"));
startActivity(browserIntent);

Related

What is the callback or return function in android studio using java?

Respect my post Im a newbie :) thank you for understanding
sorry for my grammar
This program is to choose from gallery permission and send to second activity. the
permission is allowed is okay it will send it to the second activity...but when i clicked "oks" in the first popup permission and when i "dont allow files access the device" it will run and when i click button "pick " it will stay to and main activity when i click the button "pick"
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonGalleryOpen(View view)
{
Intent intent = new Intent(this, gallery_view.class);
startActivity(intent);
}
}
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">
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="camera sample"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textview1"
android:layout_marginTop="3dp">
<Button
android:id="#+id/button_pick"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginTop="30dp"
android:gravity="center"
android:onClick="buttonGalleryOpen"
android:text="pick" />
</RelativeLayout>
</RelativeLayout>
gallery_view.java
public class gallery_view extends AppCompatActivity {
private int STORAGE_PERMISSION_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_view);
if (ContextCompat.checkSelfPermission(gallery_view.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//noinspection deprecation
startActivityForResult(intent, 3);
} else {
requestStoragePermission();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
ImageView imageView = findViewById(R.id.imageviewfromgallery);
imageView.setImageURI(selectedImage);
} else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This permission is needed because of this and that")
.setPositiveButton("oks", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(gallery_view.this, new
String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
})
.create().show();
} else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
}
activity_gallery_view.xml
<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">
<RelativeLayout
android:id="#+id/relative_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="camera sample"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/relative_1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageviewfromgallery"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
</RelativeLayout>
Check official documentation here https://developer.android.com/training/permissions/requesting#java
Also, after user disabled permission dialog,try to send user to app settings to enable it manually.
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivityForResult(intent, REQUEST_PERMISSION_SETTING);

Google Place Picker Not Opening on One click in Android Studio Java

I have used google place picker in android app for selecting location of the user by their wish. But when clicking the button it opened and suddenly it gets closed and if i click again only it opened to choose the location. And after opening also i can't search the location by typing the name.
Here i tried like this,
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/myButton"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Check Here"
android:textSize="16dp"
android:textStyle="normal"
android:textColor="#color/colorPrimary"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Button button = (Button)findViewById(R.id.myButton);
location_tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(PreviousAddressActivity.this),PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("dataview", String.valueOf(data));
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
StringBuilder stringBuilder = new StringBuilder();
String latitude = String.valueOf(place.getLatLng().latitude);
String longitude = String.valueOf(place.getLatLng().longitude);
stringBuilder.append("LATITUDE :");
stringBuilder.append(latitude);
stringBuilder.append("\n");
stringBuilder.append("Longitude");
stringBuilder.append(longitude);
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
Toast.makeText(getApplicationContext(),address, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Totally frustrated with this issue. Can anybody help me?
Thanks in Advance...

How to fix an app from continuously requesting to be updated [duplicate]

This question already has answers here:
App on Google Play always shows "Update" instead of open [closed]
(6 answers)
Closed 4 years ago.
I have uploaded an update to my app on Play and as soon as I update it, it asks to update again.
The app comprises a few button on an otherwise simple WebView app, and Google Play keeps wanting to update the app.
I cannot find any errors causing this.
I would appreciate heads-up as so what could be causing this.
public class PilatesTimetable extends AppCompatActivity {
WebView rootView;
boolean installed;
ImageButton myWhatsApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pilates_timetable);
rootView = findViewById(R.id.timetable);
rootView.loadUrl("http://www.example.com");
rootView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
WebView.setWebContentsDebuggingEnabled(false);
installed = appInstalledOrNot("com.whatsapp");
myWhatsApp = findViewById(R.id.whatsAppButton);
if (installed) {
myWhatsApp.setVisibility(View.VISIBLE);
}
if (myWhatsApp.getVisibility() == View.VISIBLE) {
myWhatsApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = "+3530871234567";
String url = "https://api.whatsapp.com/send?phone=" + number;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
}
public void callUs(View v){
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:0871234567"));
startActivity(callIntent);
}
public void textUs(View v){
try{
Intent textIntent = new Intent(Intent.ACTION_SENDTO);
textIntent.setData((Uri.parse("smsto:0871234567")));
startActivity(textIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(PilatesTimetable.this, "You do not have a texting application installed.", Toast.LENGTH_LONG).show();
}
}
public void emailUs (View v){
try {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData((Uri.parse("mailto:user#example.com")));
startActivity(emailIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(PilatesTimetable.this, "You do not have an email application installed.", Toast.LENGTH_LONG).show();
}
}
public void bookOnline (View v){
try {
Intent bookIntent = new Intent(Intent.ACTION_VIEW);
bookIntent.setData((Uri.parse("http://www.example.com")));
startActivity(bookIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(PilatesTimetable.this, "You do not have an Internet viewing application installed.", Toast.LENGTH_LONG).show();
}
}
public boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
boolean app_installed;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
}
catch (PackageManager.NameNotFoundException e) {
app_installed = false;
}
return app_installed;
}
}
Example code from the activity:
<?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"
tools:context="ie.myPackage.PilatesTimetable">
<WebView
android:id="#+id/timetable"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintTop_toTopOf="parent">
</WebView>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="85dp"
android:background="#color/primaryLightColor"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<ImageButton
android:id="#+id/whatsAppButton"
android:layout_width="0dp"
android:layout_height="85dp"
android:layout_weight="1"
android:background="#null"
android:backgroundTint="#color/primaryLightColor"
android:contentDescription="#string/whats_app_us"
android:tint="#color/white"
android:visibility="gone"
app:srcCompat="#drawable/wa_55" />
I have just finished chatting to Google and they confirmed that they have an ongoing issue with this at the moment.
So nothing to do with the app, it's their system.

How to upload images to firebase storage from tabbed actvity?

I want my newfeed.java tab to allow users to choose an image from gallery and > upload it to the firebase storage. Also, how to retrieve these images and >display in a listview ?
Newfeed.java
import static android.app.Activity.RESULT_OK;
public class NewfeedTab extends Fragment {
private static final int PICK_IMAGE_REQUEST = 234;
private StorageReference mStorageRef;
private EditText story;
private ImageButton choose;
private ImageButton upload;
private Uri filePath;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news_feed, container, false);
mStorageRef = FirebaseStorage.getInstance().getReference();
story = (EditText)rootView.findViewById(R.id.et_story);
choose = (ImageButton)rootView.findViewById(R.id.imageButton_choose);
upload = (ImageButton)rootView.findViewById(R.id.imageButton_upload);
choose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null){
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setTitle("Uploading");
progressDialog.show();
StorageReference picsRef = mStorageRef.child("images/pic.jpg");
picsRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getContext(),"Story posted",Toast.LENGTH_SHORT);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getContext(),"Story couldn't be posted",Toast.LENGTH_SHORT);
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//displaying percentage in progress dialog
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
}
}
}
The app closes after selecting the image from gallery. NewfeedTab.java is a fragment of tabbed activity.
newsfeed.xml
<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"
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.seven.pprs.bloodlink.TabActivity$PlaceholderFragment">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/et_story"
android:layout_toStartOf="#+id/imageButton_choose"
android:hint="Share your stories here" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_file_upload_black_24dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:id="#+id/imageButton_upload" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:dividerHeight="1dp"
android:divider="#android:color/holo_red_dark"
android:id="#+id/list_of_posts"
android:layout_marginBottom="16dp"
android:layout_below="#+id/et_story" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_add_a_photo_black_24dp"
android:layout_alignBottom="#+id/imageButton_upload"
android:layout_toStartOf="#+id/imageButton_upload"
android:id="#+id/imageButton_choose" />
Do you have read permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

How to ZXING Barcode Scanner not full screen only half screen

I want create application
Scan Barcode using ZXING Barcode Scanner
Like Blackberry Messenger
This is my code "MainActivity.java"
package com.example.ridwan.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import info.vividcode.android.zxing.CaptureActivity;
import info.vividcode.android.zxing.CaptureActivityIntents;
public class MainActivity extends AppCompatActivity {
private TextView tvScanResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent captureIntent = new Intent(MainActivity.this, CaptureActivity.class);
CaptureActivityIntents.setPromptMessage(captureIntent, "Barcode scanning...");
startActivityForResult(captureIntent, 0);
tvScanResult = (TextView) findViewById(R.id.tv_scanresult);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK && data != null) {
String value = data.getStringExtra("SCAN_RESULT");
tvScanResult.setText(value);
} else if (resultCode == Activity.RESULT_CANCELED) {
tvScanResult.setText("Scanning Gagal, mohon coba lagi.");
}
} else {
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Then this is my "activity_main.xml"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
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.example.ridwan.myapplication.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_marginTop="50dp"
android:id="#+id/tv_scanresult_title"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result Scan : " />
<TextView
android:layout_below="#id/tv_scanresult_title"
android:id="#+id/tv_scanresult"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:textColor="#ff1493"
android:layout_height="wrap_content"
android:text="_" />
</RelativeLayout>
Can you give me solution ?
i want to barcode in fragment.
I have achieved the same effect/UI you are looking for by using ZXing Android Embedded. Very straightforward to implement - and it also includes a torch functionality.
Step 1:
Add This Libray in Gradle in Dependancy
implementation 'com.google.zxing:core:3.2.1'
implementation 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
Step 2:
BarcodeActivity.java
public class BarcodeActivity extends AppCompatActivity {
private EditText editTextProductId;
private Button buttonGenerate, buttonScan;
private ImageView imageViewResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
initView();
}
private void initView() {
editTextProductId = findViewById(R.id.editTextProductId);
imageViewResult = findViewById(R.id.imageViewResult);
buttonGenerate = findViewById(R.id.buttonGenerate);
buttonGenerate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonGenerate_onClick(view);
}
});
buttonScan = findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonScan_onClick(view);
}
});
}
private void buttonGenerate_onClick(View view) {
try {
String productId = editTextProductId.getText().toString();
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
Writer codeWriter;
codeWriter = new Code128Writer();
BitMatrix byteMatrix = codeWriter.encode(productId, BarcodeFormat.CODE_128,400, 200, hintMap);
int width = byteMatrix.getWidth();
int height = byteMatrix.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
bitmap.setPixel(i, j, byteMatrix.get(i, j) ? Color.BLACK : Color.WHITE);
}
}
imageViewResult.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
private void buttonScan_onClick(View view) {
IntentIntegrator intentIntegrator = new IntentIntegrator(this);
intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
intentIntegrator.setCameraId(0);
intentIntegrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (intentResult != null) {
String productId = intentResult.getContents();
Toast.makeText(getApplicationContext(), productId, Toast.LENGTH_LONG).show();
}
}
}
Step 3:
activity_barcode.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="#ffffff"
android:orientation="vertical"
tools:ignore="HardcodedText">
<EditText
android:id="#+id/editTextProductId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Product Id"
android:inputType="textPersonName" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/buttonGenerate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Generate Barcode" />
<Button
android:id="#+id/buttonScan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Scan Barcode" />
</LinearLayout>
<ImageView
android:id="#+id/imageViewResult"
android:layout_width="match_parent"
android:layout_height="335dp" />
</LinearLayout>
Please Add this code in MainActivity
Add This Libray in Gradle in Dependancy
compile 'com.journeyapps:zxing-android-embedded:3.3.0#aar'
compile 'me.dm7.barcodescanner:zxing:1.9'
Add jar zbar.jar
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QCscanner = (Button) findViewById(R.id.QCscanner);
mScannerView = new ZXingScannerView(this);
QCscanner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
/*Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);*/
mScannerView = new ZXingScannerView(MainActivity.this); // Programmatically initialize the scanner view<br />
setContentView(mScannerView);
mScannerView.setResultHandler(MainActivity.this); // Register ourselves as a handler for scan results.<br />
mScannerView.startCamera();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
#Override
public void handleResult(Result result) {
Log.e("", result.getText()); // Prints scan results<br />
Log.e("", result.getBarcodeFormat().toString());
Toast.makeText(MainActivity.this, "" + result.getText() + "\n" + result.getBarcodeFormat().toString(), Toast.LENGTH_SHORT).show();
}
}
ZXING library allows you to launch an intent(activity) to scan barcodes. If you wants to make changes in that you have to make changes in CaptureActivity of ZXING lib.
Also, now since Google has included scanning feature in its playservices you can use Vision api for scanning in a fragment without integration of any third party library. https://github.com/googlesamples/android-vision/tree/master/visionSamples
Please use
https://github.com/journeyapps/zxing-android-embedded
Just include Scanner view and remove scan paddings by adding:
app:zxing_framing_rect_width="200dp"
app:zxing_framing_rect_height="200dp"
attributes.
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="#+id/zxing_barcode_scanner"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
app:zxing_framing_rect_width="200dp"
app:zxing_framing_rect_height="200dp"
app:zxing_preview_scaling_strategy="fitXY"
app:zxing_use_texture_view="false"
/>
try this. (It very simplified example):
First step. Add dependency in build.gradle(module app):
From version 4.x, only Android SDK 24+ is supported by default, and androidx is required.
implementation 'com.journeyapps:zxing-android-embedded:4.2.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
For Android SDK versions < 24, you can downgrade zxing:core to 3.3.0 or earlier for Android 14+ support:
implementation 'com.google.zxing:core:3.3.0'
Second step. Paste DecoratedBarcodeView view in you layout (activity_main.xml in this example):
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentTop="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
</com.journeyapps.barcodescanner.DecoratedBarcodeView>
<TextView
android:id="#+id/resultTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/barcode_scanner" />
</androidx.constraintlayout.widget.ConstraintLayout>
Third step. Add this code to MainActivity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val formats: Collection<BarcodeFormat> = Arrays.asList(BarcodeFormat.QR_CODE, BarcodeFormat.CODE_39)
binding.barcodeScanner.decoderFactory = DefaultDecoderFactory(formats)
binding.barcodeScanner.initializeFromIntent(Intent())
binding.barcodeScanner.decodeContinuous(object : BarcodeCallback {
override fun barcodeResult(result: BarcodeResult?) {
binding.resultTextView.text = result?.result?.text
}
})
}
override fun onResume() {
super.onResume()
binding.barcodeScanner.resume()
}
override fun onPause() {
super.onPause()
binding.barcodeScanner.pause()
}
}
Important! Implements onResume/onPause methods for activate DecoratedBarcodeView view. And don't forget grant Camera permissions for you app!
In this example i use this library:
https://github.com/journeyapps/zxing-android-embedded

Categories