首页 文章

如何在Android应用程序中的活动之间传递数据?

提问于
浏览
1123

我有一个场景,通过登录页面登录后,每个 activity 上都会有一个退出 button .

单击 sign-out 时,我将传递已登录用户的 session id 以进行注销 . 任何人都可以指导我如何保持所有 activitiessession id

这种情况的任何替代方案

30 回答

  • 16

    活动之间的数据传递主要是通过意图对象 .

    首先,您必须使用 Bundle 类将数据附加到intent对象 . 然后使用 startActivity()startActivityForResult() 方法调用活动 .

    您可以在博客文章Passing data to an Activity中找到有关它的更多信息 .

  • 5

    您可以通过3种方式在应用程序中的活动之间传递数据1.Intent 2.SharedPreferences 3.Application

    在意图中传递数据有一些限制 . 对于大量数据,您可以使用应用程序级别数据共享并将其存储在sharedpref中使您的应用程序大小增加

  • 2

    我最近发布了Vapor API,这是一个jQuery风格的Android框架,可以让各种各样的任务更加简单 . 如上所述, SharedPreferences 是你可以做到这一点的一种方式 .

    VaporSharedPreferences实现为Singleton,因此这是一个选项,并且在Vapor API中它有一个严重超载的 .put(...) 方法,因此您不必明确担心您提交的数据类型 - 只要它受支持 . 它也很流利,所以你可以链接电话:

    $.prefs(...).put("val1", 123).put("val2", "Hello World!").put("something", 3.34);
    

    它还可以选择自动保存更改,并统一读取和写入过程,因此您无需像在标准Android中那样显式检索编辑器 .

    或者你可以使用 Intent . 在Vapor API中,您还可以在VaporIntent上使用可链接重载的 .put(...) 方法:

    $.Intent().put("data", "myData").put("more", 568)...
    

    并将其作为额外的传递,如其他答案中所述 . 您可以从 Activity 检索额外内容,此外,如果您使用的是VaporActivity,则会自动为您完成此操作,以便您可以使用:

    this.extras()
    

    要在 Activity 的另一端检索它们,请切换到 .

    希望有些人感兴趣:)

  • 3

    Updated 请注意,我曾提到使用SharedPreference . 它有一个简单的API,可以在应用程序's activities. But this is a clumsy solution, and is a security risk if you pass around sensitive data. It'中访问,最好使用意图 . 它有一个广泛的重载方法列表,可用于在活动之间更好地传输许多不同的数据类型 . 看看intent.putExtra . 这个link很好地展示了putExtra的用法 .

    在活动之间传递数据时,我首选的方法是为相关活动创建一个静态方法,其中包括启动意图所需的参数 . 然后,它提供了轻松设置和检索参数 . 所以它看起来像这样

    public class MyActivity extends Activity {
        public static final String ARG_PARAM1 = "arg_param1";
    ...
    public static getIntent(Activity from, String param1, Long param2...) {
        Intent intent = new Intent(from, MyActivity.class);
            intent.putExtra(ARG_PARAM1, param1);
            intent.putExtra(ARG_PARAM2, param2);
            return intent;
    }
    
    ....
    // Use it like this.
    startActivity(MyActvitiy.getIntent(FromActivity.this, varA, varB, ...));
    ...
    

    然后,您可以为预期活动创建意图并确保拥有所有参数 . 你可以适应片段 . 上面是一个简单的例子,但你明白了 .

  • 5

    你只需要在调用你的意图时发送额外内容 .

    像这样:

    Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
    intent.putExtra("Variable name", "Value you want to pass");
    startActivity(intent);
    

    现在,在 SecondActivityOnCreate 方法中,您可以像这样获取额外内容 .

    If the value you sent was in long

    long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
    

    If the value you sent was a String

    String value = getIntent().getStringExtra("Variable name which you sent as an extra");
    

    If the value you sent was a Boolean

    Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);
    
  • 40

    最简单的方法是将会话ID传递给您用于启动活动的 Intent 中的注销活动:

    Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
    intent.putExtra("EXTRA_SESSION_ID", sessionId);
    startActivity(intent);
    

    访问意图下一个活动

    String sessionId= getIntent().getStringExtra("EXTRA_SESSION_ID");
    

    Intent的docs有更多信息(请参阅 Headers 为"Extras"的部分) .

  • 34

    您可以使用intent对象在活动之间发送数据 . 假设您有两个活动,即 FirstActivitySecondActivity .

    在FirstActivity内:

    使用意图:

    i = new Intent(FirstActivity.this,SecondActivity.class);
    i.putExtra("key", value);
    startActivity(i)
    

    在SecondActivity里面

    Bundle bundle= getIntent().getExtras();
    

    现在,您可以使用不同的bundle类方法来获取Key从FirstActivity传递的值 .

    例如 . bundle.getString("key")bundle.getDouble("key")bundle.getInt("key")

  • 76

    您还可以通过创建 parcelable 类来传递自定义类对象 . 使其成为可分割的最佳方法是编写您的类,然后将其粘贴到像http://www.parcelabler.com/这样的网站上 . 点击构建,您将获得新代码 . 复制所有这些并替换原始类内容 . 然后-

    Intent intent = new Intent(getBaseContext(), NextActivity.class);
    Foo foo = new Foo();
    intent.putExtra("foo", foo);
    startActivity(intent);
    

    并在NextActivity中得到结果 -

    Foo foo = getIntent().getExtras().getParcelable("foo");
    

    现在您可以像使用的那样简单地使用 foo 对象 .

  • 85

    如果你使用kotlin:

    在MainActivity1中:

    var intent=Intent(this,MainActivity2::class.java)
    intent.putExtra("EXTRA_SESSION_ID",sessionId)
    startActivity(intent)
    

    在MainActivity2中:

    if (intent.hasExtra("EXTRA_SESSION_ID")){
        var name:String=intent.extras.getString("sessionId")
    }
    
  • 9

    Erich指出,传递Intent额外信息是一种很好的方法 .

    Application对象是另一种方式,有时在多个活动中处理相同的状态(而不是必须将其放到任何地方)或者比原语和字符串更复杂的对象时更容易 .

    您可以扩展Application,然后设置/获取您想要的任何内容,并使用getApplication()从任何Activity(在同一个应用程序中)访问它 .

    另外请记住,您可能会看到的其他方法(如静力学)可能会出现问题,因为它们是can lead to memory leaks . 应用程序也有助于解决此问

  • 4

    另一种方法是使用存储数据的公共静态字段,即:

    public class MyActivity extends Activity {
    
      public static String SharedString;
      public static SomeObject SharedObject;
    
    //...
    
  • 10

    它帮助我在上下文中看到事物 . 这是两个例子 .

    传递数据

    主要活动

    • 将要发送的数据放入具有键值对的Intent中 . 有关密钥的命名约定,请参阅this answer .

    • startActivity 开始第二个活动 .

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        // "Go to Second Activity" button click
        public void onButtonClick(View view) {
    
            // get the text to pass
            EditText editText = (EditText) findViewById(R.id.editText);
            String textToPass = editText.getText().toString();
    
            // start the SecondActivity
            Intent intent = new Intent(this, SecondActivity.class);
            intent.putExtra(Intent.EXTRA_TEXT, textToPass);
            startActivity(intent);
        }
    }
    

    第二项活动

    • 你用 getIntent() 获取启动第二项活动的 Intent . 然后,您可以使用 getExtras() 以及在第一个活动中定义的密钥提取数据 . 由于我们的数据是一个字符串,我们在这里只使用 getStringExtra .

    SecondActivity.java

    public class SecondActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
    
            // get the text from MainActivity
            Intent intent = getIntent();
            String text = intent.getStringExtra(Intent.EXTRA_TEXT);
    
            // use the text in a TextView
            TextView textView = (TextView) findViewById(R.id.textView);
            textView.setText(text);
        }
    }
    

    传回数据

    主要活动

    • 使用 startActivityForResult 开始第二个活动,为其提供任意结果代码 .

    • 覆盖 onActivityResult . 当第二个活动完成时调用此方法 . 您可以通过检查结果代码确保它实际上是第二个活动 . (当您从同一个主要活动开始多个不同的活动时,这很有用 . )

    • 从返回 Intent 中提取数据 . 使用键值对提取数据 . 我可以使用任何字符串作为键,但我会使用预定义的 Intent.EXTRA_TEXT ,因为我正在发送文本 .

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
    
        private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        // "Go to Second Activity" button click
        public void onButtonClick(View view) {
    
            // Start the SecondActivity
            Intent intent = new Intent(this, SecondActivity.class);
            startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
        }
    
        // This method is called when the second activity finishes
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            // check that it is the SecondActivity with an OK result
            if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
                if (resultCode == RESULT_OK) {
    
                    // get String data from Intent
                    String returnString = data.getStringExtra(Intent.EXTRA_TEXT);
    
                    // set text view with string
                    TextView textView = (TextView) findViewById(R.id.textView);
                    textView.setText(returnString);
                }
            }
        }
    }
    

    第二项活动

    • 将要发送回上一个活动的数据放入 Intent . 数据使用键值对存储在 Intent 中 . 我选择使用 Intent.EXTRA_TEXT 作为我的密钥 .

    • 将结果设置为 RESULT_OK 并添加保存数据的意图 .

    • 调用 finish() 以关闭第二个活动 .

    SecondActivity.java

    public class SecondActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
        }
    
        // "Send text back" button click
        public void onButtonClick(View view) {
    
            // get the text from the EditText
            EditText editText = (EditText) findViewById(R.id.editText);
            String stringToPassBack = editText.getText().toString();
    
            // put the String to pass back into an Intent and close this activity
            Intent intent = new Intent();
            intent.putExtra(Intent.EXTRA_TEXT, stringToPassBack);
            setResult(RESULT_OK, intent);
            finish();
        }
    }
    
  • 4

    标准方法 .

    Intent i = new Intent(this, ActivityTwo.class);
    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
    String getrec=textView.getText().toString();
    Bundle bundle = new Bundle();
    bundle.putString(“stuff”, getrec);
    i.putExtras(bundle);
    startActivity(i);
    

    现在,在第二个活动中,从捆绑包中检索数据:

    获取捆绑包

    Bundle bundle = getIntent().getExtras();
    

    提取数据......

    String stuff = bundle.getString(“stuff”);
    
  • 3
    Intent intent = new Intent(YourCurrentActivity.this, YourActivityName.class);
    intent.putExtra("NAme","John");
    intent.putExtra("Id",1);
    startActivity(intent);
    

    您可以在其他活动中检索它 . 两种方式:

    int id = getIntent.getIntExtra("id", /* defaltvalue */ 2);
    

    第二种方式是:

    Intent i = getIntent();
    String name = i.getStringExtra("name");
    
  • 32

    试试这个:

    CurrentActivity.java

    Intent intent = new Intent(currentActivity.this, TargetActivity.class);
    intent.putExtra("booktype", "favourate");
    startActivity(intent);
    

    TargetActivity.java

    Bundle b = getIntent().getExtras();
    String typesofbook = b.getString("booktype");
    
  • 14

    你可以使用 Intent

    Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
    mIntent.putExtra("data", data);
    startActivity(mIntent);
    

    另一种方法可能是使用单例模式:

    public class DataHolder {
    
     private static DataHolder dataHolder;
     private List<Model> dataList;
    
     public void setDataList(List<Model>dataList) {
        this.dataList = dataList;
     }
    
     public List<Model> getDataList() {
        return dataList;
     }
    
     public synchronized static DataHolder getInstance() {
        if (dataHolder == null) {
           dataHolder = new DataHolder();
        }
        return dataHolder;
     }
    }
    

    来自您的FirstActivity

    private List<Model> dataList = new ArrayList<>();
    DataHolder.getInstance().setDataList(dataList);
    

    论SecondActivity

    private List<Model> dataList = DataHolder.getInstance().getDataList();
    
  • 1338
    /*
     * If you are from transferring data from one class that doesn't
     * extend Activity, then you need to do something like this.
     */ 
    
    public class abc {
        Context context;
    
        public abc(Context context) {
            this.context = context;
        }
    
        public void something() {
            context.startactivity(new Intent(context, anyone.class).putextra("key", value));
        }
    }
    
  • 19

    你可以使用 SharedPreferences ......

    • 记录 . SharedPreferences 中的时间存储会话ID
    SharedPreferences preferences = getSharedPreferences("session",getApplicationContext().MODE_PRIVATE);
    Editor editor = preferences.edit();
    editor.putString("sessionId", sessionId);
    editor.commit();
    
    • 退出 . 共享偏好中的时间提取会话ID
    SharedPreferences preferences = getSharedPreferences("session", getApplicationContext().MODE_PRIVATE);
    String sessionId = preferences.getString("sessionId", null);
    

    如果您没有所需的会话ID,请删除sharedpreferences:

    SharedPreferences settings = context.getSharedPreferences("session", Context.MODE_PRIVATE);
    settings.edit().clear().commit();
    

    这非常有用,因为有一次你保存了值然后检索活动的任何地方 .

  • 24

    From Activity

    int n= 10;
     Intent in = new Intent(From_Activity.this,To_Activity.class);
     Bundle b1 = new Bundle();
     b1.putInt("integerNumber",n);
     in.putExtras(b1);
     startActivity(in);
    

    To Activity

    Bundle b2 = getIntent().getExtras();
     int m = 0;
     if(b2 != null)
      {
         m = b2.getInt("integerNumber");
      }
    
  • 5

    在活动之间传递数据最方便的方法是传递意图 . 在您要发送数据的第一个活动中,您应该添加代码,

    String str = "My Data"; //Data you want to send
    Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra("name",str); //Here you will add the data into intent to pass bw activites
    v.getContext().startActivity(intent);
    

    你也应该导入

    import android.content.Intent;
    

    然后在下一个Acitvity(SecondActivity)中,您应该使用以下代码从intent中检索数据 .

    String name = this.getIntent().getStringExtra("name");
    
  • 15

    在当前的Activity中,创建一个新的 Intent

    String value="Hello world";
    Intent i = new Intent(CurrentActivity.this, NewActivity.class);    
    i.putExtra("key",value);
    startActivity(i);
    

    然后在新的Activity中,检索这些值:

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String value = extras.getString("key");
        //The key argument here must match that used in the other activity
    }
    

    使用此技术将变量从一个Activity传递到另一个Activity .

  • 6

    查理柯林斯使用 Application.class 给了我一个完美的answer . 我不知道我们可以轻松地将它子类化 . 以下是使用自定义应用程序类的简化示例 .

    AndroidManifest.xml

    赋予 android:name 属性以使用您自己的应用程序类 .

    ...
    <application android:name="MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
    ....
    

    MyApplication.java

    将其用作全局参考持有者 . 它在同一个过程中工作正常 .

    public class MyApplication extends Application {
        private MainActivity mainActivity;
    
        @Override
        public void onCreate() {
            super.onCreate();
        }
    
        public void setMainActivity(MainActivity activity) { this.mainActivity=activity; }
        public MainActivity getMainActivity() { return mainActivity; }
    }
    

    MainActivity.java

    设置应用程序实例的全局“单例”引用 .

    public class MainActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ((MyApplication)getApplication()).setMainActivity(this);
        }
        ...
    
    }
    

    MyPreferences.java

    一个简单的例子,我使用另一个活动实例的主要活动 .

    public class MyPreferences extends PreferenceActivity
                implements SharedPreferences.OnSharedPreferenceChangeListener {
        @SuppressWarnings("deprecation")
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
            PreferenceManager.getDefaultSharedPreferences(this)
                .registerOnSharedPreferenceChangeListener(this);
        }
    
        @Override
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            if (!key.equals("autostart")) {
                ((MyApplication)getApplication()).getMainActivity().refreshUI();
            }
        }
    }
    
  • 4

    我在类中使用静态字段,并获取/设置它们:

    喜欢:

    public class Info
    {
        public static int ID      = 0;
        public static String NAME = "TEST";
    }
    

    要获取值,请在“活动”中使用此值:

    Info.ID
    Info.NAME
    

    用于设置值:

    Info.ID = 5;
    Info.NAME = "USER!";
    
  • 3

    您可以尝试共享首选项,它可能是在活动之间共享数据的好选择

    保存会话ID -

    SharedPreferences pref = myContexy.getSharedPreferences("Session 
    Data",MODE_PRIVATE);
    SharedPreferences.Editor edit = pref.edit();
    edit.putInt("Session ID", session_id);
    edit.commit();
    

    得到他们 -

    SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
    session_id = pref.getInt("Session ID", 0);
    
  • 3

    这是我的最佳实践,当项目庞大而复杂时,它会有很大帮助 .

    假设我有2个活动, LoginActivityHomeActivity . 我想将 LoginActivity 中的2个参数(用户名和密码)传递给 HomeActivity .

    首先,我创建 HomeIntent

    public class HomeIntent extends Intent {
    
        private static final String ACTION_LOGIN = "action_login";
        private static final String ACTION_LOGOUT = "action_logout";
    
        private static final String ARG_USERNAME = "arg_username";
        private static final String ARG_PASSWORD = "arg_password";
    
    
        public HomeIntent(Context ctx, boolean isLogIn) {
            this(ctx);
            //set action type
            setAction(isLogIn ? ACTION_LOGIN : ACTION_LOGOUT);
        }
    
        public HomeIntent(Context ctx) {
            super(ctx, HomeActivity.class);
        }
    
        //This will be needed for receiving data
        public HomeIntent(Intent intent) {
            super(intent);
        }
    
        public void setData(String userName, String password) {
            putExtra(ARG_USERNAME, userName);
            putExtra(ARG_PASSWORD, password);
        }
    
        public String getUsername() {
            return getStringExtra(ARG_USERNAME);
        }
    
        public String getPassword() {
            return getStringExtra(ARG_PASSWORD);
        }
    
        //To separate the params is for which action, we should create action
        public boolean isActionLogIn() {
            return getAction().equals(ACTION_LOGIN);
        }
    
        public boolean isActionLogOut() {
            return getAction().equals(ACTION_LOGOUT);
        }
    }
    

    以下是我在LoginActivity中传递数据的方法

    public class LoginActivity extends AppCompatActivity {
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
    
            String username = "phearum";
            String password = "pwd1133";
            final boolean isActionLogin = true;
            //Passing data to HomeActivity
            final HomeIntent homeIntent = new HomeIntent(this, isActionLogin);
            homeIntent.setData(username, password);
            startActivity(homeIntent);
    
        }
    }
    

    最后一步,这是我在 HomeActivity 中收到数据的方式

    public class HomeActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);
    
            //This is how we receive the data from LoginActivity
            //Make sure you pass getIntent() to the HomeIntent constructor
            final HomeIntent homeIntent = new HomeIntent(getIntent());
            Log.d("HomeActivity", "Is action login?  " + homeIntent.isActionLogIn());
            Log.d("HomeActivity", "username: " + homeIntent.getUsername());
            Log.d("HomeActivity", "password: " + homeIntent.getPassword());
        }
    }
    

    完成!酷:)我只是想分享我的经验 . 如果您从事小型项目,这不应该是一个大问题 . 但是当你在大项目上工作时,当你想要重构或修复bug时,它真的很痛苦 .

  • 2

    尝试执行以下操作:

    创建一个简单的“帮助器”类(您的Intents的工厂),如下所示:

    import android.content.Intent;
    
    public class IntentHelper {
        public static final Intent createYourSpecialIntent(Intent src) {
              return new Intent("YourSpecialIntent").addCategory("YourSpecialCategory").putExtras(src);
        }
    }
    

    这将是您所有意图的工厂 . 每当你需要一个新的Intent时,创建一个IntentHelper中的静态工厂方法 . 要创建一个新的Intent,你应该这样说:

    IntentHelper.createYourSpecialIntent(getIntent());
    

    在你的活动中 . 如果要在“会话”中“保存”某些数据,请使用以下命令:

    IntentHelper.createYourSpecialIntent(getIntent()).putExtra("YOUR_FIELD_NAME", fieldValueToSave);
    

    并发送此意图 . 在目标活动中,您的字段将显示为:

    getIntent().getStringExtra("YOUR_FIELD_NAME");
    

    所以现在我们可以像使用相同的旧会话一样使用Intent(比如servlet或JSP) .

  • 1041

    If you want to tranfer bitmap between Activites/Fragments


    Activity

    To pass a bitmap between Activites

    Intent intent = new Intent(this, Activity.class);
    intent.putExtra("bitmap", bitmap);
    

    And in the Activity class

    Bitmap bitmap = getIntent().getParcelableExtra("bitmap");
    

    Fragment

    To pass a bitmap between Fragments

    SecondFragment fragment = new SecondFragment();
    Bundle bundle = new Bundle();
    bundle.putParcelable("bitmap", bitmap);
    fragment.setArguments(bundle);
    

    To receive inside the SecondFragment

    Bitmap bitmap = getArguments().getParcelable("bitmap");
    

    Transfering Large Bitmaps

    如果您的 Binders 事务失败,这意味着您将大型元素从一个活动转移到另一个活动,从而超出了 Binders 事务缓冲区 .

    So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity ,像这样

    In the FirstActivity

    Intent intent = new Intent(this, SecondActivity.class);
    
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
    byte[] bytes = stream.toByteArray(); 
    intent.putExtra("bitmapbytes",bytes);
    

    And in the SecondActivity

    byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
    Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    
  • 128

    来源类:

    Intent myIntent = new Intent(this, NewActivity.class);
    myIntent.putExtra("firstName", "Your First Name Here");
    myIntent.putExtra("lastName", "Your Last Name Here");
    startActivity(myIntent)
    

    目标类(NewActivity类):

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view);
    
        Intent intent = getIntent();
    
        String fName = intent.getStringExtra("firstName");
        String lName = intent.getStringExtra("lastName");
    }
    
  • 12

    通过Bundle Object从此活动传递参数启动另一个活动

    Intent intent = new Intent(getBaseContext(), YourActivity.class);
    intent.putExtra("USER_NAME", "xyz@gmail.com");
    startActivity(intent);
    

    检索另一个活动(YourActivity)

    String s = getIntent().getStringExtra("USER_NAME");
    

    对于简单类型的数据类型,这是可以的 . 但是如果你想在活动之间传递复杂的数据,你需要先将它序列化 .

    这里我们有员工模型

    class Employee{
        private String empId;
        private int age;
        print Double salary;
    
        getters...
        setters...
    }
    

    您可以使用谷歌提供的Gson lib来序列化这样的复杂数据

    String strEmp = new Gson().toJson(emp);
    Intent intent = new Intent(getBaseContext(), YourActivity.class);
    intent.putExtra("EMP", strEmp);
    startActivity(intent);
    
    Bundle bundle = getIntent().getExtras();
    String empStr = bundle.getString("EMP");
                Gson gson = new Gson();
                Type type = new TypeToken<Employee>() {
                }.getType();
                Employee selectedEmp = gson.fromJson(empStr, type);
    
  • 3

    补充答案:密钥字符串的命名约定

    已经回答了传递数据的实际过程,但是大多数答案都使用硬编码字符串作为Intent中的键名 . 仅在您的应用中使用时,这通常很好 . 但是,documentation recommends使用 EXTRA_* 常量来标准化数据类型 .

    Example 1: Using Intent.EXTRA_ keys*

    第一项活动

    Intent intent = new Intent(getActivity(), SecondActivity.class);
    intent.putExtra(Intent.EXTRA_TEXT, "my text");
    startActivity(intent);
    

    第二项活动:

    Intent intent = getIntent();
    String myText = intent.getExtras().getString(Intent.EXTRA_TEXT);
    

    Example 2: Defining your own static final key

    如果其中一个 Intent.EXTRA_* 字符串不符合您的需求,您可以在第一个活动开始时定义自己的字符串 .

    static final String EXTRA_STUFF = "com.myPackageName.EXTRA_STUFF";
    

    如果您只在自己的应用程序中使用密钥,那么包括软件包名称只是一种约定 . 但是,如果要创建某种其他应用程序可以使用Intent调用的服务,则必须避免命名冲突 .

    第一项活动:

    Intent intent = new Intent(getActivity(), SecondActivity.class);
    intent.putExtra(EXTRA_STUFF, "my text");
    startActivity(intent);
    

    第二项活动:

    Intent intent = getIntent();
    String myText = intent.getExtras().getString(FirstActivity.EXTRA_STUFF);
    

    Example 3: Using a String resource key

    虽然文档中没有提到,this answer建议使用String资源来避免活动之间的依赖关系 .

    strings.xml中

    <string name="EXTRA_STUFF">com.myPackageName.MY_NAME</string>
    

    第一项活动

    Intent intent = new Intent(getActivity(), SecondActivity.class);
    intent.putExtra(getString(R.string.EXTRA_STUFF), "my text");
    startActivity(intent);
    

    第二项活动

    Intent intent = getIntent();
    String myText = intent.getExtras().getString(getString(R.string.EXTRA_STUFF));
    

相关问题