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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1124548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:44:10  来源:igfitidea点击:

How to pass the values from one activity to previous activity

androidandroid-activity

提问by Kumar

How do I pass a value from one screen to its previous screen?

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

Consider this case: I have two activities. The first screen has one TextViewand a button and the second activity has one EditTextand a button.

考虑这种情况:我有两个活动。第一个屏幕有一个TextView和一个按钮,第二个活动有一个EditText和一个按钮。

If I click the first button then it has to move to second activity and here user has to type something in the text box. If he presses the button from the second screen then the values from the text box should move to the first activity and that should be displayed in the first activity TextView.

如果我单击第一个按钮,则它必须移动到第二个活动,并且用户必须在此处在文本框中键入一些内容。如果他从第二个屏幕按下按钮,则文本框中的值应移至第一个活动,并应显示在第一个活动中TextView

回答by Reto Meier

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 startActivityForResultfrom your main Activity.

通过startActivityForResult从主活动中使用,将辅助活动(您的“编辑文本”活动)作为子活动启动。

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 setResultbefore calling finishto close the secondary Activity.

在子活动中,您需要创建一个新的 Intent 并将输入的文本值包含在它的 extras 包中,而不仅仅是在用户单击按钮时关闭 Activity。setResult在调用finish关闭辅助活动之前将其传递回父调用。

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 onActivityResultto listen for callbacks from the text entry Activity. Get the extra from the returned Intent to get the text value you should be displaying.

最后一步是在调用 Activity:OverrideonActivityResult以侦听来自文本条目 Activity 的回调。从返回的 Intent 中获取额外的内容以获取您应该显示的文本值。

@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; 
    } 
  } 
} 

回答by Nikhil Agrawal

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

您可以通过多种方式访问​​其他类或活动中的变量或对象。

A. Database

A. 数据库

B. shared preferences.

B. 共享偏好。

C. Object serialization.

C. 对象序列化。

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

D. 可以保存公共数据的类可以命名为公共实用程序,这取决于您。

E. Passing data through Intents and Parcelable Interface.

E. 通过 Intents 和 Parcelable 接口传递数据。

It depend upon your project needs.

这取决于您的项目需求。

A. Database

A.数据库

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

SQLite 是一个嵌入到 Android 中的开源数据库。SQLite 支持标准的关系数据库功能,如 SQL 语法、事务和准备好的语句。

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

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

B. Shared Preferences

B.共享偏好

Suppose you want to store username. So there will be now two thing a KeyUsername, ValueValue.

假设您要存储用户名。所以现在会有两个东西,一个关键用户名,一个值。

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.

使用 putString(),putBoolean(),putInt(),putFloat(),putLong() 你可以保存你想要的数据类型。

How to fetch

如何获取

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

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

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

C. Object Serialization

C.对象序列化

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

使用 java bean 并将其作为他的字段之一存储在其中,并为此使用 getter 和 setter

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.

JavaBean 是具有属性的 Java 类。将属性视为私有实例变量。由于它们是私有的,因此可以从类外部访问它们的唯一方法是通过类中的方法。更改属性值的方法称为 setter 方法,检索属性值的方法称为 getter 方法。

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

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

Get variable in other classes

获取其他类中的变量

D. CommonUtilities

D.公用事业

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

E.通过 Intent 传递数据

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/

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

回答by Sora

you don't have to...

你不必...

Just call newIntent() from second activity

只需从第二个活动中调用 newIntent()

Intent retData=new Intent();

Add data to pass back

添加数据回传

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

Go ahead with setResult

继续使用 setResult

setResult(RESULT_OK, retData);

And can then finish

然后可以完成

finish();

回答by Will

startActivityForResult()

startActivityForResult()

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

这是 SDK 中包含更多信息的链接:

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

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

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

并向下滚动到标题为“从屏幕返回结果”的部分

回答by Ohad Aloni

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

我经常在调用活动中使用静态变量和静态 setter 方法来设置它们。

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.

请注意,只有在您不关心应用程序中同一个活动(类)的多个副本的实例化时才能使用此技巧,但我发现这是最容易实现的,并且我使用它最多.

回答by Alp Altunel

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...)

在您的代码中(例如 OnButtonClick 等...)

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();

@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);
....