Unable to scan QR code using Zxing library - java

I'm trying to integrate Zxing into my android application so the user can scan a qr code and it returns the contents of the QR code. I am able to open the barcode scanner however although it looks like it's doing something it doesn't scan the QR code. I have tested it on bar codes and it works so it looks like the issue is specific to qr codes. I've included some code snippets below.
Manifest File
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="portrait"
tools:replace="android:screenOrientation"
android:stateNotNeeded="true"/>
QR scanner fragment
package com.example.ntuevent.ui.qrScanner;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.ntuevent.R;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class QRScannerFragment extends Fragment implements View.OnClickListener {
private QRScannerViewModel qrScannerViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
qrScannerViewModel =
ViewModelProviders.of(this).get(QRScannerViewModel.class);
View root = inflater.inflate(R.layout.fragment_qr_scanner, container, false);
final TextView textView = root.findViewById(R.id.text_qr_scanner);
qrScannerViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
root.findViewById(R.id.qr_scanner_button).setOnClickListener(this);
return root;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.qr_scanner_button:
/* Request camera access */
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 1);
launchQrScanner();
}
}
private void launchQrScanner() {
if (validateCameraPermission()) {
/* Start the scanner */
IntentIntegrator intentIntegrator = new IntentIntegrator(getActivity());
/* Customisation options */
intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
intentIntegrator.setPrompt("Scan a barcode");
intentIntegrator.setCameraId(0); // Use a specific camera of the device
intentIntegrator.setBeepEnabled(false);
intentIntegrator.setOrientationLocked(true);
/* Start QR scanner */
intentIntegrator.initiateScan();
}
}
private boolean validateCameraPermission() {
/* Validates if app has access to camera */
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getContext().getApplicationContext(), "Enable camera permissions to access this feature", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (intentResult != null) {
if (intentResult.getContents() == null)
Toast.makeText(getContext().getApplicationContext(), "Scan was cancelled", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext().getApplicationContext(), intentResult.getContents(), Toast.LENGTH_SHORT).show();
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
Any help would be great!

do like me for QR code scanner, I used this code for 2 projects and worked without any problem.
first, add below libraries to your Gradle:
implementation 'me.dm7.barcodescanner:zxing:1.9.13'
implementation 'com.journeyapps:zxing-android-embedded:3.6.0#aar'
implementation 'com.google.zxing:core:3.3.3'
second, in your QR code scanner activity add below codes:
private IntentIntegrator qrScan;
in onCreate add below:
qrScan = new IntentIntegrator(this);
qrScan.setOrientationLocked(false);
qrScan.initiateScan();
after onCreate add below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode,
resultCode, data);
if (result != null) {
if (result.getContents() == null) {
//scan have an error
} else {
//scan is successful
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}

Related

How to capture and pass Mat object to a new activity?

I am planning on implementing ocr, the idea is for the user to capture an image and the app will write it as text to a file on the phone. I have managed to display the feed from the camera to the javacameraview using CvCameraViewListener2.
I now want to capture the frame as an Mat object and pass it to a new activity. The solution's I saw all involve saving the photo, or displaying the processed image or live processing. I just need to pass the Mat to another class for processing then I can release it. I'm having trouble find a methodology for doing this though it seems as though it should be fairly straightforward.
The question is essentially how to get the Mat object from the cameraview?
Any help or direction would be greatly appreciated.
Thank you stackoverflow
The relevant code is here
import android.Manifest;
import android.content.Intent;
Import android.content.pm.ActivityInfo; importandroid.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CAMERA_PERMISSION_RESULT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation != 90) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
}
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.cameraInit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//marshmallow permissions
takePhoto();
}
});
}
private void callCamera(){
Intent startCameraIntent = new Intent(getApplicationContext(), OpenCVCamera.class);
startActivity(startCameraIntent);
}
public void takePhoto() {
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
callCamera();
} else {
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this, "This app requires camera access", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION_RESULT);
}
} else {
callCamera();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == REQUEST_CAMERA_PERMISSION_RESULT){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
callCamera();
} else {
Toast.makeText(this, "Permission Denied.", Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.WindowManager;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Mat;
public class OpenCVCamera extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{
// need to correct view size (i think this can be done in the xml
// else refer to cmaera video app
// also orientation needs to be corrected
private static final String TAG = "OpenCVCamera";
private CameraBridgeViewBase cameraBridgeViewBase;
private BaseLoaderCallback baseLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
cameraBridgeViewBase.enableView();
break;
default:
super.onManagerConnected(status);
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_open_cvcamera);
cameraBridgeViewBase = (CameraBridgeViewBase) findViewById(R.id.camera_view);
cameraBridgeViewBase.setVisibility(SurfaceView.VISIBLE);
cameraBridgeViewBase.setCvCameraViewListener(this);
}
#Override
public void onResume(){
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this, baseLoaderCallback);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
baseLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
#Override
public void onCameraViewStarted(int width, int height) {
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
//original just returns inputFrame.rgba()
Core.rotate(inputFrame.rgba(), inputFrame.rgba(), Core.ROTATE_90_CLOCKWISE); //ROTATE_180 or ROTATE_90_COUNTERCLOCKWISE
return inputFrame.rgba();
}
}

Place Picker loads to long, variables don't change correctly

I'm making a simple place picker program in android. I want to save some text when user choose a point on map with place picker. And the problem is when I click on button the place picker opens too long and variable which is responsible for place can't keep up change and dialog that responses for enter text never opens. I think, maybe problem is with threads, isn't it?
MapsActivity.java
package com.example.kirill.myapplication;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, View.OnClickListener {
private static final int PLACE_PICKER_REQUEST = 1;
private GoogleMap mMap;
private Button addEventBtn;
private PlacePicker.IntentBuilder builder;
private Place place;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddEventButton:
place = null;
callPlacePicker();
if (place != null) {
openDialog();
}
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
addEventBtn = (Button) findViewById(R.id.AddEventButton);
}
#Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
Marker marker = mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
addEventBtn.setOnClickListener(this);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(this, data);
}
}
}
public void openDialog() {
DialogEventCreate dialogEventCreate = new DialogEventCreate();
dialogEventCreate.show(getSupportFragmentManager(), "dialog Event Create");
}
public void callPlacePicker() {
builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
DialogEventCreate.java
package com.example.kirill.myapplication;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
public class DialogEventCreate extends AppCompatDialogFragment {
private EditText editEventName;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
builder.setView(view)
.setTitle("Create Event")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
editEventName = view.findViewById(R.id.editEventName);
return builder.create();
}
}
Please help me, what could go wrong?
Your problem is that the Place Picker communicates with your main activity asynchronously, so you're opening your dialog before it returns. Try waiting until Place Picker has returned before opening the dialog like so:
.
.
.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddEventButton:
place = null;
callPlacePicker();
break;
}
}
.
.
.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(this, data);
openDialog();
}
}
}

How to save image into gallery Android ap

I'm making an android application, when clicking on a button it opens the camera however after taking the picture the image doesn't save. I want to be able to save it into my gallery album.
public void onClickbtnCamera(View v){
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uriSavedImage=Uri.fromFile(new File("/storage/emulated/0/DCIM/Camera/"));
intent1.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(intent1,3);
}
You are passing in a directory in EXTRA_OUTPUT. EXTRA_OUTPUT needs to point to a file:
package com.commonsware.android.camcon;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
public class CameraContentDemoActivity extends Activity {
private static final int CONTENT_REQUEST=1337;
private File output=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.jpeg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CONTENT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == CONTENT_REQUEST) {
if (resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/jpeg");
startActivity(i);
finish();
}
}
}
}
(from this sample project)

Unable to save images taken using app?

I have spent much time trying to resolve this trivial problem but seem to be going in circles even after reading many tutorials and previously asked questions.
I am a novice at programming but want to get better and believe that learning through mistakes is the best way.
Can someone please help identify the problem with this code and what can be done in order to allow the pictures taken by the device's camera to be saved onto the phone afterwards rather than being discarded and previewed.
Thanks in advance!
Java code for relevant class:
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
public class Activity_Camera extends Activity implements View.OnClickListener {
public static final int cameraData = 1;
ImageButton ib;
ImageView iv;
Intent i;
Bitmap bmp;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Info:
Intent i = new Intent(this, Help.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
initialise();
}
private void initialise() {
iv = (ImageView) findViewById(R.id.ivPicReturn);
ib = (ImageButton) findViewById(R.id.ibTakePic);
ib.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.ibTakePic:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//
i.putExtra(MediaStore.EXTRA_OUTPUT, getOutputMediaFileUri());
//
startActivityForResult(i, cameraData);
break;
}
}
//
private String getOutputMediaFileUri() {
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, "image.jpg");
Uri uriSavedImage = Uri.fromFile(image);
Intent imageIntent = null;
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
return null;
}
//
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}
}
}
because you're returning null return null; in your getOutputMediaFileUri
try this instead
public void onClick(View v) {
switch (v.getId()) {
case R.id.ibTakePic:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, getOutputMediaFileUri());
startActivityForResult(i, cameraData);
break;
}
}
private Uri getOutputMediaFileUri() {
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, "image.jpg");
return Uri.fromFile(image);
}

Issues With the OCR code and Java Code for ANDROID

here is my code to convert the picture taken from the camera into text using tesseract's java wrapper tess4j! i have included the jar files added them to my path! code does not show any syntax errors! i launch the default camera it starts i take picture and it is shown in the image view i declared however the editbox seems empty though it should show the result of OCR!
package your.apnakaam.namespace;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.graphics.Bitmap;
import android.widget.ImageView;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.File;
import java.io.File;
import net.sourceforge.tess4j.*;
public class KaamsekhaActivity extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
//**************************************************************************************************
private Intent data;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setContentView(R.layout.apna_layout);
Button capt_but = (Button)findViewById(R.id.capture_btn);
this.imageView = (ImageView)this.findViewById(R.id.picture);
capt_but.setOnClickListener(new View.OnClickListener()
{
//#Override
// TODO Auto-generated method stub
public void onClick(View v)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
void myfunction()
}
}
public void myfunction()
{
TextView disp = (TextView)findViewById(R.id.editText1);
File new_pic = (File) data.getExtras().get("data");
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
try
{
String result = instance.doOCR(new_pic);
disp.setText(result);
}
catch (TesseractException e)
{
System.err.println(e.getMessage());
}
}
}
I can't figure out whats wrong with the code!
The function doOCR takes a buffered image that is not possible while working in android! Bufferedimage uses IIOimage that is used in java but not in android!

Categories