onActivityResult() not called in new nested fragment API - java

I have been using the new nested fragment API that Android includes in the support library.
The problem that I am facing with nested fragments is that, if a nested fragment (that is, a fragment that has been added to another fragment via the FragmentManagerreturned by getChildFragmentManager()) calls startActivityForResult(), the nested fragment's onActivityResult() method is not called. However, both the parent fragment's onActivityResult() and activity's onActivityResult() do get called.
I don't know if I am missing something about nested fragments, but I did not expect the described behavior. Below is the code that reproduces this problem. I would very much appreciate if someone can point me in the right direction and explain to me what I am doing wrong:
package com.example.nestedfragmentactivityresult;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends FragmentActivity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, new ContainerFragment())
.commit();
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// This is called
Toast.makeText(getApplication(),
"Consumed by activity",
Toast.LENGTH_SHORT).show();
}
public static class ContainerFragment extends Fragment
{
public final View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
View result = inflater.inflate(R.layout.test_nested_fragment_container,
container,
false);
return result;
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
getChildFragmentManager().beginTransaction()
.add(R.id.content, new NestedFragment())
.commit();
}
public void onActivityResult(int requestCode,
int resultCode,
Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// This is called
Toast.makeText(getActivity(),
"Consumed by parent fragment",
Toast.LENGTH_SHORT).show();
}
}
public static class NestedFragment extends Fragment
{
public final View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
Button button = new Button(getActivity());
button.setText("Click me!");
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
startActivityForResult(intent, 0);
}
});
return button;
}
public void onActivityResult(int requestCode,
int resultCode,
Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// This is NOT called
Toast.makeText(getActivity(),
"Consumed by nested fragment",
Toast.LENGTH_SHORT).show();
}
}
}
test_nested_fragment_container.xml is:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>

I solved this problem with the following code (support library is used):
In container fragment override onActivityResult in this way:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
Now nested fragment will receive call to onActivityResult method.
Also, as noted Eric Brynsvold in similar question, nested fragment should start activity using it's parent fragment and not the simple startActivityForResult() call. So, in nested fragment start activity with:
getParentFragment().startActivityForResult(intent, requestCode);

Yes, the onActivityResult() in nested fragment will not be invoked by this way.
The calling sequence of onActivityResult (in Android support library) is
Activity.dispatchActivityResult().
FragmentActivity.onActivityResult().
Fragment.onActivityResult().
In the 3rd step, the fragment is found in the FragmentMananger of parent Activity. So in your example, it is the container fragment that is found to dispatch onActivityResult(), nested fragment could never receive the event.
I think you have to implement your own dispatch in ContainerFragment.onActivityResult(), find the nested fragment and invoke pass the result and data to it.

Here's how I solved it.
In Activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
List<Fragment> frags = getSupportFragmentManager().getFragments();
if (frags != null) {
for (Fragment f : frags) {
if (f != null)
handleResult(f, requestCode, resultCode, data);
}
}
}
private void handleResult(Fragment frag, int requestCode, int resultCode, Intent data) {
if (frag instanceof IHandleActivityResult) { // custom interface with no signitures
frag.onActivityResult(requestCode, resultCode, data);
}
List<Fragment> frags = frag.getChildFragmentManager().getFragments();
if (frags != null) {
for (Fragment f : frags) {
if (f != null)
handleResult(f, requestCode, resultCode, data);
}
}
}

For Androidx with Navigation Components using NavHostFragment
Updated answer on September 2, 2019
This issue is back in Androidx, when you are using a single activity and you have nested fragment inside the NavHostFragment, onActivityResult() is not called for the child fragment of NavHostFragment.
To fix this, you need manually route the call to the onActivityResult() of child fragments from onActivityResult() of the host activity.
Here's how to do it using Kotlin code. This goes inside the onActivityResult() of your main activity that hosts the NavHostFragment:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.your_nav_host_fragment)
val childFragments = navHostFragment?.childFragmentManager?.fragments
childFragments?.forEach { it.onActivityResult(requestCode, resultCode, data) }
}
This will make sure that the onActivityResult() of the child fragments will be called normally.
For Android Support Library
Old answer
This problem has been fixed in Android Support Library 23.2 onwards.
We don't have to do anything extra anymore with Fragment in Android Support Library 23.2+. onActivityResult() is now called in the nested Fragment as expected.
I have just tested it using the Android Support Library 23.2.1 and it works. Finally I can have cleaner code!
So, the solution is to start using the latest Android Support Library.

I have search the FragmentActivity source.I find these facts.
when fragment call startActivityForResult(), it actually call his parent FragmentActivity's startAcitivityFromFragment().
when fragment start activity for result,the requestCode must below 65536(16bit).
in FragmentActivity's startActivityFromFragment(),it call Activity.startActivityForResult(), this function also need a requestCode,but this requestCode is not equal to the origin requestCode.
actually the requestCode in FragmentActivity has two part. the higher 16bit value is (the fragment's index in FragmentManager) + 1.the lower 16bit is equal to the origin requestCode. that's why the requestCode must below 65536.
watch the code in FragmentActivity.
public void startActivityFromFragment(Fragment fragment, Intent intent,
int requestCode) {
if (requestCode == -1) {
super.startActivityForResult(intent, -1);
return;
}
if ((requestCode&0xffff0000) != 0) {
throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
}
super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff));
}
when result back.FragmentActivity override the onActivityResult function,and check if the requestCode's higher 16bit is not 0,than pass the onActivityResult to his children fragment.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFragments.noteStateNotSaved();
int index = requestCode>>16;
if (index != 0) {
index--;
final int activeFragmentsCount = mFragments.getActiveFragmentsCount();
if (activeFragmentsCount == 0 || index < 0 || index >= activeFragmentsCount) {
Log.w(TAG, "Activity result fragment index out of range: 0x"
+ Integer.toHexString(requestCode));
return;
}
final List<Fragment> activeFragments =
mFragments.getActiveFragments(new ArrayList<Fragment>(activeFragmentsCount));
Fragment frag = activeFragments.get(index);
if (frag == null) {
Log.w(TAG, "Activity result no fragment exists for index: 0x"
+ Integer.toHexString(requestCode));
} else {
frag.onActivityResult(requestCode&0xffff, resultCode, data);
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
so that's how FragmentActivity dispatch onActivityResult event.
when your have a fragmentActivity, it contains fragment1, and fragment1 contains fragment2.
So onActivityResult can only pass to fragment1.
And than I find a way to solve this problem.
First create a NestedFragment extend Fragment override the startActivityForResult function.
public abstract class NestedFragment extends Fragment {
#Override
public void startActivityForResult(Intent intent, int requestCode) {
List<Fragment> fragments = getFragmentManager().getFragments();
int index = fragments.indexOf(this);
if (index >= 0) {
if (getParentFragment() != null) {
requestCode = ((index + 1) << 8) + requestCode;
getParentFragment().startActivityForResult(intent, requestCode);
} else {
super.startActivityForResult(intent, requestCode);
}
}
}
}
than create MyFragment extend Fragment override onActivityResult function.
public abstract class MyFragment extends Fragment {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
int index = requestCode >> 8;
if (index > 0) {
//from nested fragment
index--;
List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null && fragments.size() > index) {
fragments.get(index).onActivityResult(requestCode & 0x00ff, resultCode, data);
}
}
}
}
That's all!
Usage:
fragment1 extend MyFragment.
fragment2 extend NestedFragment.
No more different.Just call startActivityForResult() on fragment2, and override the onActivityResult() function.
Waring!!!!!!!!
The requestCode must bellow 512(8bit),because we spilt the requestCode in 3 part
16bit | 8bit | 8bit
the higher 16bit Android already used,the middle 8bit is to help fragment1 find the fragment2 in his fragmentManager array.the lowest 8bit is the origin requestCode.

For Main Activity you write OnActivityForResult with Super class like as
#Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
beginCrop(result.getData());
} }
For activity Write intent without getActivity()
like as
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, 103);
OnActivityResult for fragment
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 101 && resultCode == getActivity().RESULT_OK && null != data) {
}}

I faced the same problem! I solved it by using static ChildFragment in the ParentFragment, like this:
private static ChildFragment mChildFragment;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mChildFragment.onActivityResult(int requestCode, int resultCode, Intent data);
}

Related

How to pass a callback method between Xamarin Android activites [duplicate]

In my activity, I'm calling a second activity from the main activity by startActivityForResult. In my second activity, there are some methods that finish this activity (maybe without a result), however, just one of them returns a result.
For example, from the main activity, I call a second one. In this activity, I'm checking some features of a handset, such as does it have a camera. If it doesn't have then I'll close this activity. Also, during the preparation of MediaRecorder or MediaPlayer if a problem happens then I'll close this activity.
If its device has a camera and recording is done completely, then after recording a video if a user clicks on the done button then I'll send the result (address of the recorded video) back to the main activity.
How do I check the result from the main activity?
From your FirstActivity, call the SecondActivity using the startActivityForResult() method.
For example:
int LAUNCH_SECOND_ACTIVITY = 1
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);
In your SecondActivity, set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.
For example: In SecondActivity if you want to send back data:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
If you don't want to return data:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
Now in your FirstActivity class, write the following code for the onActivityResult() method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LAUNCH_SECOND_ACTIVITY) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
// Write your code if there's no result
}
}
} //onActivityResult
To implement passing data between two activities in a much better way in Kotlin, please go through 'A better way to pass data between Activities'.
How to check the result from the main activity?
You need to override Activity.onActivityResult() and then check its parameters:
requestCode identifies which app returned these results. This is defined by you when you call startActivityForResult().
resultCode informs you whether this app succeeded, failed, or something different
data holds any information returned by this app. This may be null.
Example
To see the entire process in context, here is a supplemental answer. See my fuller answer for more explanation.
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Add a different request code for every activity you are starting from here
private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// Start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
}
// This method is called when the second activity finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) { // Activity.RESULT_OK
// get String data from Intent
String returnString = data.getStringExtra("keyName");
// set text view with string
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(returnString);
}
}
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
// "Send text back" button click
public void onButtonClick(View view) {
// get the text from the EditText
EditText editText = (EditText) findViewById(R.id.editText);
String stringToPassBack = editText.getText().toString();
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.putExtra("keyName", stringToPassBack);
setResult(RESULT_OK, intent);
finish();
}
}
Complementing the answer from Nishant, the best way to return the activity result is:
Intent returnIntent = getIntent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
I was having a problem with
new Intent();
Then I found out that the correct way is using
getIntent();
to get the current intent.
startActivityForResult: Deprecated in Android X
For the new way we have registerForActivityResult.
In Java :
// You need to create a launcher variable inside onAttach or onCreate or global, i.e, before the activity is displayed
ActivityResultLauncher<Intent> launchSomeActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
// your operation....
}
}
});
public void openYourActivity() {
Intent intent = new Intent(this, SomeActivity.class);
launchSomeActivity.launch(intent);
}
In Kotlin :
var resultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
// your operation...
}
}
fun openYourActivity() {
val intent = Intent(this, SomeActivity::class.java)
resultLauncher.launch(intent)
}
Advantage:
The new way is reduce complexity which we faced when we call the activity from a fragment or from another activity
Easily ask for any permission and get callback
For those who have problem with wrong requestCode in onActivityResult
If you are calling startActivityForResult() from your Fragment, the requestCode is changed by the Activity that owns the Fragment.
If you want to get the correct resultCode in your activity try this:
Change:
startActivityForResult(intent, 1); To:
getActivity().startActivityForResult(intent, 1);
The ActivityResultRegistry is the recommended approach
ComponentActivity now provides an ActivityResultRegistry that lets you handle the startActivityForResult()+onActivityResult() as well as requestPermissions()+onRequestPermissionsResult() flows without overriding methods in your Activity or Fragment, brings increased type safety via ActivityResultContract, and provides hooks for testing these flows.
It is strongly recommended to use the Activity Result APIs introduced in Android 10 Activity 1.2.0-alpha02 and Fragment 1.3.0-alpha02.
Add this to your build.gradle
def activity_version = "1.2.0-beta01"
// Java language implementation
implementation "androidx.activity:activity:$activity_version"
// Kotlin
implementation "androidx.activity:activity-ktx:$activity_version"
How to use the pre-built contract
This new API has the following pre-built functionalities
TakeVideo
PickContact
GetContent
GetContents
OpenDocument
OpenDocuments
OpenDocumentTree
CreateDocument
Dial
TakePicture
RequestPermission
RequestPermissions
An example that uses the takePicture contract:
private val takePicture = prepareCall(ActivityResultContracts.TakePicture()) { bitmap: Bitmap? ->
// Do something with the Bitmap, if present
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener { takePicture() }
}
So what’s going on here? Let’s break it down slightly. takePicture is just a callback which returns a nullable Bitmap - whether or not it’s null depends on whether or not the onActivityResult process was successful. prepareCall then registers this call into a new feature on ComponentActivity called the ActivityResultRegistry - we’ll come back to this later. ActivityResultContracts.TakePicture() is one of the built-in helpers which Google have created for us, and finally invoking takePicture actually triggers the Intent in the same way that you would previously with Activity.startActivityForResult(intent, REQUEST_CODE).
How to write a custom contract
A simple contract that takes an Int as an input and returns a string that the requested Activity returns in the result Intent.
class MyContract : ActivityResultContract<Int, String>() {
companion object {
const val ACTION = "com.myapp.action.MY_ACTION"
const val INPUT_INT = "input_int"
const val OUTPUT_STRING = "output_string"
}
override fun createIntent(input: Int): Intent {
return Intent(ACTION)
.apply { putExtra(INPUT_INT, input) }
}
override fun parseResult(resultCode: Int, intent: Intent?): String? {
return when (resultCode) {
Activity.RESULT_OK -> intent?.getStringExtra(OUTPUT_STRING)
else -> null
}
}
}
class MyActivity : AppCompatActivity() {
private val myActionCall = prepareCall(MyContract()) { result ->
Log.i("MyActivity", "Obtained result: $result")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
button.setOnClickListener {
myActionCall(500)
}
}
}
Check this official documentation for more information.
If you want to update the user interface with the activity result, you can't to use this.runOnUiThread(new Runnable() {}. Doing this, the UI won't refresh with the new value. Instead, you can do this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
return;
}
global_lat = data.getDoubleExtra("LATITUDE", 0);
global_lng = data.getDoubleExtra("LONGITUDE", 0);
new_latlng = true;
}
#Override
protected void onResume() {
super.onResume();
if(new_latlng)
{
PhysicalTagProperties.this.setLocation(global_lat, global_lng);
new_latlng=false;
}
}
This seems silly, but it works pretty well.
In Kotlin
Suppose A & B are activities the navigation is from A -> B
We need the result back from A <- B
in A
// calling the Activity B
resultLauncher.launch(Intent(requireContext(), B::class.java))
// we get data in here from B
private var resultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
when (result.resultCode) {
Activity.RESULT_OK -> {
result.data?.getStringExtra("VALUE")?.let {
// data received here
}
}
Activity.RESULT_CANCELED -> {
// cancel or failure
}
}
}
In B
// Sending result value back to A
if (success) {
setResult(RESULT_OK, Intent().putExtra("VALUE", value))
} else {
setResult(RESULT_CANCELED)
}
It is a very common problem on Android
It can be broken down into three pieces
Start Activity B (happens in Activity A)
Set requested data (happens in activity B)
Receive requested data (happens in activity A)
startActivity B
Intent i = new Intent(A.this, B.class);
startActivity(i);
Set requested data
In this part, you decide whether you want to send data back or not when a particular event occurs.
E.g.: In activity B there is an EditText and two buttons b1, b2.
Clicking on Button b1 sends data back to activity A.
Clicking on Button b2 does not send any data.
Sending data
b1......clickListener
{
Intent resultIntent = new Intent();
resultIntent.putExtra("Your_key", "Your_value");
setResult(RES_CODE_A, resultIntent);
finish();
}
Not sending data
b2......clickListener
{
setResult(RES_CODE_B, new Intent());
finish();
}
The user clicks the back button
By default, the result is set with Activity.RESULT_CANCEL response code
Retrieve result
For that override onActivityResult method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RES_CODE_A) {
// b1 was clicked
String x = data.getStringExtra("RES_CODE_A");
}
else if(resultCode == RES_CODE_B){
// b2 was clicked
}
else{
// The back button was clicked
}
}
I will post the new "way" with Android X in a short answer (because in some case you does not need custom registry or contract). If you want more information, see: Getting a result from an activity
Important: there is actually a bug with the backward compatibility of Android X so you have to add fragment_version in your Gradle file. Otherwise you will get an exception "New result API error : Can only use lower 16 bits for requestCode".
dependencies {
def activity_version = "1.2.0-beta01"
// Java language implementation
implementation "androidx.activity:activity:$activity_version"
// Kotlin
implementation "androidx.activity:activity-ktx:$activity_version"
def fragment_version = "1.3.0-beta02"
// Java language implementation
implementation "androidx.fragment:fragment:$fragment_version"
// Kotlin
implementation "androidx.fragment:fragment-ktx:$fragment_version"
// Testing Fragments in Isolation
debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
Now you just have to add this member variable of your activity. This use a predefined registry and generic contract.
public class MyActivity extends AppCompatActivity{
...
/**
* Activity callback API.
*/
// https://developer.android.com/training/basics/intents/result
private ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
switch (result.getResultCode()) {
case Activity.RESULT_OK:
Intent intent = result.getData();
// Handle the Intent
Toast.makeText(MyActivity.this, "Activity returned ok", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(MyActivity.this, "Activity canceled", Toast.LENGTH_SHORT).show();
break;
}
}
});
Before new API you had :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity .this, EditActivity.class);
startActivityForResult(intent, Constants.INTENT_EDIT_REQUEST_CODE);
}
});
You may notice that the request code is now generated (and hold) by the Google framework.
Your code becomes:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity .this, EditActivity.class);
mStartForResult.launch(intent);
}
});
First you use startActivityForResult() with parameters in the first Activity and if you want to send data from the second Activity to first Activity then pass the value using Intent with the setResult() method and get that data inside the onActivityResult() method in the first Activity.
In your Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.takeCam).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),TakePhotoActivity.class);
intent.putExtra("Mode","Take");
startActivity(intent);
}
});
findViewById(R.id.selectGal).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),TakePhotoActivity.class);
intent.putExtra("Mode","Gallery");
startActivity(intent);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
In Second Activity to Display
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
private static final int PICK_PHOTO_FOR_AVATAR = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_photo);
imageView=findViewById(R.id.imageView);
if(getIntent().getStringExtra("Mode").equals("Gallery"))
{
pickImage();
}
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
}
}
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "Camera Permission Denied..", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
if (data == null) {
Log.d("ABC","No Such Image Selected");
return;
}
try {
Uri selectedData=data.getData();
Log.d("ABC","Image Pick-Up");
imageView.setImageURI(selectedData);
InputStream inputStream = getApplicationContext().getContentResolver().openInputStream(selectedData);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Bitmap bmp=MediaStore.Images.Media.getBitmap(getContentResolver(),selectedData);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e){
}
}
}
You need to override Activity.onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CODE_ONE) {
String a = data.getStringExtra("RESULT_CODE_ONE");
}
else if(resultCode == RESULT_CODE_TWO){
// b was clicked
}
else{
}
}

onActivityResult return data from fragment to activity

I Have an activity A that opens an activity B using startActivityForResult.
Now in activity B it's an activity fragment holder as well it contains an ActionBar with menu items.
Now whenever I press action bar button in activity B it should return data from selected fragment of an activity B not to its holder instead it should return data to activity A because it's the one who did the launch.
So it's basically passing data fragment (inside activity B) to activity B then to Activity A.
I am trying hopelessly to find a way to solve it. Is there any possible way to do it?
Disclaimer there are many ways, this is the one I prefer, not the best ever and not the perfect one, I just like this.
The easiest way, in my opinion, is to pass the data from Fragment inside B to ActivityB, then from ActivityB to ActivityA.
Step 1 to pass data from Fragment to container activity you have many ways; the one I usually use is to use an Interface:
Create interface for ActivityB
public interface IActivityB {
void setDataAAndFinish(whateverType data);
}
Implement interface in your activityB
public class InterventoActivity extends AppCompatActivity implements IInterventoActivity {
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private Bundle dataA = null;
#Override
public void setDataAAndFinish(whateverType data) {
dataA = data;
Intent intent = new Intent();
intent.putExtra("data", data)
setResult(RESULT_OK, intent);
finish();
}
}
Set activityA to request and accept return from ActivityB
first, start activityB for result and not normally
Intent i = new Intent(this, ActivityB.class);
startActivityForResult(i, 1);
Then read result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
whateverType data = data.getStringExtra("data");
}
}
}
Now from fragment
((IActivityB)getActivity()).setDataAAndFinish(myDatas);
You need to declare a function in your ActivityB like the following.
public void sendDataBackToActivityA(String dataToBePassedToActivityA) {
Intent intent = new Intent();
intent.putExtra("data", dataToBePassedToActivityA);
setResult(RESULT_OK, intent);
finish();
}
Now from the Fragment that you launched from ActivityB, just call the method on some action in your Fragment that was launched from ActivityB. So the pseudo implementation of the process in your Fragment should look like the following. Declare this function in your Fragment and invoke the function on some action in your Fragment.
public void sendDataToActivityAFromFragment(String dataToBePassed) {
((ActivityB)getActivity()).sendDataBackToActivityA(dataToBePassed);
}
This will serve your purpose I hope.
You can declare static variables in your A activity and set it from the B activity
Or you can make static class and set variables values from B Activity and get it in A activity
Or you can send the menu value from Activity B to A while you exit Activity B and start activity A by using bundle
this is how you set the data to be passed to activity A in activity B
val resultIntent = Intent()
resultIntent.putExtra(DATA, "closed")
setResult(Activity.RESULT_OK, resultIntent)
finish()
this is how you get data in activity A
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == FILE_UPLOAD_CODE) {
when (resultCode) {
Activity.RESULT_OK -> {
// data here is obtained data of the method paramater
}}}}
In your Activity A.Move from activity A to b like this:-
int YOUR_CODE=101; // it can be whatever you like
Intent i = new Intent(getActivity(), B.class);
startActivityForResult(i,YOUR_CODE);
In your Activity B in its fragment
Intent resultIntent = new Intent();
resultIntent.putExtra("NAME OF THE PARAMETER", valueOfParameter);
...
setResult(Activity.RESULT_OK, resultIntent);
finish();
And in your Activity A's onActivityResult() function do this:-
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (resultCode==YOUR_CODE)
{
String value = (String) data.getExtras().getString("NAME OF THE PARAMETER"); //get Data here
}
}
}
In kotlin: -
In class A
startActivityForResult(Intent(context, B::class.java), 143)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 143) {
if (data!!.extras.get("check").equals("0")) {
childpager.currentItem = 0
}
}
}
In Class B
val intent = Intent()
intent.putExtra("check", "0")
setResult(Activity.RESULT_OK, intent)

onActivityResult in Fragment can't access UI elements

I have a button in Fragment when I press it I open a new activity for result but When I return back to my fragment I found all UI element = null
Please find the code
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), MyActivity.class);
getActivity().startActivityForResult(intent, "3030");
}
});
when choose a value from activity I should back to fragment and set data to textview in the activity.
Intent intent = Activity.this.getIntent();
intent.putExtra("categoryId", id);
intent.putExtra("categoryName", name);
setResult(RESULT_OK, intent);
finish();
and I have put that in the activity that contains the fragment
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 3030 && resultCode == RESULT_OK) {
Fragment fragment = mTabFragments.get(MyFragment.class.getName());
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
and in fragment
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 3030 && resultCode == Activity.RESULT_OK) {
int categoryId = data.getIntExtra("categoryId", 0);
String categoryName = data.getStringExtra("categoryName");
mChooseCategoryTextView.setText(categoryName);
}
}
the problem now that mChooseCategoryTextView is null
Can anyone tell me what is the problem?
To get result in fragment
startActivityForResult(intent,REQ_CODE);
not
getActivity().startActivityForResult(intent,REQ_CODE);
I think the question how you initialise this view?
Since your lunching another activity so your whole fragment my be reconstruct or only onViewCreated recalled again.
So my guess is that you don't reinitialize or override mChooseCategoryTextView reference in one of fragment callbacks.
Try to add more logs and check what's happening for this reference
I believe the error is in the line
Fragment fragment = mTabFragments.get(MyFragment.class.getName());
I assume mTabFragments in an adapter of some sort? I'd have to look at it's code to be sure, but it sounds like it's not returning the right fragment. Make sure that the reference it's returning is the same as the fragment that is being shown on screen.

Custom RecyclerAdapter and startActivityForResult

I have a Fragment that contains a RecyclerView which uses a custom RecyclerAdapter. I have an onClickListener inside my custom RecyclerAdapter - when a position is clicked I want it to start startActivityForResult. So far this works in as such as when it is clicked it starts the Activity as desired. However when I press the back button to go to the Fragment containing the RecyclerView onActivityResult is never called. I have passed in a context to the custom RecyclerAdapter. Is this something that is possible? Or does the Activity/Fragment initiating startActivityForResult be the one that intercepts it? If not I will end up handling the onClick in the Fragment with a gesture detector or something similar, but before that I wanted to give this a fair crack! Note: I have included onActivityResult in the MainActivity which has the Fragment container so the Fragment does receive onActivityResult if startActivityForResult is initiated from the Fragment. My code:
RecyclerAdapter onClickListener:
#Override
public void onClick(View v) {
String titleId = titlesListDataArrayList.get(getLayoutPosition()).getTitle_id();
Intent intent = new Intent(context, CreateItemsActivity.class);
intent.putExtra("TITLE_ID", titleId);
((Activity) context).startActivityForResult(intent, Constants.NEW_ITEMS_REQUEST_CODE);
}
CreateItemsActivity.class - onBackPressed()
#Override
public void onBackPressed() {
Intent intent = new Intent();
setResult(Constants.NEW_ITEMS_REQUEST_CODE, intent);
finish();
}
MyListsFragment.class (contains RecyclerView)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("CALLED", "OnActivity Result");
// if requestCode matches from CreateItemsActivity
if (requestCode == Constants.NEW_ITEMS_REQUEST_CODE) {
Log.e("REQUEST CODE", String.valueOf(requestCode));
populateRecyclerView();
}
}
Also I have this in the MainActivity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// included to allow fragment to receive onActivityResult
}
Your calling Activities onActivityResult will only be called when the second activity finishes and a setResult has been executed.
Since the user is hitting the back button the 2nd activity is finishing without setResult being called.
You'll need to override onBackPressed so you can execute your setResult code.
I see you have implemented this but I think the crux of the issue is that you need to return Activity.RESULT_OK not your request code.
#Override
public void onBackPressed() {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
super.onBackPressed();
}
In this case you don't need to explicitly return your requestCode of Constants.NEW_ITEMS_REQUEST_CODE because Android will forward that automatically.
OK, so IF by any chance somebody else has this problem here is my
solution. I added this code into the MainActivity onActivityResult (note I have a frame container which is where all fragments are inflated):
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// get current fragment in container
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frameContainer);
fragment.onActivityResult(requestCode, resultCode, data);
}
I believe this works as the MainActivity is top in the hierarchy and intercepts the onActivityResult, so basically I just point it where I want it to be used.

Pick image from Gallery in android app : "Method called after release() "

i tried to to pick image from Gallery in my android application but after that an error message appears :
Exception :
java.lang.RuntimeException: Method called after release()
Code :
public class ProductAfter extends Fragment{
......
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
......
}
First Step :
You have to #Override this method to catch the call back from the Gallery to Fragment
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check with your Request code and do stuff with that
}
Second Step:
From the Gallery the call back will be directly to the Parent Activity, So you have to #Override the same method in the parent Activity
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// here check for all the fragments where the method is overidden and callback reaches there
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
if (fragment != null)
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
Hope this will resolve you issues
in TabsPagerAdapter :
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Games fragment activity
return new CategorieFragment();
case 1:
// Movies fragment activity
return new ProductBefore();
case 2:
return new ProductAfter();
case 3:
// Top Rated fragment activity
return new CodeBarreAuto();
}
return null;
}
when i change number cases --> case 2 by case 1 and case 1 by case 2 it's woks fine !!

Categories

Resources