Krish Krish - 5 months ago 30
Android Question

onActivityResult not calling in Fragment's

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 barcode i am getting those barcode result where ever i want using onActivityResult method

Here my problem is when i scanning 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);
}
}

Answer

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.

Comments