Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android How to read an asset from outside of main activity

Tags:

android

assets

I need to be able to be able to call readAsset from outside of the main activity of my application. I have heard people mention needing to pass the Context around, but the language has been very vague. Can someone describe the steps necessary to add the ability to call readAsset to an existing class that is not the main activity? Creating a public function in the main activity and having others call that will not work as the place I need to add readAsset to, is in a separate thread.

like image 564
corbin Avatar asked Nov 08 '10 17:11

corbin


2 Answers

public class NonActivity {
    public void doStuff(Context c) {
        //read from assets
        c.getAssets();
        //use assets however
    }
}

Not sure what you're asking, but perhaps something like this? Just add to the existing class, and use the context to retrieve the assets. In your activity call the method like this:

public class MyActivity extends Activity {
  public void OnCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    NonActivity n = new NonActivity();
    n.doStuff(this);
  }
}
like image 172
danh32 Avatar answered Sep 26 '22 19:09

danh32


To read assets, you need a Context, but you don't have to use an Activity as your Context; you can use the Application object instead.

Android Context without being in an activity? And other activity-less programming?

public class MyApplication extends Application {
    private static MyApplication instance;

    public MyApplication() {
        instance = this;
    }

    public static MyApplication getInstance() {
         return instance;
    }
}

You'll need to add the android:name attribute to the <application> element in AndroidManifest.xml first:

 <application android:name="com.example.MyApplication" ... />

Now you can call MyApplication.getInstance().getAssets() statically from anywhere.

Alternately, you could use Dagger dependency injection to inject an Application directly into your object. (Injecting the Application context is a bit tricky. See Dagger 2 injecting Android Context and this issue filed on the Danger github repo.)

like image 34
Dan Fabulich Avatar answered Sep 23 '22 19:09

Dan Fabulich