Xamarin.Android OnActivityResult not being called inside a Fragment - android

It appears as if OnActivityResult does not get called after accepting the picture taken from the camera.
Am I calling StartActivityForResult() wrong?, or is there something I am missing.
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Android.OS.Bundle savedInstanceState)
{
var m_View = inflater.Inflate (Resource.Layout.Feed, null);
btnCamera = m_View.FindViewById<Button> (Resource.Id.btnCamera);
btnGallery = m_View.FindViewById<Button> (Resource.Id.btnGallery);
ivPicture = m_View.FindViewById<ImageView> (Resource.Id.imageView1);
btnCamera.Click += (sender, e) => {
//launch gallery
//allow photo editing/saving
var mediaPicker = new MediaPicker (Activity);
if (!mediaPicker.IsCameraAvailable){
// Console.WriteLine ("No Camera!");
}else {
Intent intent = new Intent(MediaStore.ActionImageCapture);
StartActivityForResult(intent, 0);
}
};
btnGallery.Click += (sender, e) => {
//launch gallery
//allow photo editing/saving
var imageIntent = new Intent ();
imageIntent.SetType ("image/*");
imageIntent.SetAction (Intent.ActionGetContent);
StartActivityForResult (
Intent.CreateChooser (imageIntent, "Select photo"), 0);
};
return m_View;
}
protected virtual void OnActivityResult (int requestCode, Result resultCode, Intent data)
{
System.Console.WriteLine ("WOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
Uri contentUri = data.Data;
ivPicture.SetImageURI (data.Data);
}

Hmm.. I created a sample and it worked just fine for me. The only difference I see is that it looks like your override is not correct. It should be public override void OnActivityResult()
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var rootView = inflater.Inflate(Resource.Layout.MainFragment, container, false);
var button = rootView.FindViewById<Button>(Resource.Id.button_camera);
button.Click += (sender, args) =>
{
var intent = new Intent(MediaStore.ActionImageCapture);
StartActivityForResult(intent, 0);
};
return rootView;
}
public override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
Log.Debug("TestFragment", "Got result");
// do what you want with the result here
}

Try changing the data type of resultCode to int, instead of Result and making the overridden function public.
e.g.
public override void OnActivityResult(int requestCode, int resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
}

For the people that use Android.Support.V4.App Fragment. You can override the OnActivityResult method in your Fragment but it will never be called if you use this in combination with a FragmentActivity!
It will be the OnActivityResult of the FragmentActivity that will be called. This can be implemented like following:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
}

Check for request code is same as provided for startActivityForResult(intent, 0) here 0 is request code.. eg if you put 999 here insted of 0 ..then in onActivity result method check for requestcode == 999. it is used to check if the intent is the same as asked for and nothing other than that..
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) { // ADD THIS
// Get Data and do something with it
}
}

Related

Can't access onActivityResult zxing for fragment

I'am trying to read the barcode via Zxing in fragment
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_caddie, container, false);
etCodigo = v.findViewById(R.id.etCodigo);
btnLeerCodigo = v.findViewById(R.id.btnLeerCodigo);
btnLeerCodigo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
escanear();
}
});
text = "";
return v;
}
public void escanear() {
IntentIntegrator intent = IntentIntegrator.forSupportFragment(FragmentCaddie.this);
//IntentIntegrator intent = new IntentIntegrator(getActivity());
intent.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
intent.setPrompt("ESCANEAR CODIGO");
intent.setCameraId(0);
intent.setBeepEnabled(false);
intent.setBarcodeImageEnabled(false);
intent.initiateScan();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Toast.makeText(getContext(), "Cancelaste el escaneo", Toast.LENGTH_SHORT).show();
} else {
text = text + " + " + result.getContents().toString() ;
etCodigo.setText(text);
escanear();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
The issue is it doesn't access the onActivityResult
The hosting activity overrides onActivityResult(), but it did not make a call to super.onActivityResult() for unhandled result codes. Apparently, even though the fragment is the one making the startActivityForResult() call, the activity gets the first shot at handling the result. This makes sense when you consider the modularity of fragments. Once I implemented super.onActivityResult() for all unhandled results, the fragment got a shot at handling the result.
Check this out:
onActivityResult is not being called in Fragment
I hope to be useful for u :)
The solution was quiet simple the onActivityResult that i implemented was Overrided from the parent activity
The solution is to call the fragment onActivityResult from the parent activity
private static final int BARECODE_REQUEST = 114910;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BARECODE_REQUEST) {
super.onActivityResult(requestCode,resultCode,data);
}
}

ArrayList is null after executing onActivityResult

I have Activity > Fragment > RecyclerView .
I am getting data from server in a ArrayList to inflate recyclerView in onCreate() of fragment.
In recyclerView there is Image with which I open camera and click photo.
But when I return after successful image capture, I get my ArrayList null
onCreate in ShipmentFragment :
ArrayList<ShipmentDetails> shipmentList;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shipmentList = getShipmentLists();
}
in activity's onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CAMERA_IMAGE_CAPTURE_REQUEST_CODE:
if (resultCode == RESULT_OK) {
ShipmentFragment shipmentFragment = new ShipmentFragment();
shipmentFragment.entryToList();
} else {
Toast.makeText(OrderActivity.this, "Error capturing image", Toast.LENGTH_SHORT).show();
}
break;
}
entryToList() in ShipmentFragment:
public void entryToList() {
// Here I get shipmentList null
int size = shipmentList.size();
}

resultCode 0 and data zero in onActivityResult

I have activity with one fragment, and then that fragment call some activity which that activity will give some value into first activity. i use onActivityResult but i don't know why resultCode always 0 and data always zero,.
on Activity One i have
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: "+ requestCode +" "+resultCode+" "+data);
}
Activity one have some fragmentX which call activity two
private final int REQUEST_CODE = 10;
private void start (){
Intent intent = new Intent(getContext(),Main2Activity.class);
intent.putExtra("xxx","test1");
getActivity().startActivityForResult(intent,REQUEST_CODE);
}
then in Activity Two, when i touch onBackpress, will pass some value.
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = getIntent().putExtra("yyy","test2");
setResult(RESULT_OK,intent);
}
}
but, i don't know why, onActivityResult i can't get the data.
my final purpose is, i want to setArgument that data to fragmentX.
1.You can call onActivityResult in the fragment
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: "+ requestCode +" "+resultCode+" "+data);
}
2.Use super.onBackPressed(); after setResult in your method
#Override
public void onBackPressed() {
Intent intent = getIntent().putExtra("yyy","test2");
setResult(RESULT_OK,intent);
super.onBackPressed();
}
In first activity write the below code:
1st method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
In Fragment
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// In fragment write your logic here
}
2nd method: (I didn't try but as per doc may be this is one of the reason try once) if it will not work go 1st method its 100 percent solution
Here when your calling second activity using getContext()
getContext() - Returns the context view only current running activity.
getActivity()- Return the Activity this fragment is currently associated with.
Try instead of getContext() use getActivity() when you calling intent to next activity
Ex:
private final int REQUEST_CODE = 10;
Intent intent = new Intent(getActivity(),Main2Activity.class);
intent.putExtra("xxx","test1");
getActivity().startActivityForResult(intent,REQUEST_CODE);
For start new activity
private final int REQUEST_CODE = 10;
private void start (){
Intent intent = new Intent(getContext(),Main2Activity.class);
intent.putExtra("xxx","test1");
getActivity().startActivityForResult(intent,REQUEST_CODE);
}
From Second activity
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = getIntent().putExtra("yyy","test2");
setResult(10,intent);
}
}
you have to set the integer code using which you have started second activity. you have started second activity with the code "10".so use the same value when you setResult(10,intent);
onActivityResult you need to check Request code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==10){
if(data!=null)
{
//you have to manage your own list of fragments for activity because getSupportFragmentManager().getFragments() is deprecated now.
//Send data to fragments
if (arrayFragments != null) {
for (Fragment fragment : arrayFragments) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
}
}
Remember you have to manage your own list of fragments using ArrayList or HashMap.
Hope this will help you if you need any other help inform me.
if you wants to send return data in onActivityResult then you should use super.onBackPressed() after data set in setResult() method
example:
#Override
public void onBackPressed() {
val intent = Intent()
intent.putExtra("IsReturnData", true)
setResult(RESULT_OK,intent);
super.onBackPressed(); //write this line at the end of method
}

In Multi Image Selector OnActivityResult() method is not getting called in Fragment

I am trying to make image selector for application.For that i am using multi-image-selector library which is perfeclty works when used in activity ,but here i want to use it in fragment.so in fragment OnActivityResult() method is not getting called.Can anyone help me to solve this?
Here's my code:
MainActivity.java:(My Main Activity)
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().replace(R.id.frame, new Image_Selecter()).commit();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Utilz.printLog("Parentactivity", "onActivityResult");
Log.e("hererererer", "hererererer");
if (requestCode == REQUEST_IMAGE) {
new Image().onActivityResult(requestCode, resultCode, data);
}
}
}
Image:(My Fragment)
public class Image extends Fragment {
private ArrayList<String> mSelectPath;
private static final int REQUEST_IMAGE = 2;
ArrayList<Uri> mMedia = new ArrayList<Uri>();
Uri uri;
ImageView img;
protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_image, container, false);
img = (ImageView) view.findViewById(R.id.img);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pickImage();
}
});
return view;
}
public void pickImage() {
MultiImageSelector selector = new MultiImageSelector(getActivity());
selector.showCamera(true);
selector.multi();
selector.count(1);
selector.origin(mSelectPath);
selector.start(getActivity(), REQUEST_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE) {
if (resultCode == getActivity().RESULT_OK) {
mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
mMedia.clear();
for (String p : mSelectPath) {
Uri uri = Uri.parse(p);
mMedia.add(uri);
}
uri = mMedia.get(0);
Log.e("uri", " " + uri);
if (!uri.toString().contains("content://")) {
uri = Uri.fromFile(new File(uri.toString()));
Log.e("in if", " uri = " + uri);
}
try {
Glide.with(this)
.load(uri)
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(img);
} catch (Exception e) {
Log.e("Exceptionn", " " + e);
}
}
}
}
Try this in your activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Parentactivity", "onActivityResult");
if (requestCode == REQUEST_IMAGE) { //use request code as REQUEST_IMAGE while starting intent for camera
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame);
fragment.onActivityResult(requestCode, resultCode, data);//calling fragments onActivityResult here
}
}
IIRC onActivityResult doesn't get called on a Fragment, it gets called on your parent Activity. You would need to catch this in the Activity and forward the result on to the fragment.
There are two methods which looks same but behaves little bit different.
If method is called by from activity, its not going to give callback to fragment unless called from fragment.
Activity.startActivityForResult()
Fragment.startActivityForResult()
Check out the library if there is way to calling it from fragment.
I dont know the library, just imaging if you can pass fragment to
MultiImageSelector selector = new MultiImageSelector(getActivity()); or selector.start(getActivity(), REQUEST_IMAGE);
Good luck
Emre
you have to call it with intent
public void pickImage() {
Intent intent = new Intent(getContext(), MultiImageSelectorActivity.class);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
startActivityForResult(intent, REQUEST_IMAGE);
}
if you were doing getActivity().startActivityForResult(intent, REQUEST_IMAGE);
the on OnActivityResult() will happen on activity instead of fragment. The way you are using it is like that, so you need to use the intent way.
also that maybe will make your code to work
public void pickImage() {
MultiImageSelector selector = new MultiImageSelector(getContext());
selector.showCamera(true);
selector.multi();
selector.count(1);
selector.origin(mSelectPath);
selector.start(getContext(), REQUEST_IMAGE);
}

onActivityResult not being called in custom Fragment or anywhere else attempted

There have been many successful answers to this question, but there's still something I'm not understanding or that I'm doing incorrectly. One answer is implementing onActivityResult in the host Activity, but I guess I don't know which one that is or I'm following it wrong.
And no, I'm not calling getActivity.startActivityForResult(), just startActivityForResult().
Depending on a selection made in FirstActivity, one or more other selections are possible, created using Fragments. One Fragment is ButtonFragment, which when selected, starts OptionsActivity, like so:
public class ButtonFragment extends Fragment
{
.....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode != Activity.RESULT_CANCELED)
{
if(requestCode == OPTIONS_REQUEST_CODE)
{
Bundle extras = data.getExtras();
if (extras != null) {
String selection = (String) extras.get("optionsSelection");
data.setText(selection);
}
}
}
}
private void openOptionsActivity()
{
Intent intent = new Intent(getActivity(), OptionsActivity.class);
intent.putExtra("optionsArray", options);
startActivityForResult(intent, OPTIONS_REQUEST_CODE);
}
}
This fragment is being added in BaseActivity:
public class BaseActivity extends FragmentActivity
{
.....
fm.beginTransaction().add(
R.id.FragmentContainer, frag).commitAllowingStateLoss();
fm.executePendingTransactions();
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
finish();
}
}
Inside OptionsActivity:
public class OptionsActivity extends BaseSpinnerActivity
{
.....
private class OptionsAdapter extends BaseSpinnerAdapter
{
public OptionsAdapter(Context context, Object[] values)
{
super(context, values);
}
protected void fillRow(ViewHolder holder, int position)
{
String option = options[position];
if(option != null) {
holder.text.setText(option);
}
}
protected void onRowSelect(View v)
{
Intent returnIntent = new Intent();
String optionSelection = (String)v.getTag();
returnIntent.putExtra("optionSelected", optionSelection);
setResult(RESULT_OK, returnIntent);
finish();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
finish();
}
}
The same thing is done inside BaseSpinnerActivity, which extends from ListActivity. (I know, should use FragmentActivity, but I haven't had a chance to convert it yet.)
None of these onActivityResult()'s are being called.
What am I missing or doing wrong? Any help is appreciated!

Categories

Resources