Reading text from resources in non-activity class in Android

I want to read some text from one of the raw text files in Android application and display a line from this text file in the app. widget.

For the MainActivity, I have written a method which get an InputStream using the following code:

getBaseContext().getResources().openRawResource(R.raw.tips);

My question is how to get reference to Context in the AppwidgetProvider because the MainActivity's onCreate method won't be invoked when user is using the widget and not the app. itself. The above code results in compiler error in the widgetprovider class.

Upvotes: 2

Views: 1053

Answers (3)

SREEJITH
SREEJITH

Reputation: 814

You can get it from onUpdate. pls check the code

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    // TODO Auto-generated method stub
    super.onUpdate(context, appWidgetManager, appWidgetIds);
    context.getResources().openRawResource(id);
}

Upvotes: 2

David Manpearl
David Manpearl

Reputation: 12656

The best way to do this is to pass a Context into all of your classes and functions that require to access the application's resources.

The second best way to do this is to store a static Context in your Application class. Here is an example that describes exactly how to do it: Static way to get 'Context' on Android?

Upvotes: 1

Pankaj Kumar
Pankaj Kumar

Reputation: 82938

If you have problem with Context only

public void onUpdate(Context context, AppWidgetManager appWidgetManager,
      int[] appWidgetIds) {..}

of AppWidgetProvider gets the context object into params..

Can u share your implementation?

Upvotes: 1

Related Questions