【问题标题】:Calling a function that has 'Activity' as an argument调用以“活动”为参数的函数
【发布时间】:2010-04-07 03:58:14
【问题描述】:

为了简单起见,我已经剥离了我的功能:

public static int countLines(String fileName, Activity activity) throws IOException {  
   BufferedReader in = new BufferedReader(new InputStreamReader(activity.getAssets().open(fileName))); 
   return 3;
}

我从这里调用它:

private CharSequence RandomRead() throws IOException {
    int numberLines = countLines("data.txt", ??????);           
    return "Success"
}

在调用 countLines("data.txt", ??????) 时,我将什么作为 Activity 的参数?我整夜都在谷歌上搜索,但找不到实际调用以 Activity 为参数的函数的示例。 (很多示例实际上使用了“活动”,但没有调用示例函数)。

谢谢!

【问题讨论】:

    标签: android android-activity


    【解决方案1】:

    getAssets() 是 Context 类中的一个函数。您可以在那里使用 Activity 的原因是因为 Activity 是 Context 的间接子类。

    根据您从哪里调用 countLines,您应该能够传递应用程序的上下文而不是活动对象。在大多数情况下,您可以通过调用 getApplicationContext() 来获取应用程序的上下文。只需将您的功能更改为:

    public static int countLines(String fileName, Context context) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(context.getAssets().open(fileName))); 
    
    return 3;
    }
    

    【讨论】:

    • 很少有理由打电话给getApplicationContext()。只需使用Activity 本身,因为它是Context
    • 谢谢普拉哈斯特!它就像一个魅力!感谢您的快速回复。
    • CommonsWare,我想跟进您的回复。我的问题是我应该把什么放在我有 '???????' 的地方在上面的函数调用中。使用 Prashast 的建议,我将“getApplicationContext()”作为参数,它工作正常。但是,如果我要使用您对“活动”的保留,我会用什么作为参数来代替“getApplicationContext()”?谢谢。
    • 从这个问题我不知道这个电话是在哪里打的。如果它来自广播接收器或服务,他将没有活动对象。对我来说,在这里使用应用程序上下文而不是将自己限制在一个活动中更有意义。
    猜你喜欢
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多