Android 全局变量动态值

Android global variable dynamic value

大家好我想使用一个全局整数变量,我将根据用户正确或错误的选择在 7 种不同的活动中递增。问题是我每次在每个不同的 activity 中实现变量时,都不会保留该值。相反,我得到了变量的默认值。我想要的是,当我在下一个变量中再次使用它时,我对变量所做的每个增量都会被保存。任何帮助表示赞赏。 我尝试过但失败了:

public class MyApplication extends Application {

private int grade=0;

public int setGrade(int grade) {
    this.grade = grade;
}

public int getGrade() {
    return grade;
}

}

public class lessonOnePhoto extends Activity {

private int grade = ((MyApplication) this.getApplication()).getGrade();

if (rbtn[0].getText().toString().equals("Boy")) {
grade++;
}
else {
Toast.makeText(getApplicationContext(),"Wrong Choise",Toast.LENGHT_SHORT).show();
}
}

您递增的 grade 是本地的并且对您的 activity 是私有的。它也是一个原语,而不是一个对象,所以grade = .getGrade()会将局部变量设置为与全局值相同的值,它不是某种引用。

相反,做这样的事情:

MyApplication myApplication = ((MyApplication) this.getApplication());
myApplication.setGrade(myApplication.getGrade()++);

或者实现自增自减方法。

public class MyApplication extends Application {

private int grade=0;

public int setGrade(int grade) {
    this.grade = grade;
}

public int getGrade() {
    return grade;
}

public void incrementGrade() {
    grade++;
}

public void decrementGrade() {
    grade--;
}

您必须增加原始应用程序值..而不是副本以在活动之间维护变量

if (rbtn[0].getText().toString().equals("Boy")) {
grade++;
}

改为

if (rbtn[0].getText().toString().equals("Boy")) {
((MyApplication) this.getApplication()).setGrade(grade++)
}

您可以在应用程序 class 中添加一种方法来增加值

public class MyApplication extends Application {

private int grade=0;

public int incrementGrade() {
    this.grade = grade + 1;
}

public int setGrade(int grade) {
    this.grade = grade;
}

public int getGrade() {
    return grade;
}
}

并在需要时递增

MyApplication myApplication = ((MyApplication) this.getApplication());
myApplication.incrementGrade();

或 ================

使该成绩静态并通过以静态方式访问它来递增

 public static int grade = 0;

访问它就在这个

 MyApplication.grade ++;

您可以 get the result from the activities 在用户输入响应的位置并从管理所有响应的 MainActivity 处理它。

另一种避免在应用程序 class 中存储信息的方法是 Singleton with a Shared Instance that stores the global variables. However, the use of singletons is considered a bad practice in some cases.