Skip to main content

Android - receiving result from another activity

Its a common operation in Android application to launch new activity all the time. There are times when you want to receive the result from new activity started. For example in one of my recent projects I have to launch settings activity (SettingsActivity) to set the mode of application and when this activity is closed it should return the selected mode to the caller activity (MainActivity).

How child Activity returns result
Activity class has a method setResult which sets the result code to be returned to parent activity. Another overload of setResult allows you to pass Intent also for any extra data to be sent.
In my SettingsActivity I have code like this
if (settingsSavedByUser()){
    Intent i=new Intent();
    i.putExtra("mode","selectedApplicationMode");
    setResult(RESULT_OK,i); //RESULT_OK and Intent(i) will be returned to parent
}else{
    setResult(RESULT_CANCELLED); //RESULT_CANCELLED will be returned to parent
}
How parent Activity receive result
Activity class has method onActivityResult which we can override to receive the result from any child Activity started. Here is how I use onActivityResult in MainActivity to receive results from SettingsActivity
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data){
    //SETTINGS_REQUEST_CODE is defined in my app as an integer (98621)
    if (requestCode==SETTINGS_REQUEST_CODE){
        if (resultCode==RESULT_OK){
            //it means settings were save so we can get selected application
            //mode from Intent(data)
            String selectedMode=data.getExtras().getString("mode","");
            Toast toast = Toast.makeText(this,"Selected mode: "+selectedMode,Toast.LENGTH_SHORT);
            toast.show();
        }else{
            Toast toast = Toast.makeText(this,"Cancelled",Toast.LENGTH_SHORT);
            toast.show();
        }
    }
    super.onActivityResult(requestCode,resultCode,data);
}

Starting child activity to receive result
To start Activity when you want to receive result from that Activity in onActivityResult you use method startActivityForResult. Here is how I start SettingsActivity from my MainActivity
Intent i=new Intent(this,SettingsActivity.class);
startActivityForResult(i,SETTINGS_REQUEST_CODE);

Comments

Popular posts from this blog

Decoding JPEG image file using libavcodec

I got a chance to work on a video encoding application that decodes series of jpeg files and convert them into ogg theora video file. I used the infamous libavcodec library that is used in FFMPEG . I decided to write blog posts explaining how I decode jpeg images and convert them into ogg video file. This is the first part and in this I will explain how to decode jpeg images using libavcodec. To learn how to write decoded images as a ogg video file please read http://random-stuff-mine.blogspot.com/2017/07/encoding-raw-images-to-ogg-theora-video.html Before reading this blog post you must be aware of using and setting up libavcodec. I highly recommend this tutorial to get basics of using libavcodec http://www.ffmpeg.org/doxygen/0.6/api-example_8c-source.html Allocating input format context We will first allocate input format for reading the file. We will use avformat_open_input function that will allocate AVFormatContext structure passed to it , the function detects input typ...

Multithreaded C# TCP server to handle multiple clients

I decided to write a minimal multithreaded TCP based server as a blog post. Following class can serve as a skeleton for any small or large scale multithreaded TCP socket server. It do not contain much error handling , it is only to give an idea that how multithreaded server works and how it can process multiple clients using threading. using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections.Generic; namespace RandomStuffMine { public class MTServer {     public int Port{get;set;}     public Socket ServerSocket{get;set;}     private List<Client> Clients=new List<Client>();     private bool runServer=true;     public MTServer(int port)     {         Port=port;         ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);     }   ...

CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information

I created a new Blazor Server app in Visual Studio 2019 and tried to run it. But I was getting this error CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information. I couldn't find any reason or solution to this problem. I tried creating the project multiple times but same error. I created a new .Net Core Web App and added a new razor component and included that component in a razor page (cshtml file) like this @(await Html.RenderComponentAsync<GeofenceWork>(RenderMode.ServerPrerendered)) and <component type="typeof(GeofenceWork)" render-mode="serverprerendered" /> As soon as I navigate to this page that has component added I got the same error: CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information. This was very frustrating. After hours of trying and searching I figured out the solution.  ...