2015-04-28 56 views
-2

大家好,我想利用一個全局整型變量,根據用戶對錯選擇,我將在7個不同的活動中增加。問題是我每次在每個不同的活動中實現變量時,都不保留該值。相反,我得到的變量的默認值。我想要的是,我對變量所做的每個增量都保存下來,當我在下一個變量中再次使用它時。任何幫助讚賞。 我曾嘗試和失敗:Android全局變量動態值

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(); 
} 
} 

回答

2

grade你遞增是局部的,專用於您的活動。這也是一個原始的,而不是一個對象,所以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--; 
} 
0

,你必須增加原有的應用價值..不是複製來維持變量之間的活動

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

變化

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

這不起作用。如果分數在其他地方更改,則該活動將不具有當前值。 – Simon

0

您可以添加一個方法應用程序類增加值

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

OR ================當

和增量

作出這樣的等級由靜態的方式訪問它的靜態和增量

public static int grade = 0; 

訪問它躺在這個

MyApplication.grade ++; 
+0

公開變量是一種不好的做法。相反,使用getter和setter,以便將來如果應用程序中的等級實現發生更改(例如,共享首選項或數據庫),則其餘代碼不需要更改。 – Simon

0

可以get the result from the activities用戶在其中輸入的資源通過管理所有響應的MainActivity進行處理和處理。

避免將信息存儲在應用程序類中的另一種方法是使Singleton具有存儲全局變量的共享實例。但是,在some cases中使用單例被認爲是不好的做法。