onActivityResult() is not calling in fragment - android

I want to scan QR Code in fragment.
But onActivityResult is not calling.
Fragment.java
#Override
public View onCreateView(LayoutInflater inflater ,ViewGroup container ,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate( R.layout.fragment_offer ,container ,false );
scanOffer = view.findViewById( R.id.scanOffer );
scanOffer.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
scanBarcode();
}
} );
return view;
}
public void scanBarcode() {
/** This method will listen the button clicked passed form the fragment **/
Intent intent = new Intent(getContext(),CaptureActivity.class);
intent.setAction("com.google.zxing.client.android.SCAN");
intent.putExtra("SAVE_HISTORY", false);
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
uniqueCode = data.getStringExtra("SCAN_RESULT");
Log.d(TAG, "contents: " + uniqueCode);
Toast.makeText( getContext() ,uniqueCode ,Toast.LENGTH_SHORT ).show();
// callAddStoreContestParticipantService();
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.d(TAG, "RESULT_CANCELED");
}
}
}
Please help me.
onActivityResult() is not calling
CaptureActivity.class opens Qr after scanning onActivityResult() is not calling

Try below code for barcode scan and also override on activity result in parent activity
private static final int BARCODE_REQUEST = 312;
private void startBarcode() {
//IntentIntegrator.forFragment(getActivity().initiateScan()); // `this` is the current Fragment
IntentIntegrator integrator = new IntentIntegrator(getActivity()) {
#Override
protected void startActivityForResult(Intent intent, int code) {
Fragment.this.startActivityForResult(intent, BARCODE_REQUEST); // REQUEST_CODE override
}
};
//IntentIntegrator integrator = new IntentIntegrator(getActivity());
//IntentIntegrator.forSupportFragment(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(true);
integrator.setBarcodeImageEnabled(true);
integrator.setOrientationLocked(false);
integrator.setTimeout(15000);
integrator.initiateScan();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case BARCODE_REQUEST:
IntentResult Result = IntentIntegrator.parseActivityResult(IntentIntegrator.REQUEST_CODE, resultCode, data);
if (Result != null) {
if (Result.getContents() == null) {
Timber.i("cancelled scan");
showSnackbar("cancelled scan", true);
} else {
Timber.i("Scanned");
showSnackbar("Code scan successfully", false);
try {
long id = Long.parseLong(Result.getContents());
// getFood(id);
searchBarcode(Result.getContents());
} catch (Exception e) {
e.printStackTrace();
}
// searchBarcode(Result.getContents());
//getFood(Long.valueOf(mItem.get(position - 1).getID()));
}
} else {
showSnackbar("Barcode not scanned", true);
Timber.i("Barcode Result is NULL");
super.onActivityResult(requestCode, resultCode, data);
}
break;
}
}
You can get reference from this example:Barcode Scanner

you have to call getActivity().startActivityForResult(intent, 0);
in your fragment
and in your activity you in onActivityResultMethod() you have to call yourfragmnt.onActivityResult()

Related

Disable button in a Listview's row while getting response of a save?

Issue:
I have a Listview in Mainactivity. Each row of listview has two buttons say SET and RUN.
Pressing SET will take you to SET activity and if the user clicks save button in SET Activity, I need to disable the SET button in the corresponding row position of the listview in mainactivity.
So Far Done:
For that I have a refresh function on a onclicklistener to requery the list with updated values. How to call that refresh function without keypress in the Mainactivity or is there any other way?
Activity MAIN :
viewHolder.ButtonSET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = v.getTag().toString();
if (title.equals("SET")) {
if (Integer.parseInt((String) viewHolder.TDNQTY.getText()) > 0) {
if(scanoverornot(pos)<=0) {
Intent s = new Intent(DN.this, SETActivity.class);
s.putExtra("position", pos);
s.putExtra("mode", "SET");
try{
startActivityForResult(s, saverequestcode);
// getContext().startActivity(s);
}
catch(Exception e){
Toast.makeText(getContext(),""+e,Toast.LENGTH_LONG).show();
}
}
}
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case saverequestcode:
if (resultCode == RESULT_OK) {
String SItem= data.getStringExtra("SItem");
int SPos= data.getIntExtra("SPos", 0);
saved = 700;
Toast.makeText(getApplicationContext(), ""+ SItem+ SPos, Toast.LENGTH_LONG).show();
//btnvalidate.performClick();
}
}
}
Activity SET :
Intent sav = new Intent();
sav.putExtra("SItem", String.valueOf(itemno));
sav.putExtra("SPos", String.valueOf(pos));
setResult(RESULT_OK, sav);
finish();
You can use startActivityForResult to nail this purpose:
startActivityForResult(new Intent(this, DestinationActivity.class), MY_RESULT);
And then in your MainActivity:
public int MY_RESULT = 10;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_RESULT) {
if (resultCode == Activity.RESULT_OK) {
//refresh the list according to your logic
}
}
}
Don't forget to call setResult(Activity.RESULT_OK); when user clicks save button.
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setResult(Activity.RESULT_OK);
}
});
Issue Lines:
Have to add super.onActivityResult(requestCode, resultCode, data);
Removed switch case and used if condition for requestCode check
Solution:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null)
return;
if (requestCode == saverequestcode) {
if (resultCode == Activity.RESULT_OK) {
String SItem = data.getStringExtra("SItem");
String SPos = data.getStringExtra("SPos");
Toast.makeText(getApplicationContext(), "Item :" + SItem + "Position :" + SPos, Toast.LENGTH_LONG).show();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Any methods
}
}
else if (requestCode == importrequestcode){
}
}
Activity SET :
Intent sav = new Intent();
sav.putExtra("SItem", String.valueOf(itemno));
sav.putExtra("SPos", String.valueOf(pos));
setResult(Activity.RESULT_OK,sav);
finish();

Use onActivityResult when button IsClicked

I have an activity that once a ToggleButton is clicked, it starts another activity as follows:
Intent intent = new Intent(ChatActivity.this, BBActivity.class);
startActivityForResult(intent,1);
In that second activity it performs few calculations and then:
confirmedData.putExtra( "confirmedB", (Serializable) bSelected );
confirmedData.putExtra( "dateInMillis",DateInMillis );
setResult(ChatActivity.RESULT_OK,confirmedData);
Then, I use the following to get the results in my first activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == ChatActivity.RESULT_OK){
ArrayList<DiscoverB> confirmedB = (ArrayList<DiscoverB>)data.getSerializableExtra("confirmedB");
Long DateInMillis = data.getLongExtra( "dateInMillis", System.currentTimeMillis());
Log.d("ERROR", "error");
}
if (resultCode == ChatActivity.RESULT_CANCELED) {
}
}
}
Now, I had like to use confirmedB Once a button in my activity is clicked.
How can I pass the values from onActivityResult to my ClickListener?
ChatAdapter.OnConfirmClickListener confirmListener = new ChatAdapter.OnConfirmClickListener(){
#Override
public void onClick(Button confirmB) {
???myarraylist = onActivityResult(requestCode, resultCode, data)???
HERE I NEED MY confirmedB
}
};
Thank you
In your first activity, declare a variable
ArrayList<DiscoverB> confirmedB;
In OnActivityResult, you can initialize confirmedB
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == ChatActivity.RESULT_OK){
confirmedB = (ArrayList<DiscoverB>)data.getSerializableExtra("confirmedB");
Long DateInMillis = data.getLongExtra( "dateInMillis", System.currentTimeMillis());
Log.d("ERROR", "error");
}
if (resultCode == ChatActivity.RESULT_CANCELED) {
}
}
}
You can use it now in your clickListener,
ChatAdapter.OnConfirmClickListener confirmListener = new ChatAdapter.OnConfirmClickListener(){
#Override
public void onClick(Button confirmB) {
???myarraylist = onActivityResult(requestCode, resultCode, data)???
here you can use confirmedB
}
};

zxing not returning scanned QR code when in landscape mode in Android

I'm using zxing to read QR codes. It works fine when I scan a code when the phone is in portrait mode, but when I scan in landscape mode it appears to return, but the onActivityResult method is never called (my breakpoint isn't even hit).
From build file:
compile 'com.journeyapps:zxing-android-embedded:3.0.2#aar'
compile 'com.google.zxing:core:3.2.0'
Code from the activity. This is called but at that point fragment is null:
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (fragment != null && Activity.RESULT_OK == resultCode) {
fragment.onActivityResult(requestCode, resultCode, intent);
}
}
Here is my code from the fragment:
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
// Handle QR scan result
if (Activity.RESULT_OK == resultCode) {
final IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanResult != null) {
final String contentString = scanResult.getContents();
if (Strings.isNotEmpty(contentString)) {
processDataAsynchronously(contentString);
}
}
}
}
OnClick code:
#Override
public void onClick(final View v) {
int viewId = v.getId();
if (viewId == R.id.check_qr_button) {
// Get permissions to use the camera
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
final Runnable cameraPermissionsRunnable = new Runnable() {
#Override
public void run() {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
};
// Why we request this permission
DialogManager.showOkDialog(getActivity(), R.string.permissions_explanation_camera_qr, true, cameraPermissionsRunnable, true, true);
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
} else {
IntentIntegrator.forSupportFragment(this).initiateScan();
//ALSO TRIED THIS BUT DIDN'T WORK EITHER
/*
final IntentIntegrator integrator = new IntentIntegrator(getActivity());
integrator.setOrientationLocked(false);
integrator.setBeepEnabled(true);
integrator.initiateScan();
*/
}
return;
}
super.onClick(v);
}
Thanks for any tips!

startActivityForResult doesn't work in a Fragment while image upload from camera or gallery

public class Profile extends Fragment implements Profile_frg{
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog d = new Dialog(mainActivity);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.activity_custom_dialog);
d.setCanceledOnTouchOutside(true);
gallery = (ImageView) d.findViewById(R.id.imageView1);
camera = (ImageView) d.findViewById(R.id.imageView2);
cancel = (ImageView) d.findViewById(R.id.imageView3);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
d.dismiss();
}
});
gallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent gintent = new Intent();
gintent.setType("image/*");
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(
gintent, "Select Picture"), PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(mainActivity,
e.getMessage(), Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
d.dismiss();
}
});
camera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// define the file-name to save photo taken by Camera
// activity
String fileName = "new-photo-name.jpg";
// create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image captured by camera");
// imageUri is the current activity attribute, define
// and save it for later usage (also in
// onSaveInstanceState)
imageUri = context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
// create new Intent
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, PICK_Camera_IMAGE);
d.dismiss();
}
});
d.show();
}
});
}// Work Fine till here...
public void onActivityResult(int requestCode,int resultCode,Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}//didn't detect this method
Yes, there is no onActivityResult() callback in fragments.
You have to override activityResult method in your host activity(in which your fragment is defined)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == GALLERY/CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Fragment yourFragment = getSupportFragmentManager().findFragmentByTag("FRAGMENT_TAG"); // same tag while adding fragment for the first time.
if (yourFragment != null) {
yourFragment.onActivityResult(requestCode, resultCode, data); //calling method that should be defined in your fragment.
}
}
super.onActivityResult(requestCode, resultCode, data);
}
And in your fragment do like this :
public void onActivityResult(int requestCode,int resultCode,Intent data) {
...
Pull your image data from data object
do your further process from here.
...
}
Yes, startActivityForResult will not work directly if you are calling it from any fragment. After getting the result, the callback will hit the onActivityResult of the Hosting Activity from where you have to manually redirect it to the respective fragment.
Below is the sample code of the onActivityResult of your Activity. Please note that this only redirect the result to the respective fragment.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1001:
Fragment frag = getSupportFragmentManager().findFragmentByTag("TAG"); // TAG should be same as the one you entered while adding the fragment
if (frag != null) {
frag .onActivityResult(requestCode, resultCode, data);
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}

Android Camera passing bitmap from Camera Intent to MainActivity

I am trying to take a picture and set it in my MainActivity to an ImageView.
I want to have my camera activity as a seperate class so i tried the following:
MainActivity:
public void onClick(View v) {
switch (v.getId()) {
case R.id.action_button:
Intent camera = new Intent(MainActivity.this,Camera.class);
startActivityForResult(camera ,CAMERA_IDENTIFITER);
break;
default:
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
Log.d("onActivityResult","Sucessfully callbacked!"); //This one wont be executed!
switch(requestCode) {
case (CAMERA_IDENTIFITER) : {
if (resultCode == Activity.RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
mImageView.setImageBitmap(bitmap);
}
break;
}
}
}
And this is my camera Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
pm = getPackageManager();
}
#Override
protected void onStart() {
super.onStart();
if(!isFromActivityResult){
dispatchTakePictureIntent();
}
}
public void dispatchTakePictureIntent() {
if (takePictureIntent.resolveActivity(pm) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch {...}
if (photoFile != null) {
pictureTaken = true;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
bitmap = ImageFileHandler.handleSamplingAndRotationBitmap(this, Uri.fromFile(new File(mCurrentPhotoPath)));
//mImageView.setImageBitmap(bitmap);
resultIntent = new Intent();
resultIntent.putExtra(MediaStore.EXTRA_OUTPUT,
bitmap);
setResult(Activity.RESULT_OK, resultIntent);
Log.d("onActivityResult","finish() executed!"); //This one gets executed!
finish();
} catch {...}
}
}
The camera intent is starting properly but when i take a picture i dont get back to the onActivityResult in my MainActivity , i'm stuck in the Camera intent.
Your onStart() gets called after onActivityResult() is being executed. Hence starting camera intent again and again. Put Logs and test your self.
To solve the issue
Keep a boolean variable in your activity isFronActivityResult. Keep default value as false and do isFromActivityResult = true; inside onActivityResult(). In onStart do the following:
#Override
protected void onStart() {
super.onStart();
if(!isFromActivityResult)
dispatchTakePictureIntent();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
bitmap = ImageFileHandler.handleSamplingAndRotationBitmap(this, Uri.fromFile(new File(mCurrentPhotoPath)));
//mImageView.setImageBitmap(bitmap);
resultIntent = new Intent();
resultIntent.putExtra(MediaStore.EXTRA_OUTPUT,
bitmap);
setResult(Activity.RESULT_OK, resultIntent);
isFromActivityResult = true;// add this line
finish();
} catch {...}
}
}

Categories

Resources