Learn how to transfer data to and from an activity in android using Intents.
My Demo application consists of 2 activities
MainActivity
newactivity
Content:
In MainActivity, there is layout which contains, a Text View to display 'Activity 1. and an Edit Text to enter the text which you will be transferring to new_activity. and a 'click me' Button on click of which, the second activity should start with the data in the edit text packed and sent to the second activity through an intent.
Code for the Java class 'MainActivity.java' is as follows,
Code for the Layout of MainActivity - 'activity_main.xml' is as follows,
In new_activity, there is a Text View which will display the data received from the MainActivity. and a 'Send back the data' button, on click of which "Data successfully returned" string is sent back to the MainActivity and is displayed in the Edit Text. (this is receiving data)
Code for the Java class 'newactivity.java' is as follows,
Code for the Layout of new_activity - 'activity_newactivity.xml' is as follows,
Some Functions used in the code and its brief explanation:
PutExtra(String id, value):
Use the 'putExtra(string id,value)' function. id should match during extraction process. Learn more here.
StartActivityforResult(Intent, Request_code)
This calls an intent and starts an activity and when returning, will handle the result sent back from the called activity. Received data should be handled in 'OnActivityResult()' method. see below. Learn more about 'StartActivityforResult()'.
OnActivityResult(int request_code, int result_code, Intent data)
This will handle the result returned back from an activity which was called for a result using 'StartActivityforResult()' method. Parameters are 'request code' , 'result code', and 'data returned'. If the result was successful, result code will be 'RESULT_OK'.Learn more about each parameter and this function here.
setResult(RESULT_CODE, RESULT_INTENT)
This is to set the result to an intent and send it back to the called activity which is handled there in 'OnActivityResult()'. two parameters here. One is the result code. That is 'RESULT_OK' if the result was successful. and the second parameter is 'Intent' which contains the data to be returned. Learn more about this here.
finish()
This function finishes the current activity.
Watch the video demonstration at my YouTube channel.
Queries will be cleared if comments are dropped. ;)
He is a simple passionate tech freak who himself is an engineering student at Canara Engineering college. He likes App Development, Web designing, Blogging, Youtubing, Debugging and also is a CodeGeek!
Share your views about this article!