簡體   English   中英

如何將數據從一個活動傳遞到下一個活動

[英]How to pass the data from one Activity to the next activity

我目前正在開發一個android應用,並使用firebase實時數據庫。 如何將用戶數據從登錄活動傳遞到家庭活動的導航標題?

為了將用戶數據傳遞到Home Activity的Navigation標頭中,我應該在Login Activity中添加什么?

用戶無需輸入用戶名即可登錄,但我希望從實時數據庫中獲取用戶名,並將其也傳遞給導航標題。

Login.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);
                }
            }
        }

Home.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和用戶名。

如果您的數據集很少(如名稱,電子郵件),則可以使用上述@ Mushirih建議的intent putExtra方法。

但是,如果您設置了一堆數據,則可以使用Android Bundle Intent在下一個Activity中傳遞它,如下所示

LoginActivity類

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

您可以使用putExtra方法跨Intent傳遞數據。

Intent intent = new Intent(getBaseContext(), Home.class);
intent.putExtra(<your data unique id in quotes>, <your data e.g username>);
startActivity(intent);

在您的Home.class中,您可以按以下方式檢索數據

String username = getIntent().getStringExtra(<your data unique id in quotes>,<default value incase the value is not correctly passed e.g null>);

希望這能回答您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM