首页 > 解决方案 > 如何将数据从一个活动传递到下一个活动

问题描述

我目前正在开发一个 android 应用程序并使用 firebase 实时数据库。如何将用户数据从登录活动传递到主页活动的导航标题?

为了将用户数据传递给 Home Activity 的 Navigation 标头,我应该在 Login Activity 中添加什么?

用户无需输入用户名即可登录,但我希望从实时数据库中获取用户名并将其传递给导航标题。

登录.java

firebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {

            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                progressDialog.dismiss();
                if(task.isSuccessful()){
                    finish();
                startActivity(new Intent(getApplicationContext(),Home.class));

                }
                else
                {

                    Toast.makeText(LoginActivity.this,"Login failed. Kindly check your email and password.",Toast.LENGTH_SHORT);
                }
            }
        }

主页.java

View headerView = navigationView.getHeaderView(0);
    useremail = (TextView)headerView.findViewById(R.id.HVuseremail);
    useremail.setText(Common.currentUser.getName());
    username = (TextView)headerView.findViewById(R.id.HVusername);
    username.setText(Common.currentUser.getName()); 

我希望我的导航标题将在其上显示 useremail 和用户名。

标签: javafirebaseandroid-studiofirebase-realtime-databasepass-data

解决方案


如果您有少量数据(如姓名、电子邮件),那么您可以使用上面@Mushirih 建议的意图 putExtra 方法。

但是如果你有一堆数据集,你可以使用 Android Bundle Intent 将它传递给下一个活动,如下所示

登录活动类

        Bundle bundle = new Bundle();
        bundle.putString("Name",value);
        bundle.putInt("Phone",6752525);
        bundle.putBoolean("IsMale",false);
        //..................like so on ............
        Intent intent = new Intent(LoginActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

在 SecondActivity 类中,您可以像这样接收它:-

Bundle bundle = getIntent().getExtras();
 String showtext = bundle.getString("Name"); //this for string
 int phone = bundle.getInt("Phone"); // this is for phone
  //.....like for other data...............

推荐阅读