Skip to content
Fix Code Error

How to manage startActivityForResult on Android?

March 13, 2021 by Code Error
Posted By: Anonymous

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 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?

Solution

From your FirstActivity call the SecondActivity using 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 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 much better way in Kotlin please go through this link ‘A better way to pass data between Activities‘

Answered By: Anonymous

Related Articles

  • ListView inside ScrollView is not scrolling on Android
  • Android Layout Animations from bottom to top and top…
  • Android : Fragment doesn't fit into Fragment Container
  • How to implement HorizontalScrollView like Gallery?
  • Play sound on button click android
  • How to set dropdown arrow in spinner?
  • Playing HTML5 video on fullscreen in android webview
  • Constraint Layout Vertical Align Center
  • android.view.InflateException: Binary XML file line…
  • Error inflating class android.support.v7.widget.Toolbar?
  • Fragment Not Showing in the Activity
  • onClick for buttons on custom CardView
  • Audio File is not Uploading to Firebase Storage
  • Vue js vuecli3 application does not work in ie11…
  • Integrate ZXing in Android Studio
  • Android adding simple animations while…
  • Failed to load AppCompat ActionBar with unknown…
  • Unable to run Robolectric and Espresso with a…
  • How to use ScrollView in Android?
  • Getting duplicated cardviews using SwipeRefresh Layout
  • Android ListView headers
  • Remove Text from the edit text when edit text is focused
  • MaterialCardView is in front of NavigationView. How…
  • Percentage width in a RelativeLayout
  • Couldn't load memtrack module Logcat Error
  • Android + Pair devices via bluetooth programmatically
  • How to center the content inside a linear layout?
  • Button is null object reference (Android Studio)
  • GridLayout and Row/Column Span Woe
  • Text size and different android screen sizes
  • SeekBar and media player in android
  • Error inflating class…
  • AppCompat v7 r21 returning error in values.xml?
  • Android App crashes on animated gradient background
  • Programmatically Hide/Show Android Soft Keyboard
  • Unable to move from one fragment to another
  • java.lang.NullPointerException: Attempt to invoke…
  • Android: How to Programmatically set the size of a Layout
  • Android app unable to start activity componentinfo
  • Navigation View and Constraint Layout
  • How to turn on front flash light programmatically in…
  • java.lang.RuntimeException: Unable to start activity…
  • Google in-app billing, a toast breaks everything
  • How to Intialize the Binding Properties in the…
  • Could not find androidx.camera:camera-view
  • Fit Image in ImageButton in Android
  • Moving from one activity to another Activity in Android
  • Android - java.lang.SecurityException: Permission…
  • This app won't run unless you update Google Play…
  • Android Camera Preview Stretched
  • Failed linking file resources
  • Android "gps requires ACCESS_FINE_LOCATION" error,…
  • How to hide toolbar in collapsed mode and show in…
  • why do i need to click two times to play audio
  • READ_EXTERNAL_STORAGE permission for Android
  • Android - styling seek bar
  • How to get the design view to look the same on your device
  • IOException: read failed, socket might closed -…
  • CardView not showing Shadow in Android L
  • Android Layout Right Align
  • How to properly record stream from canvas?
  • Android TextView Text not getting wrapped
  • Gridview with two columns and auto resized images
  • ADB - Android - Getting the name of the current activity
  • Move to another EditText when Soft Keyboard Next is…
  • how to show progress bar(circle) in an activity…
  • For loops print only last value
  • How to disable keypad popup when on edittext?
  • How to make custom dialog with rounded corners in android
  • Fragment not showing properly
  • GridLayout (not GridView) how to stretch all children evenly
  • Google Maps Android API v2 - Interactive InfoWindow…
  • Auto-fit TextView for Android
  • Defining a percentage width for a LinearLayout?
  • Duplicate ID, tag null, or parent id with another…
  • How to pass values between Fragments
  • How to receive serial data using android bluetooth
  • DatePicker onDateSet method not running
  • Capture Image from Camera and Display in Activity
  • How to create a Custom Dialog box in android?
  • Put buttons at bottom of screen with LinearLayout?
  • How to get current location in Android
  • How to add Typescript to a Nativescript-Vue project?
  • Android activity life cycle - what are all these…
  • Google Maps Android API v2 Authorization failure
  • Android Transparent TextView?
  • How do I align views at the bottom of the screen?
  • Adding custom radio buttons in android
  • How do I make a LinearLayout scrollable?
  • NullPointerException: Attempt to invoke virtual…
  • Android:java.lang.OutOfMemoryError: Failed to…
  • Add Items to ListView - Android
  • hardcoded string "row three", should use @string resource
  • Android "elevation" not showing a shadow
  • Android list view inside a scroll view
  • How to center the elements in ConstraintLayout
  • Unable to get Notification pop-up
  • android.content.res.Resources$NotFoundException:…
  • Android - How to download a file from a webserver
  • Create a custom View by inflating a layout?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

What are the differences between type() and isinstance()?

Next Post:

How to delete rows from a pandas DataFrame based on a conditional expression

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error