How do I share variables between classes?

≯℡__Kan透↙ 提交于 2020-01-05 07:53:05

问题


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 screen(Activity) is shown, how do I carry over the number to the next screen?


回答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");
    }



回答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




回答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();




回答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();


来源:https://stackoverflow.com/questions/9440672/how-do-i-share-variables-between-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!