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;

    ...
    IntentIntent=newIntent(...);
    intent.putExtra("score_key", score);
    startActivity(intent);

Activity 2's onCreate():

int score;
    ...

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

Bundleb=newBundle();
b.putInt("testScore", numCorrect);
Intenti=newIntent(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,

publicclassmainClass 
{
    privatestaticint sharedVariable = 0;


    publicstaticintgetSharedVariable()
    {
          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.

publicclassMyAppextendsandroid.app.Application {

privateString myVariable;

publicStringgetMyVariable() {
    return myVariable;
}

publicvoidsetMyVariable(Stringvar) {
    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:

MyAppctx= (MyApp)getApplicationContext();
Stringvar= ctx.getMyVariable();

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