2012-02-24 59 views
0

我在我的項目中有兩個類。第一個是「公共類Schtimetable extends Activity」,其中有一個方法需要在Class中調用B:「公共類ClassMode」。該法是我該如何使用非活動類中的活動類的函數

public int calculateWeeks() { 
    SharedPreferences preferences = getSharedPreferences("currentWeek", 
      Context.MODE_PRIVATE); 
    int csweek = preferences.getInt("CSweek", 1); 
    int weekofyear = preferences.getInt("currentWeek", 0); 
    int now_weekofyear = Calendar.getInstance().get(Calendar.WEEK_OF_YEAR); 
    return (csweek + now_weekofyear - weekofyear);// return current week 
} 

我覺得我不能使用它,就像這樣:

Schtimetable s = new Schtimetable(); 
    int oddOReven = cursor.getInt(cursor.getColumnIndex("oddOReven")); 
    cursor.close(); 
    if ((s.calculateWeeks() % 2 == oddOReven) || (oddOReven == 2)) { 
     Log.i(TAG, "has Class is true"); 
     return true; 
    } else { 
     Log.i(TAG, "has Class is false"); 
     return false; 
    } 
在所有

,我想有該方法calculateweeks數據()返回,我怎麼能得到它。 謝謝!

回答

3

不要從活動中調用方法。活動是爲了開始,而不是像普通的舊Java對象那樣實例化。將方法放在其他地方(在其他一些輔助類中),並讓它作爲參數使用Context(這樣您就可以獲得SharedPreferences)。然後,在任何活動中,您都可以調用該方法。另外,你應該可以使該方法是靜態的。

+0

但我不能使方法靜態,因爲getSharedPreferences不是一個靜態方法。 – IdroidCheung 2012-02-24 04:14:37

0

使用這樣

YourActivtyClass activityclassobject = new YourActivtyClass(); 

activityclassobject.activityclassmethod(); 

在非活動類使用這種

從另一活動類稱爲...

我希望你明白進程調用方法..

相關問題