Skip to content Skip to sidebar Skip to footer

How Do I Share Variables Between Classes?

Say I am making something like a quiz, and I have a counter to show the number of questions that have been answered correctly. When one question is correctly answered, and a new s

Solution 1:

When you say screens do you mean Activities? Then you probably want to pass them via extras in your intents.

Activity 1:

    int score;

    ...
    Intent Intent = new Intent(...);
    intent.putExtra("score_key", score);
    startActivity(intent);

Activity 2's onCreate():

    int score;
    ...

    Bundle extras = getIntent().getExtras();

    // Read the extras data if it's available.
    if (extras != null)
    {
        score = extras.getInt("score_key");
    }

Solution 2:

You can send numbers, strings, etc in a bundle with your intent.

Bundle b = new Bundle();
b.putInt("testScore", numCorrect);
Intent i = new Intent(this, MyClass.class);
i.putExtras(b);
startActivity(intent)

you can also put StringArrays and a few other simple vars


Solution 3:

One of this way you can share your data among whole project,

public class mainClass 
{
    private static int sharedVariable = 0;


    public static int getSharedVariable()
    {
          return sharedVariable;
    }
}

From the other class/activity , you can access it directly using classname and . (dot) operator. e.g. mainClass.getSharedVariable();


Solution 4:

A good practice for storing variables across Activitiys is using a own implementation of the Application Class.

public class MyApp extends android.app.Application {

private String myVariable;

public String getMyVariable() {
    return myVariable;
}

public void setMyVariable(String var) {
    this.myVariable = var;
}

Add the new Class in the Manifest.xml inside the application tag:

<application android:name="MyApp" android:icon="@drawable/icon" android:label="@string/app_name">

Now you can manipulate the variable in every Activity as follows:

MyApp ctx = (MyApp)getApplicationContext();
String var = ctx.getMyVariable();

Post a Comment for "How Do I Share Variables Between Classes?"