开发者

Calling a function that has 'Activity' as an argument

开发者 https://www.devze.com 2022-12-26 02:45 出处:网络
I have stripped dow开发者_StackOverflown my functions for simplicity: public static int countLines(String fileName, Activity activity) throws IOException {

I have stripped dow开发者_StackOverflown my functions for simplicity:

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

I am calling it from here:

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

In the call to countLines("data.txt", ??????), what do I put as the argument for the Activity? I've Googled all night and I can find no examples of an actual call to a function where Activity is an argument. (Lots of examples actually using 'activity', but no calls to the example functions).

Thanks!


getAssets() is a function from the class Context. The reason you could be using Activity there is because Activity is an indirect subclass of Context.

Depending on where you are calling countLines from you should be able to pass the context of the application instead of the activity object. In most cases you can get your application's context by calling getApplicationContext(). Just change your function to:

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

return 3;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消