如何将值从一个活动传递到前一个活动

如何将一个值从一个屏幕传递到其上一个屏幕?

考虑一下这个例子: 我有两个活动。第一屏幕有一个 TextView和一个按钮,第二活动有一个 EditText和一个按钮。

如果我点击第一个按钮,那么它必须移动到第二个活动,这里用户必须在文本框中输入一些东西。如果他从第二个屏幕按下按钮,那么文本框中的值应该移动到第一个活动,并且应该显示在第一个活动 TextView中。

98013 次浏览

startActivityForResult()

And here's a link from the SDK with more information:

http://developer.android.com/guide/appendix/faq/commontasks.html#opennewscreen

and scroll down to the part titled "Returning a Result from a Screen"

To capture actions performed on one Activity within another requires three steps.

Launch the secondary Activity (your 'Edit Text' Activity) as a subactivity by using startActivityForResult from your main Activity.

Intent i = new Intent(this,TextEntryActivity.class);
startActivityForResult(i, STATIC_INTEGER_VALUE);

Within the subactivity, rather than just closing the Activity when a user clicks the button, you need to create a new Intent and include the entered text value in its extras bundle. To pass it back to the parent call setResult before calling finish to close the secondary Activity.

Intent resultIntent = new Intent();
resultIntent.putExtra(PUBLIC_STATIC_STRING_IDENTIFIER, enteredTextValue);
setResult(Activity.RESULT_OK, resultIntent);
finish();

The final step is in the calling Activity: Override onActivityResult to listen for callbacks from the text entry Activity. Get the extra from the returned Intent to get the text value you should be displaying.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (STATIC_INTEGER_VALUE) : {
if (resultCode == Activity.RESULT_OK) {
String newText = data.getStringExtra(PUBLIC_STATIC_STRING_IDENTIFIER);
// TODO Update your TextView.
}
break;
}
}
}

you don't have to...

Just call newIntent() from second activity

Intent retData=new Intent();

Add data to pass back

putExtras (retData.putExtra("userName", getUsrName()));

Go ahead with setResult

setResult(RESULT_OK, retData);

And can then finish

finish();

I often use static variables in the calling activity with static setter methods to set them.

In this way I can change values in any activity at will, regardless of the exact flow of control between the various activities.

Note that this trick can only be used if you don't care about the instantiation of more than one copy of the same activity (class) in the application, yet I found this to be the easiest to implement, and I use it the most.

There are couple of ways by which you can access variables or object in other classes or Activity.

A. Database

B. shared preferences.

C. Object serialization.

D. A class which can hold common data can be named as Common Utilities it depends on you.

E. Passing data through Intents and Parcelable Interface.

It depend upon your project needs.

A. Database

SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements.

Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html

B. Shared Preferences

Suppose you want to store username. So there will be now two thing a Key Username, Value Value.

How to store

 // Create object of SharedPreferences.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("userName", "stackoverlow");


//commits your edits
editor.commit();

Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.

How to fetch

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");

http://developer.android.com/reference/android/content/SharedPreferences.html

C. Object Serialization

Object serlization is used if we want to save an object state to send it over network or you can use it for your purpose also.

Use java beans and store in it as one of his fields and use getters and setter for that

JavaBeans are Java classes that have properties. Think of properties as private instance variables. Since they're private, the only way they can be accessed from outside of their class is through methods in the class. The methods that change a property's value are called setter methods, and the methods that retrieve a property's value are called getter methods.

public class VariableStorage implements Serializable  {


private String inString ;


public String getInString() {
return inString;
}


public void setInString(String inString) {
this.inString = inString;
}




}

Set the variable in you mail method by using

VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);

Then use object Serialzation to serialize this object and in your other class deserialize this object.

In serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

If you want tutorial for this refer this link

http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html

Get variable in other classes

D. CommonUtilities

You can make a class by your self which can contain common data which you frequently need in your project.

Sample

public class CommonUtilities {


public static String className = "CommonUtilities";


}

E. Passing Data through Intents

Please refer this tutorial for this option of passing data.

http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/

The best way to do here is to put variable to a common class which is defined outside the scope

public class Utils
{
public static String mPosition;
}

inside your code (e.g. OnButtonClick etc...)

Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
Utils.mPosition = mViewData.mPosition + "";
LogHelper.e(TAG, "before intent: " + Utils.mPosition);
startActivityForResult(intent, Keys.PICK_CONTACT);

inside the code of

@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Keys.PICK_CONTACT) { if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData();

            //you may use the variable here after intent result
LogHelper.e(TAG, "after intent: " + Utils.mPosition);
....