Android basic--startactivityforresult start interface and return data, upload avatar

Source: Internet
Author: User
Tags string back

In the development process of Android application, often appear after starting an interface after filling in some content with the data back to the pre-launch interface, the most typical application is the login process. In many applications of the module, there is "my" this module, in the non-logged-in state click on one of the items, it will pop up the login interface, log in after the completion of my interface, will show some login data, the implementation of this feature will be used to startactivityforresult.

The following is a small demo to illustrate the use of Startactivityforresult, as well as some applications in the actual development.

The demo is as follows:


Main interface layout:

Three buttons, one TextView

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "vertical" > <button android:id= "@+id/btn_a" android:layout_width= "Wrap_content" Android oid:layout_height= "Wrap_content" android:layout_marginleft= "20dip" android:layout_margintop= "20dip" a        ndroid:text= "Start a interface and return data"/> <button android:id= "@+id/btn_b" android:layout_width= "Wrap_content"        android:layout_height= "Wrap_content" android:layout_marginleft= "20dip" android:layout_margintop= "20dip" android:text= "Start B interface"/> <linearlayout android:layout_width= "Match_parent" Android:layout_hei            ght= "Wrap_content" android:layout_margin= "20dip" android:orientation= "Horizontal" > <button            Android:id= "@+id/btn_login"Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Login"/>            <button android:id= "@+id/btn_logout" android:layout_width= "Wrap_content"    android:layout_height= "Wrap_content" android:visibility= "Gone" android:text= "logout"/>        </LinearLayout> <textview android:id= "@+id/tv_content" android:layout_width= "Match_parent"        android:layout_height= "30dip" android:layout_marginleft= "20dip" android:layout_marginright= "20dip" android:layout_margintop= "20dip"/></linearlayout>


Main interface Java code

public void OnClick (View v) {Intent Intent;//TODO auto-generated method Stubswitch (V.getid ()) {Case r.id.btn_a:intent = New Intent (Mainactivity.this, Activitya.class); Intent.putextra ("Data", "information passed to a"); Startactivityforresult (Intent, a ); Break;case r.id.btn_b:intent = new Intent (mainactivity.this, Activityb.class); Intent.putextra ("Data", "information passed to B"); StartActivity (intent); Break;case r.id.btn_login:intent = new Intent (Mainactivity.this,loginactivity.class); Intent.putextra ("Data", "transmitted to the Login interface"); Startactivityforresult (intent, login); Break;case r.id.btn_logout: Btnlogin.setclickable (True); logout.setvisibility (View.gone); Btnlogin.settext ("Login"); break;default:break;}} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {//TODO auto-generated method stub Super.onactivityresult (Requestcode, ResultCode, data); if (ResultCode = = RESULT_OK) {switch (requestcode) {case A:bundle bundle = Data.getextras (); String back = bundle.getstring ("Back"); Toast.maketext (GetapplicatIoncontext (), "A interface data returned by:::::::" +back, 0). Show (); Content.settext ("The data returned from interface a" +back); Break;case Login:bundle Loginbundle = Data.getextras (); String username = loginbundle.getstring ("username"); String Passwrod = loginbundle.getstring ("password"); Content.settext ("Data returned from the login interface" +username+ ":::::::" +passwrod); Btnlogin.settext ("Logged in"); Btnlogin.setclickable (false); logout.setvisibility (view.visible); Toast.maketext (Getapplicationcontext (), username+ ":::.::::" +passwrod, 0). Show (); break;default:break;}}}

There are two main places, one is to start the activity, if you want to bring results back, you need to use Startactivityforresult (intent, Requestcode) This method, the method two parameters one is the intent with the data, The other is the request code, which is used to identify to the activity which activity is returning data, because there may be multiple startactivityforresult in an activity, so when it returns, Activity in order to identify which activity returned data is to be differentiated using requestcode.


There is also an important method Onactivityresult (int requestcode, int resultcode, Intent data) This method is called when the data is returned at the end of Startactivityforresult initiated activity, where the second parameter is the result code and the result code is RESULT_OK, indicating that the activity ends and returns the result.

The first parameter, Requestcode, is the identifier of the activity being activated, which is passed in when the Startactivityforresult method is used.

The third parameter, data, is the intent type, which is the data returned from the activity, which can be obtained by using the Data.getextras () method and then extracting some basic data from the bundle.

Through different result codes, the corresponding operation of the data returned by different activity can be carried out, and some specific function effects may be accomplished reasonably.



So is it true that all startactivityforresult-initiated activity returns data? The answer is no, if you want the activity to return data and some settings to respond to in the activity, see the activity's code

The code for Activitya is as follows:

protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( Savedinstancestate); LinearLayout ll = new LinearLayout (this); Layoutparams params = new Layoutparams (layoutparams.match_parent,layoutparams.wrap_content); Ll.setLayoutParams ( params); ll.setorientation (linearlayout.vertical); TextView TV = new TextView (this), Tv.settext ("I am a Interface"); Ll.addview (TV); Button close = New button (this), Close.settext ("Close interface and Return"), Close.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View v) {Intent Intent = new Intent (); Intent.putextra ("Back", "I am the data returned by a interface"); Setresult ( RESULT_OK, intent); Finish ();}}); Ll.addview (Close); Setcontentview (ll); Toast.maketext (Getapplicationcontext (), Getintent (). Getextras (). getString ("Data"), 0). Show ();

Note that there is a piece of code that is Setresult (RESULT_OK, intent); Immediately after the finish ();

To be able to successfully return data, the activity must call the Setresult method before ending finish (), two parameters of the method, the first being the result code, which is the second parameter in the Onactivityresult method ResultCode, In general, we set this value to RESULT_OK


Activityb no need to return data because it is using startactivity

The code for ACTIVITYB is as follows:

protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.LAYOUT.ACTIVITYB); Button close = (Button) Findviewbyid (r.id.btn_close), Close.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubfinish ();}}); Toast.maketext (Getapplicationcontext (), Getintent (). Getextras (). getString ("Data"), 0). Show ();


Loginactivity's Code:

protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.login); etusername = (EditText) Findviewbyid (r.id.et_username); Etpassword = (EditText) Findviewbyid (R.id.et_password); Button login = (button) Findviewbyid (R.id.btn_login), Login.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method stubstring Password = Etpassword.gettext (). toString (). Trim (); String username = Etusername.gettext (). toString (). Trim (); Toast.maketext (Getapplicationcontext (), "Login successful, return to original interface", 0). Show (); Intent Intent = new Intent (); Intent.putextra (" Username ", username); Intent.putextra (" Password ", password); Setresult (RESULT_OK, intent); Finish ();}); Toast.maketext (Getapplicationcontext (), Getintent (). Getextras (). getString ("Data"), 0). Show ();} 


After the interface login is successful, the user name and password are returned to the main page and displayed, and the main page cannot log on again, you can use the logout operation.


Here, this little demo is done.

The main demo two features, one is to start the activity and bring the results back, the results are displayed on the page.

One is to start the activity without the result return, this kind of operation is more common and simple.


Complete code: http://download.csdn.net/download/yanglfree/7503139


Here's the next startactivityforresult. Another more common Application scenario: upload Avatar


As follows:


Click on the Avatar, pop-up selection dialog box, select Album or take photos, the completion will appear cropping screen, after the completion of the crop, will be displayed in the interface, if there is a server, will be uploaded to the server.

Take a look at the following key pieces of code:

Avatar's Click event:

public void OnClick (view v) {charsequence[] items = {"View Avatar", "Phone album", "Phone photo"};new Alertdialog.builder (mainactivity.this). Settitle ("Upload photo"). Setitems (Items, new Dialoginterface.onclicklistener () {public void OnClick (Dialoginterface dialog, int which) {if (which = = select_picture) {Intent Intent = new Intent (Intent.action_pick); Intent.settype ("image/*"); Startactivityforresult (intent,photo_request_gallery);} else if (which = = Select_camera) {Intent Intent = new Intent ("Android.media.action.IMAGE_CAPTURE");//Determine if the memory card is available, can be stored if (Hassdcard ()) {Intent.putextra (Mediastore.extra_output,uri.fromfile ( Environment.getexternalstoragedirectory (), photo_file_name)));} Startactivityforresult (Intent,photo_request_camera);} else if (which = = Select_scan) {//TODO view Avatar}}). Create (). Show ();});

The Startacitivityforresult method used for starting albums and taking pictures, and because albums and photos are system applications, intent uses the specified intent

Photo: "Android.media.action.IMAGE_CAPTURE"

Albums: Intent.action_pick

In the Activityresult method:

public void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityresult (Requestcode,  ResultCode, data), if (ResultCode = = ACTIVITY.RESULT_OK) {if (Requestcode = = photo_request_gallery) {//Gallery if (data = = NULL) {return;} Uri uri = Data.getdata (); crop (URI);} else if (Requestcode = = Photo_request_camera) {//Take Picture if (Hassdcard ()) {file = new file (Environment.getexternalstoragedirec Tory (), photo_file_name); Crop (Uri.fromfile (FILE));} else {Toast.maketext (this, "No memory card found, no photos saved! ", 0). Show ();}} else if (Requestcode = = photo_request_cut) {//cropping try {bmp = Data.getparcelableextra ("Data");p Hoto.setimagebitmap (BMP); File tempfile = Bitmaputils.savebitmapfile (bmp,photo_file_name); upload (tempfile);//upload to server PD = new ProgressDialog ( This);pd. Setmessage ("Avatar is uploading, please wait later");pd. Show (); catch (Exception e) {e.printstacktrace ();}} }}

Complete code Download: http://download.csdn.net/detail/yanglfree/7504613



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.