2012-02-24 60 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(); 

在非活动类使用这种

从另一活动类称为...

我希望你明白进程调用方法..

相关问题