Pregunta

Iam trying to create an application that have

  1. MainActivity
    it is a login page , it contain 4 variable, when i click the login button, it goes to another activity HomeTab using an intent
    Intent i = new Intent(FirstMain.this,Home_tab.class);
    startActivity(i);

  2. HomeTab - it has three Tab views.
    a. Profile
    b. Account
    c. Settings

My problem is how to pass that 4 variables from the MainActivity to the 3 activities in the Tab

¿Fue útil?

Solución 6

you have two options.

  1. you can use intent.
  2. you can use sharedpreferences.

Otros consejos

You can add a Bundle as extra parameter in an intent

Bundle bundle = new Bundle();
bundle.putString("key", "peanuts");
bundle.putInteger("key2", 100);
i.putExtras(bundle);

Then to retrieve it

final Bundle parameters = this.getIntent().getExtras();
String food = parameters.getString("key");

In Class 1:

i.putExtras("Variable1", "Value1");
i.putExtras("Variable2", 2);
i.putExtras("Variable3", true);
startActivity(i);

In Class 2:

String Var1 = this.getIntent().getExtras().getString("Variable1");
int Var2 = this.getIntent().getExtras().getInt("Variable2");
boolean Var3 = this.getIntent().getExtras().getBool("Variable3");

You can pass them in the Intent you use to launch the HomeTab activity (see Intent).

use intent.putExtra to pass values you want

Intent i=new Intent(FirstMain.this,Home_tab.class);
i.putExtra("Profile", "profiledata");
i.putExtra("Account", "Account data");
startActivity(i)

and get those passing values in next activity

Intent intent = getIntent();
String id = intent.getStringExtra("Profile");
String name = intent.getStringExtra("Account");

Check How do I get extra data from intent on Android?

In Login Activity send the variable via Intent

Intent i = new Intent(FirstMain.this,Home_tab.class);
i.putExtra("var1", "username");
i.putExtra("var2", "activity";
startActivity(i);

In the Home_Tab get the Intent

Intent intent = getIntent();
String id = intent.getStringExtra("var1");
String name = intent.getStringExtra("var2");

For info on shared preferences see here

If you have a number of "global" variables, you can setup a "BaseActivity" that inherits from Activity does not have a cooresponding view, and then have all your other Activities inherit from BaseActivity rather than directly from Activity.

That allows you to have public shared variables on BaseActivity that all your other activities that inherit from that can access.

Obviously be careful with this technique, it could easily be really messy and lead to globals that shouldn't be global, etc. But it is handy for cleaning up code that is duplicated across views (shared methods on BaseActivity) or passing information between views, like a loggedIn state.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top