onActivityResult not calling in Fragment's - android

Hi I am new for android and in my app I am using Z-bar library for scanning barcode.
For this I am using ZbarScannerActivity class like below, so after scanning the barcode I am getting those barcode results where ever I want using onActivityResult method.
Here my problem is when I am scanning the barcode I want to get this result in my Fragment, but here onActivityResult not calling in my Fragment.
But it's calling in my Activities please help me.
How can I solve this problem?
ZbarScanner Activity:-
public class ZBarScannerActivity extends ActionBarActivity {
private Camera mCamera;
private CameraPreview mPreview;
private Handler autoFocusHandler;
ImageScanner scanner;
ImageView backButton;
private boolean barcodeScanned = false;
private boolean previewing = true;
CustomTextview navigation_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner_view_layout);
ActionBar actionBar = getSupportActionBar();
String header = "<font color=\"#ffffff\">" + "BarCode Scanner"
+ " </font>";
CommonUtils.actionbarHeader(this, actionBar, header);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
autoFocusHandler = new Handler();
mCamera = getCameraInstance();
/* Instance barcode scanner */
scanner = new ImageScanner();
scanner.setConfig(0, Config.X_DENSITY, 3);
scanner.setConfig(0, Config.Y_DENSITY, 3);
mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
preview.addView(mPreview);
navigation_title = (CustomTextview)findViewById(R.id.navigationTitle_id);
navigation_title.setText("Barcode Scanner");
backButton = (ImageView)findViewById(R.id.navigationbackbutton_id);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
static {
System.loadLibrary("iconv");
}
public void onPause() {
super.onPause();
releaseCamera();
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
}
return c;
}
private void releaseCamera() {
if (mCamera != null) {
previewing = false;
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
private Runnable doAutoFocus = new Runnable() {
public void run() {
if (previewing)
mCamera.autoFocus(autoFocusCB);
}
};
PreviewCallback previewCb = new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
Size size = parameters.getPreviewSize();
Image barcode = new Image(size.width, size.height, "Y800");
barcode.setData(data);
int result = scanner.scanImage(barcode);
if (result != 0) {
previewing = false;
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
SymbolSet syms = scanner.getResults();
for (Symbol sym : syms) {
System.out.println("------->"+sym.getData());
barcodeScanned = true;
finishActivivtyWithResult(sym.getData());
}
}
}
};
// Mimic continuous auto-focusing
AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
autoFocusHandler.postDelayed(doAutoFocus, 1000);
}
};
/**
*
* #param barCodeResult
*/
private void finishActivivtyWithResult(String barCodeResult){
if (barCodeResult.contains("//b")) {
String replacedString = barCodeResult.replace("//b", "");
System.out.println("One========>" + replacedString);
barCodeResult = replacedString;
}
if (barCodeResult.contains("/t")) {
String replacedString = barCodeResult.replace("/t", "-");
System.out.println("After========>" + replacedString);
barCodeResult = replacedString;
}
Bundle conData = new Bundle();
conData.putString("barCodeResult", barCodeResult);
Intent intent = new Intent();
intent.putExtras(conData);
setResult(RESULT_OK, intent);
finish();
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
my fragment:-
//Camera Button Action Event:-
/**
* #return
*/
private View.OnClickListener cameraDetails() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
BAR_CODE_SCANNER_CODE = 100;
checkCameraPermission();
}
};
}
//BarCode Scanner Result:-
private void checkCameraPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkManifestPermissionSets();
} else {
scanProductCode();
}
}
#TargetApi(23)
private void checkManifestPermissionSets() {
int cameraPermission = ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.CAMERA);
List<String> permissions = new ArrayList<String>();
if (cameraPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.CAMERA);
}
if (!permissions.isEmpty()) {
requestPermissions(
permissions.toArray(new String[permissions.size()]),
REQUEST_CODE_SOME_FEATURES_PERMISSIONS);
} else {
scanProductCode();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_SOME_FEATURES_PERMISSIONS: {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
//Log.d("Permissions", "Permission Granted: "+ permissions[i]);
scanProductCode();
break;
} else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
//Log.d("Permissions", "Permission Denied: " + permissions[i]);
//CommonUtils.showToastMessage(StockTransfer.this, "You've disabled the App required Permissions");
break;
}
}
}
break;
default: {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
}
private void scanProductCode() {
if (isCameraAvailable()) {
CommonUtils.showToastMessage(getActivity(),
"Please Scan Your Product BarCode");
callThreadScannerActivity();
} else {
Toast.makeText(getActivity(), "Rear Facing Camera Unavailable",
Toast.LENGTH_SHORT).show();
}
}
private void callThreadScannerActivity() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// dialog.dismiss();
callScannerActivity();
}
}, 700);
}
// Call Scanner Activity:-
private void callScannerActivity() {
Intent intent = new Intent(getActivity(), ZBarScannerActivity.class);
startActivityForResult(intent, BAR_CODE_SCANNER_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("result code------>" + requestCode);
}
private boolean isCameraAvailable() {
PackageManager pm = getActivity().getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
}

Simple logic connected to general life
activity : father(parent)
fragment : child
if child wanna money than he ask to him/ her father.
technical way if fragment(child) wanna data from onActivityResult it always VIA Activity(father).
ohk .. lets look on code side
stuff at
yourActivity (Parent)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
this list of fragment(child) of activity said to him activity(father) for data
when activity received data it gives as fragments(childs) demands.

In fragment whenever we start activity for any result then that result in received in onActivityResult of activity then we have to pass this result to fragment's onActivityResult
Write this to your activitys's onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Logg.e("RESULT ", " " + resultCode);
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case 100:
Fragment YourRfargment= getFragmentManager().findFragmentByTag("Your Fragment TAG");
updateproFragment.onActivityResult(requestCode, resultCode, data);
break;
}
}
by this you will get your result in fragment's onActivityresult.

Related

Xamarin Forms: Return String from Android Activity

I'm trying to develop a mobile app in Xamarin Forms...One of the functionalities is text recognition. I need to recognize the text and then send it to another page (xaml). So i made an activity where it does recognize the text but i don't know how to return the string "Resultados" (Results). I tried to do a little search and many suggested that the "OnActivityResult" should return the values...but it doesnt get triggered.
Can anyone help me out what i am doing wrong?
TextRecognition.cs - activity(android)
public class TextRecognition : AppCompatActivity, ISurfaceHolderCallback, IProcessor, ITextRecognition
{
private SurfaceView cameraView;
private TextView textView;
private CameraSource cameraSource;
public string Resultados;
private const int RequestCameraPermissionID = 1001;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
cameraView = FindViewById<SurfaceView>(Resource.Id.surface_view);
textView = FindViewById<TextView>(Resource.Id.txtview);
TextRecognizer textRecognizer = new TextRecognizer.Builder(ApplicationContext).Build();
if (!textRecognizer.IsOperational)
{
Log.Error("Main Activity", "Detector dependencies are not yet available");
}
else
{
cameraSource = new CameraSource.Builder(ApplicationContext, textRecognizer)
.SetFacing(CameraFacing.Back)
.SetRequestedFps(2.0f)
.SetRequestedPreviewSize(1280, 1024)
.SetAutoFocusEnabled(true)
.Build();
cameraView.Holder.AddCallback(this);
textRecognizer.SetProcessor(this);
}
Android.Widget.Button logonButton = FindViewById<Android.Widget.Button>(Resource.Id.button_send);
logonButton.Click += delegate {
button_OnClick();
};
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
switch (requestCode)
{
case RequestCameraPermissionID:
{
if (grantResults[0] == Android.Content.PM.Permission.Granted)
{
cameraSource.Start(cameraView.Holder);
}
}
break;
}
}
public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
{
}
public void SurfaceCreated(ISurfaceHolder holder)
{
if (ActivityCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.Camera) != Android.Content.PM.Permission.Granted)
{
ActivityCompat.RequestPermissions(this, new string[]
{
Android.Manifest.Permission.Camera
}, RequestCameraPermissionID);
return;
}
cameraSource.Start(cameraView.Holder);
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
cameraSource.Stop();
}
public void ReceiveDetections(Detections detections)
{
SparseArray items = detections.DetectedItems;
if (items.Size() != 0)
{
textView.Post(() =>
{
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < items.Size(); i++)
{
strBuilder.Append(((TextBlock)items.ValueAt(i)).Value);
strBuilder.Append("\n");
}
textView.Text = strBuilder.ToString();
Resultados = strBuilder.ToString();
});
}
}
async void button_OnClick()
{
Toast.MakeText(this, "Hello from " + Resultados, ToastLength.Long).Show();
Intent data = new Intent(this, typeof(TextRecognition));
SetResult(Result.Ok, data);
Finish();
}
public void Release()
{
}
public string LaunchActivityInAndroid()
{
Activity activity = Forms.Context as Activity;
var intent = new Intent(Forms.Context, typeof(TextRecognition));
activity.StartActivityForResult(intent, Convert.ToInt32(Result.Ok));
return Resultados;
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
switch(resultCode)
{
case Result.Ok:
break;
}
Finish();
}
public interface ITextRecognition
{
}
}
I tried to do a little search and many suggested that the "OnActivityResult" should return the values...but it doesnt get triggered.
You are using OnActivityResult a bit wrong. For example, if you have two Activity, ActivityA and ActivityB, OnActivityResult method in ActivityA, ActivityB need return some value to ActivityA, we can use activityA.StartActivityForResult() to open ActivityB,
ActivityB Use SetResult method to send data to ActivityA.
public class ActivityB: Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
Intent intent = new Intent();
intent.PutExtra("respond", "Hello,Alice!I'm Bob.");
SetResult(Result.Ok, intent);
}
}
Then OnActivityResultwill be triggered in the ActivityA.
I need to recognize the text and then send it to another page (xaml)
If you want to send data from Activity to Forms pages, You can use MessagingCenter to achieve it.
In Activity, we can use following code to send it.
MessagingCenter.Send<App, string>(App.Current as App, "OpenPage", "You send message:" + Resultados);
In the xamarin forms pages, you can use following code to get it.
MessagingCenter.Subscribe<App, string>(App.Current, "OpenPage", (snd, arg) =>
{
var getValue = arg;
});
Here is a link about MessagingCenter.
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center
===========update===========
I write a scan demo. Here is running gif.
Here is interface about dependenceService.
public interface ITextRecognition
{
void LaunchActivityInAndroid();
}
Here is achievement about dependenceService.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Support.V7.App;
using Android.Views;
using Android.Widget;
using FormsTextRecognizer.Droid;
using Xamarin.Forms;
using static Android.Gms.Vision.Detector;
using Android.Gms.Vision;
using Android.Gms.Vision.Texts;
using Android.Support.V4.App;
using Android;
using Android.Content.PM;
using Android.Util;
[assembly: Dependency(typeof(TextRecognition))]
namespace FormsTextRecognizer.Droid
{
[Activity(Label = "ScanActivity", Theme = "#style/Theme.AppCompat.Light.NoActionBar")]
public class TextRecognition : AppCompatActivity, ITextRecognition, ISurfaceHolderCallback, IProcessor
{
// private CameraSource cameraSource;
private SurfaceView cameraView;
TextRecognizer textRecognizer;
private const int RequestCameraPermissionID = 1001;
private CameraSource cameraSource;
public string Resultados;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
cameraView = FindViewById<SurfaceView>(Resource.Id.surface_view);
Android.Widget.Button logonButton = FindViewById<Android.Widget.Button>(Resource.Id.button_send);
textRecognizer = new TextRecognizer.Builder(Android.App.Application.Context).Build();
// Android.Gms.Vision.Frame frame = new Android.Gms.Vision.Frame.Builder().SetBitmap(bitmap).Build();
if (!textRecognizer.IsOperational)
{
Log.Error("Main Activity", "Detector dependancies are not yet available");
}
else
{
cameraSource = new CameraSource.Builder(ApplicationContext, textRecognizer)
.SetFacing(CameraFacing.Back)
.SetRequestedFps(2.0f)
.SetRequestedPreviewSize(1920, 1080)
.SetAutoFocusEnabled(true)
.Build();
cameraView.Holder.AddCallback(this);
textRecognizer.SetProcessor(this);
}
logonButton.Click += LogonButton_Click;
}
private void LogonButton_Click(object sender, EventArgs e)
{
// throw new NotImplementedException();
Toast.MakeText(this, Resultados, ToastLength.Short).Show();
MessagingCenter.Send<App, string>(App.Current as App, "OpenPage", "You send message:" + Resultados);
Finish();
}
public void LaunchActivityInAndroid()
{
//string ScanText = "";
Activity activity = Forms.Context as Activity;
var intent = new Intent(Forms.Context, typeof(TextRecognition));
activity.StartActivity(intent);
// activity.StartActivityForResult(intent, Convert.ToInt32(Result.Ok));
// return Resultados;
}
public void ReceiveDetections(Detections detections)
{
//throw new NotImplementedException();
SparseArray items = detections.DetectedItems;
if (items.Size() != 0)
{
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < items.Size(); i++)
{
strBuilder.Append(((TextBlock)items.ValueAt(i)).Value);
strBuilder.Append("\n");
}
// textView.Text = strBuilder.ToString();
Resultados = strBuilder.ToString();
// });
}
}
public void Release()
{
// throw new NotImplementedException();
}
public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
{
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
switch (requestCode)
{
case RequestCameraPermissionID:
{
if (grantResults[0] == Permission.Granted)
{
cameraSource.Start(cameraView.Holder);
}
}
break;
}
}
public void SurfaceCreated(ISurfaceHolder holder)
{
//throw new NotImplementedException();
if (ActivityCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.Camera) != Android.Content.PM.Permission.Granted)
{
//Request Permission
ActivityCompat.RequestPermissions(this, new string[] {
Android.Manifest.Permission.Camera
}, RequestCameraPermissionID);
return;
}
cameraSource.Start(cameraView.Holder);
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
cameraSource.Stop();
}
}
}
Here is Forms page background code.
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
MessagingCenter.Subscribe<App, string>(App.Current, "OpenPage", (snd, arg) =>
{
scanLabel.Text = arg;
});
}
private void Button_Clicked(object sender, EventArgs e)
{
DependencyService.Get<ITextRecognition>().LaunchActivityInAndroid();
}
}
Here is my demo, you can refer to it.
https://github.com/851265601/FormsTextRecognizer

How to set sourceImagePath, outputFile in Image Editor

I am using a library implementation com.github.iamutkarshtiwari:Ananas:1.2.3. Everything is working fine but I am facing two errors sourceImagePath, outputFilePath. How can I solve it and remove log e and use camera to run app?
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int REQUEST_PERMISSON_SORAGE = 1;
public static final int REQUEST_PERMISSON_CAMERA = 2;
public static final int SELECT_GALLERY_IMAGE_CODE = 7;
public static final int TAKE_PHOTO_CODE = 8;
public static final int ACTION_REQUEST_EDITIMAGE = 9;
private ImageView imgView;
private Bitmap mainBitmap;
private Dialog loadingDialog;
private int imageWidth, imageHeight;
private String path;
private Uri photoURI = null;
private final int PHOTO_EDITOR_REQUEST_CODE = 123;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private Object BaseActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
#Override
protected void onPause() {
compositeDisposable.clear();
super.onPause();
}
#Override
protected void onDestroy() {
compositeDisposable.dispose();
super.onDestroy();
}
private void initView() {
DisplayMetrics metrics = getResources().getDisplayMetrics();
imageWidth = metrics.widthPixels;
imageHeight = metrics.heightPixels;
imgView = findViewById(R.id.img);
View selectAlbum = findViewById(R.id.select_album);
View editImage = findViewById(R.id.edit_image);
selectAlbum.setOnClickListener(this);
editImage.setOnClickListener(this);
View takenPhoto = findViewById(R.id.take_photo);
takenPhoto.setOnClickListener(this);
loadingDialog = BaseActivity.getLoadingDialog(this, R.string.iamutkarshtiwari_github_io_ananas_loading,
false);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_photo:
takePhotoClick();
break;
case R.id.edit_image:
editImageClick();
break;
case R.id.select_album:
selectFromAblum();
break;
}
}
protected void takePhotoClick() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
requestTakePhotoPermissions();
} else {
launchCamera();
}
}
private void requestTakePhotoPermissions() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSON_CAMERA);
return;
}
launchCamera();
}
public void launchCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
Uri outputFileUri = Uri.fromFile(FileUtils.genEditFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
} else {
File file = FileUtils.genEditFile();
Uri photoUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (intent.resolveActivity(getApplicationContext().getPackageManager()) != null) {
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
}
Facing Problem Here
private void editImageClick() {
File outputFile = FileUtils.genEditFile();
try {
Intent intent = new ImageEditorIntentBuilder(this, sourceImagePath, outputFilePath)
.withAddText() // Add the features you need
.withPaintFeature()
.withFilterFeature()
.withRotateFeature()
.withCropFeature()
.withBrightnessFeature()
.withSaturationFeature()
.withBeautyFeature()
.withStickerFeature()
.forcePortrait(true) // Add this to force portrait mode (It's set to false by default)
.build();
EditImageActivity.start(BaseActivity, intent, PHOTO_EDITOR_REQUEST_CODE);
} catch (Exception e) {
Log.e("Demo App", e.getMessage()); // This could throw if either `sourcePath` or `outputPath` is blank or Null
}
}
private void selectFromAblum() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
openAblumWithPermissionsCheck();
} else {
openAlbum();
}
}
private void openAlbum() {
MainActivity.this.startActivityForResult(new Intent(
MainActivity.this, SelectPictureActivity.class),
SELECT_GALLERY_IMAGE_CODE);
}
private void openAblumWithPermissionsCheck() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSON_SORAGE);
return;
}
openAlbum();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSON_SORAGE
&& grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else if (requestCode == REQUEST_PERMISSON_CAMERA
&& grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
launchCamera();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHOTO_EDITOR_REQUEST_CODE) { // same code you used while starting
String newFilePath = data.getStringExtra(EditImageActivity.OUTPUT_PATH);
boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false);
}
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SELECT_GALLERY_IMAGE_CODE:
handleSelectFromAblum(data);
break;
case TAKE_PHOTO_CODE:
handleTakePhoto();
break;
case ACTION_REQUEST_EDITIMAGE:
handleEditorImage(data);
break;
}
}
}
private void handleTakePhoto() {
if (photoURI != null) {
path = photoURI.getPath();
loadImage(path);
}
}
private void handleEditorImage(Intent data) {
String newFilePath = data.getStringExtra(ImageEditorIntentBuilder.OUTPUT_PATH);
boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IS_IMAGE_EDITED, false);
if (isImageEdit) {
Toast.makeText(this, getString(R.string.save_path, newFilePath), Toast.LENGTH_LONG).show();
} else {
newFilePath = data.getStringExtra(ImageEditorIntentBuilder.SOURCE_PATH);
}
loadImage(newFilePath);
}
private void handleSelectFromAblum(Intent data) {
path = data.getStringExtra("imgPath");
loadImage(path);
}
private void loadImage(String imagePath) {
compositeDisposable.clear();
Disposable applyRotationDisposable = loadBitmapFromFile(imagePath)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(subscriber -> loadingDialog.show())
.doFinally(() -> loadingDialog.dismiss())
.subscribe(
this::setMainBitmap,
e -> Toast.makeText(
this, R.string.iamutkarshtiwari_github_io_ananas_load_error, Toast.LENGTH_SHORT).show()
);
compositeDisposable.add(applyRotationDisposable);
}
private void setMainBitmap(Bitmap sourceBitmap) {
if (mainBitmap != null) {
mainBitmap.recycle();
mainBitmap = null;
System.gc();
}
mainBitmap = sourceBitmap;
imgView.setImageBitmap(mainBitmap);
}
private Single<Bitmap> loadBitmapFromFile(String filePath) {
return Single.fromCallable(() ->
BitmapUtils.getSampledBitmap(
filePath,
imageWidth / 4,
imageHeight / 4
)
);
}
}

How to fix "QR scanner is not scanning QR codes"?

I'm trying to develop an Android app that can scan QR codes. But the problem is, it only auto focus on the QR code but not returning any results. Is there a way to fix this?
I'm using zxing libraries.
Hello guys, can someone help me?
I guess you dont have onActivityResult in your code and that is why you cant capture and return any result.
So I am attaching my work and it would help you.
cameraView = (SurfaceView) v.findViewById(R.id.cameraView);
textResult = (TextView) v.findViewById(R.id.textView);
barcodeDetector = new BarcodeDetector.Builder(v.getContext())
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource.Builder(v.getContext(), barcodeDetector)
.setRequestedPreviewSize(640, 640).build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Request permission
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.CAMERA}, RequestCameraPermissionID);
return;
}
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if (qrcodes.size() != 0) {
textResult.post(new Runnable() {
#Override
public void run() {
//Create vibrate
Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
textResult.setText(qrcodes.valueAt(0).displayValue);
showResultDialogue(qrcodes.valueAt(0).displayValue);
}
});
}//End if Statement
}
});
Here is the onActivityResult and I think you dont have it.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//We will get scan results here
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
//check for null
if (result != null) {
if (result.getContents() == null) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
alertDialog.setTitle("Error");
alertDialog.setMessage("Scanning Error. Please try Again");
alertDialog.show();
} else {
//show dialogue with result
showResultDialogue(result.getContents());
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
//method to construct dialogue with scan results
public void showResultDialogue(final String result) {
final AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(getContext(), android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(getContext());
}
//If the text of QR Code is success then Check-in Successful.
//if(result.equalsIgnoreCase("success")){
//Stop the scanner
barcodeDetector.release();
builder.setTitle("Successfully Scan QR Code")
.setMessage("Result ---> " + result)
.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
//Click ok and Back to Main Page
}
}).create().show();

OnBackPress() - Activity is blank using ZBarScannerView

I have implemented Barcode Scanner functionality in my application using ZBarScannerView.
I have an activity which contains multiple fragments and on one fragment I have a scan button. By clicking on that button I jump to scan activity where I have implemented the ZBarScannerView code.
When I got the barcode from scan activity I jumped it back to that fragment which contains the barcode click button. And then if I press back from that fragment it shows blank screen. What should I do?
Please Reply
Code for ScanActivity:
public class ScanActivity extends AppCompatActivity implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
private static final int REQUEST_CAMERA = 1;
ArrayList<ModelProductDetail> modelProductArticleCodeList;
DatabaseHelper databaseHelper;
String article_code;
ArrayList<ModelUnrecognisedCode> modelUnrecognisedCodeArrayList;
ArrayList<ModelUnrecognisedCode> singleUnrecognisedCheck;
//camera permission is needed.
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
databaseHelper = new DatabaseHelper(this);
checkUserPermission();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mScannerView == null) {
mScannerView = new ZBarScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView);
}
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
checkUserPermission();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void checkUserPermission() {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
return;
}
}
loadImage();
}
private void loadImage() {
if (mScannerView == null) {
mScannerView = new ZBarScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView);
}
}
#Override
public void onResume() {
super.onResume();
if (mScannerView instanceof ZBarScannerView) {
mScannerView.startCamera();
mScannerView.setResultHandler(this);
// Stop camera on pause
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mScannerView instanceof ZBarScannerView) {
mScannerView.stopCamera(); // Stop camera on pause
}
}
#Override
public void handleResult(me.dm7.barcodescanner.zbar.Result result) {
String resultCode = result.getContents();
Log.e("TAG", "handleResult: " + resultCode);
mScannerView.stopCamera();
modelProductArticleCodeList = new ArrayList<>();
modelProductArticleCodeList = databaseHelper.getProductByArtCode(resultCode);
if (modelProductArticleCodeList.size() == 0) {
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(getApplicationContext().VIBRATOR_SERVICE);
vibrator.vibrate(1000);
singleUnrecognisedCheck = new ArrayList<>();
singleUnrecognisedCheck = databaseHelper.getUnrecognisedByCode(resultCode);
if (singleUnrecognisedCheck.size() == 0) {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("unrecognised_alert", true);
in.putExtra("unrecognised_code", resultCode);
in.putExtra("jump", "1");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Toast.makeText(this, "not matched code", Toast.LENGTH_SHORT).show();
} else {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("jump", "3");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Toast.makeText(this, "Unrecognised code has already been added.", Toast.LENGTH_SHORT).show();
}
} else {
// for (ModelProductDetail modelProductDetail : modelProductArticleCodeList) {
// article_code = modelProductDetail.getArticle_code();
// }
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("product_art", resultCode);
in.putExtra("source_type", "art");
in.putExtra("jump", "2");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
}
public void changeFragments(Fragment fragment) {
FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
private void getDialog() {
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog_unrecognised_code);
d.setCanceledOnTouchOutside(true);
d.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
final EditText etCode = (EditText) d.findViewById(R.id.etCode);
final EditText etrecognisedComment = (EditText) d.findViewById(R.id.etrecognisedComment);
ImageView imgClose = (ImageView) d.findViewById(R.id.imgClose);
ImageButton ibSubmit = (ImageButton) d.findViewById(R.id.ibSubmit);
imgClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
d.dismiss();
}
});
ibSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ModelUnrecognisedCode modelUnrecognisedCode = new ModelUnrecognisedCode();
modelUnrecognisedCode.setUnrecognised_code(etCode.getText().toString());
modelUnrecognisedCode.setUnrecognised_comment(etrecognisedComment.getText().toString());
databaseHelper.addUnrecognisedCode(modelUnrecognisedCode);
// changeFragments(new SearchProductFragment());
modelUnrecognisedCodeArrayList = new ArrayList<>();
modelUnrecognisedCodeArrayList = databaseHelper.getUnrecognisedCode();
Log.e("TAG", "unrecognised code: " + modelUnrecognisedCodeArrayList.size());
d.dismiss();
}
});
d.show();
}
}
I'm assuming After successful barcode scanning you're fetching product data and if data found then you are changing the screen . So change your else statement with this and see if it works
else {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("product_art", resultCode);
in.putExtra("source_type", "art");
in.putExtra("jump", "2");
startActivity(in);
finish();
}

surface view does not show camera after i gave permission

public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_camera, container, false);
cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
flipCamera = view.findViewById(R.id.flipCamera);
flashCameraButton = view.findViewById(R.id.flash);
captureImage = view.findViewById(R.id.captureImage);
surfaceView = view.findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
flipCamera.setOnClickListener(this);
captureImage.setOnClickListener(this);
flashCameraButton.setOnClickListener(this);
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (Camera.getNumberOfCameras() > 1) {
flipCamera.setVisibility(View.VISIBLE);
}
if (!getActivity().getBaseContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
flashCameraButton.setVisibility(View.GONE);
}
return view;
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (!openCamera(Camera.CameraInfo.CAMERA_FACING_BACK)) {
alertCameraDialog();
}
}
private boolean openCamera(int id) {
boolean result = false;
cameraId = id;
releaseCamera();
try {
camera = Camera.open(cameraId);
} catch (Exception e) {
e.printStackTrace();
}
if (camera != null) {
try {
setUpCamera(camera);
camera.setErrorCallback(new Camera.ErrorCallback() {
#Override
public void onError(int error, Camera camera) {
}
});
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
result = true;
} catch (IOException e) {
e.printStackTrace();
result = false;
releaseCamera();
}
}
return result;
}
private void setUpCamera(Camera c) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
int degree = 0;
switch (rotation) {
case Surface.ROTATION_0:
degree = 0;
break;
case Surface.ROTATION_90:
degree = 90;
break;
case Surface.ROTATION_180:
degree = 180;
break;
case Surface.ROTATION_270:
degree = 270;
break;
default:
break;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
// frontFacing
rotation = (info.orientation + degree) % 330;
rotation = (360 - rotation) % 360;
} else {
// Back-facing
rotation = (info.orientation - degree + 360) % 360;
}
c.setDisplayOrientation(rotation);
Camera.Parameters params = c.getParameters();
showFlashButton(params);
List<String> focusModes = params.getSupportedFlashModes();
if (focusModes != null) {
if (focusModes
.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
params.setFlashMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
}
params.setRotation(rotation);
}
private void showFlashButton(Camera.Parameters params) {
boolean showFlash = (getActivity().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH) && params.getFlashMode() != null)
&& params.getSupportedFlashModes() != null
&& params.getSupportedFocusModes().size() > 1;
flashCameraButton.setVisibility(showFlash ? View.VISIBLE
: View.INVISIBLE);
}
private void releaseCamera() {
try {
if (camera != null) {
camera.setPreviewCallback(null);
camera.setErrorCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("error", e.toString());
camera = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.flash:
flashOnButton();
break;
case R.id.flipCamera:
flipCamera();
break;
case R.id.captureImage:
takeImage();
break;
default:
break;
}
}
private void takeImage() {
camera.takePicture(null, null, new Camera.PictureCallback() {
private File imageFile;
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
// convert byte array into bitmap
Bitmap loadedImage = null;
Bitmap rotatedBitmap = null;
loadedImage = BitmapFactory.decodeByteArray(data, 0, data.length);
// rotate Image
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(rotation);
rotatedBitmap = Bitmap.createBitmap(loadedImage, 0, 0,
loadedImage.getWidth(), loadedImage.getHeight(),
rotateMatrix, false);
String state = Environment.getExternalStorageState();
File folder = null;
if (state.contains(Environment.MEDIA_MOUNTED)) {
folder = new File(Environment
.getExternalStorageDirectory() + "/Demo");
} else {
folder = new File(Environment
.getExternalStorageDirectory() + "/Demo");
}
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
java.util.Date date = new java.util.Date();
imageFile = new File(folder.getAbsolutePath()
+ File.separator
+ new Timestamp(date.getTime()).toString()
+ "Image.jpg");
imageFile.createNewFile();
Toast.makeText(getActivity().getBaseContext(), "Image Saved", Toast.LENGTH_SHORT).show();
openCamera(cameraId);
} else {
Toast.makeText(getActivity().getBaseContext(), "Image Not saved", Toast.LENGTH_SHORT).show();
return;
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
// save image into gallery
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
FileOutputStream fout = new FileOutputStream(imageFile);
fout.write(ostream.toByteArray());
fout.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, imageFile.getAbsolutePath());
getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void flipCamera() {
int id = (cameraId == Camera.CameraInfo.CAMERA_FACING_BACK ? Camera.CameraInfo.CAMERA_FACING_FRONT
: Camera.CameraInfo.CAMERA_FACING_BACK);
if (!openCamera(id)) {
alertCameraDialog();
}
}
private void alertCameraDialog() {
Toast.makeText(getActivity(), "Error to open camera", Toast.LENGTH_SHORT).show();
}
private void flashOnButton() {
if (camera != null) {
try {
Camera.Parameters param = camera.getParameters();
param.setFlashMode(!flashmode ? Camera.Parameters.FLASH_MODE_TORCH
: Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(param);
flashmode = !flashmode;
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
This is my camera fragment code. When i give permission at runtime the surfaceview does not show camera. It show camera at onResume() or on any Button click in that fragment.How to solve this issue. How to set When i click on Allow button in permission it shows camera in surface view automatically.
In onCreate set visibilty of surfaceView as INVISIBLE.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
if (checkCameraHardware(this) == false) {
showDialogForExit();
}
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceView.setVisibility(View.INVISIBLE);
infoTextview = (TextView) findViewById(R.id.info_text);
askForPermissions();
}
Then after attaching cameraSource to surfaceView,set visibilty of surfaceView to VISIBLE again.
surfaceView.setVisibility(View.VISIBLE);
Use this class
public class RunTimePermission extends Activity
{
private Activity activity;
private ArrayList<PermissionBean> arrayListPermission;
private String[] arrayPermissions;
private RunTimePermissionListener runTimePermissionListener;
public RunTimePermission(Activity activity)
{
this.activity = activity;
}
public class PermissionBean
{
String permission;
boolean isAccept;
}
public void requestPermission(String[] permissions, RunTimePermissionListener runTimePermissionListener)
{
this.runTimePermissionListener = runTimePermissionListener;
arrayListPermission = new ArrayList<PermissionBean>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
for (int i = 0; i < permissions.length; i++)
{
PermissionBean permissionBean = new PermissionBean();
if (ContextCompat.checkSelfPermission(activity, permissions[i]) == PackageManager.PERMISSION_GRANTED)
{
permissionBean.isAccept = true;
}
else
{
permissionBean.isAccept = false;
permissionBean.permission = permissions[i];
arrayListPermission.add(permissionBean);
}
}
if (arrayListPermission.size() <= 0)
{
runTimePermissionListener.permissionGranted();
return;
}
arrayPermissions = new String[arrayListPermission.size()];
for (int i = 0; i < arrayListPermission.size(); i++)
{
arrayPermissions[i] = arrayListPermission.get(i).permission;
}
activity.requestPermissions(arrayPermissions, 10);
}
else
{
if (runTimePermissionListener != null)
{
runTimePermissionListener.permissionGranted();
}
}
}
public interface RunTimePermissionListener
{
void permissionGranted();
void permissionDenied();
}
private void callSettingActivity()
{
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
intent.setData(uri);
activity.startActivity(intent);
}
private void checkUpdate()
{
boolean isGranted = true;
int deniedCount = 0;
for (int i = 0; i < arrayListPermission.size(); i++)
{
if (!arrayListPermission.get(i).isAccept)
{
isGranted = false;
deniedCount++;
}
}
if (isGranted)
{
if (runTimePermissionListener != null)
{
runTimePermissionListener.permissionGranted();
}
}
else
{
if (runTimePermissionListener != null)
{
setAlertMessage();
runTimePermissionListener.permissionDenied();
}
}
}
public void setAlertMessage()
{
AlertDialog.Builder adb;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
adb = new AlertDialog.Builder(activity, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
adb = new AlertDialog.Builder(activity);
}
adb.setTitle(activity.getResources().getString(R.string.app_name));
String msg = "<p>Dear User, </p>" +
"<p>Seems like you have <b>\"Denied\"</b> the minimum requirement permission to access more features of application.</p>" +
"<p>You must have to <b>\"Allow\"</b> all permission. We will not share your data with anyone else.</p>" +
"<p>Do you want to enable all requirement permission ?</p>" +
"<p>Go To : Settings >> App > " + activity.getResources().getString(R.string.app_name) + " Permission : Allow ALL</p>";
adb.setMessage(Html.fromHtml(msg));
adb.setPositiveButton("Allow All", new AlertDialog.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
callSettingActivity();
dialog.dismiss();
}
});
adb.setNegativeButton("Remind Me Later", new AlertDialog.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
if (!((Activity) activity).isFinishing() && msg.length() > 0)
{
adb.show();
}
else
{
Log.v("log_tag", "either activity finish or message length is 0");
}
}
private void updatePermissionResult(String permissions, int grantResults)
{
for (int i = 0; i < arrayListPermission.size(); i++)
{
if (arrayListPermission.get(i).permission.equals(permissions))
{
if (grantResults == 0)
{
arrayListPermission.get(i).isAccept = true;
}
else
{
arrayListPermission.get(i).isAccept = false;
}
break;
}
}
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
for (int i = 0; i < permissions.length; i++)
{
updatePermissionResult(permissions[i], grantResults[i]);
}
checkUpdate();
}
}
Write this code in your activity onCreate() Method
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
runTimePermission = new RunTimePermission(this);
runTimePermission.requestPermission(new String[]{Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, new RunTimePermission.RunTimePermissionListener() {
#Override
public void permissionGranted() {
// First we need to check availability of play services
initControls();
identifyOrientationEvents();
//create a folder to get image
folder = new File(Environment.getExternalStorageDirectory() + "/Media");
if (!folder.exists()) {
folder.mkdirs();
}
//capture image on callback
captureImageCallback();
//
if (camera != null) {
Camera.CameraInfo info = new Camera.CameraInfo();
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
imgFlashOnOff.setVisibility(View.GONE);
}
}
}
#Override
public void permissionDenied() {
}
});
then write this code out of onCreate()
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (runTimePermission != null) {
runTimePermission.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
Sorry for late answer, but maybe it will be useful to someone. Just call start camera method in your onRequestPermissionsResult like this:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Utils.log(TAG, "onRequestPermissionsResult call");
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Utils.log(TAG, "Permission granted - show camera");
if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The default way to show camera might look like this:
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
cameraSource.start(surfaceView.getHolder());
Utils.log(TAG, "Check permission: granted - start camera");
} else {
Utils.log(TAG, "Check permission: restricted - request");
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
It worked for me:
before get permission or show any dialogs set surface visibility to GONE
surfaceView.setVisibility(View.GONE);
then after get permission or dismiss dialogs set surface visibility to VISIBLE
surfaceView.setVisibility(View.VISIBLE);
you have to receive your permission details here
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA_PERMISSION:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Here call or Open your camera;
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
for more information :
link 1: https://developer.android.com/training/permissions/requesting.html
link 2: https://www.androidhive.info/2016/11/android-working-marshmallow-m-runtime-permissions/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
for (int result : grantResults) {
if (result == PackageManager.PERMISSION_GRANTED) {
surfaceView.setVisibility(View.VISIBLE); // <----there u go
return;
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
CODE_REQUESTED_1);
}
}
}
}
}

Categories

Resources