views:

38

answers:

1

I have stripped down 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!

+1  A: 

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;
}
Prashast
There is rarely a reason to call `getApplicationContext()`. Just use the `Activity` itself, since it is a `Context`.
CommonsWare
Thanks Prashast! It worked like a charm! Thanks for your quick response.
Andrew
CommonsWare, I'd like to follow up on your response. My question was what do I put where I have '???????' in the function call above. Using Prashast's suggestion I put "getApplicationContext()" as the argument and it works fine. However, if I were to use your seggestion of staying with 'Activity', what would I put as the argument in place of 'getApplicationContext()'?Thanks.
Andrew
From the question I don't know where this call is being made. If its from a broadcast receiver or from a service he would not have an activity object. It makes more sense to me to use the application context here instead of restricting yourself to an activity.
Prashast