2011-02-02 58 views
1

我的应用程序有多个以不同方式使用相同数据库的活动。定期地,数据从我的应用程序外部添加到数据库中。因此,我不是复制代码来检查每个活动中的数据库,而是试图创建一个可以从任何活动中使用的类来检查数据库中的新条目。我正在使用fileInputStream,并使用openFileInput方法打开一个文件,该文件包含一些用于确定新数据库条目是否对应用程序感兴趣的首选项。在每个活动中使用openFileInput方法都能按预期工作,但在我自己的类中使用它会导致错误,指出openFileInput()方法未定义。我已经导入了java.io.FileInputStream,但错误仍然存​​在。Android:我如何在自己的类中使用为活动定义的方法?

回答

3

openFileInput是Context的成员。你应该把你的活动传递给你的班级(作为一个上下文)并从那里调用它。

public class MyClass{ 
    protected Context mContext; 
    public MyClass(Context c) 
    { 
    mContext = c; 
    } 
    public void doSomething() 
    { 
    mContext.openFileInput(...) 
    } 
} 
+0

工程就像一个魅力!非常感谢。 – 2011-02-03 00:16:56

0

您可以使用继承:

public class ActivityWithDBManagementAbilities extends Activity{ 
    public YourAnswerType checkDB(YourParameterType parameter){ 
     //here the code that check the data base 
    } 
} 

那么你的活动从该类扩展(实际活动中使用未复制代码父亲方法)。例如:

public class MyActivity1 extends ActivityWithDBManagementAbilities{ 

    //inside some method. 
    YourAnswerType dbStatus = checkDB(yourParam); 

} 

我还没有测试它,但它应该工作。

相关问题