开发者

How to retrieve a context from a non-activity class?

开发者 https://www.devze.com 2023-03-23 21:28 出处:网络
I have found one answer that appears to say I should create a separate class and make a static MyApplication object and make a get method. Then any class can call MyApplication.get() to retrieve the c

I have found one answer that appears to say I should create a separate class and make a static MyApplication object and make a get method. Then any class can call MyApplication.get() to retrieve the context.

Is there any other cleaner way? This is my situation:

I have a class A and a class B. Class A contains an obje开发者_JAVA百科ct from class B (let's call the object b). In class A I call, "b.play()". However, I get a null pointer exception because class B needs to pass a context to the MediaPlayer.create() method.

Until now I threw together a hack and from class A I called.... "b.play(this)" and simply passed the context to B. However that is pretty ugly and looks like a bad use of OOP.

Any thoughts?


This problem seem to arise a lot in Android development. One solution to obtaining a reference to a specific Context is subclassing the Application and grab a reference to the Context which you want.

public class MyApplication extends Application { 

private Context context;

@Override
public onCreate() {
  super.onCreate();
  this.context = getApplicationContext() // Grab the Context you want.
}

public static Context getApplicationContext() { return this.context; }
}

This solution however requires that you specify the name of your subclass in your manifest.

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

You can then use this anywhere in your application like this in non-activity classes.

MyApplication.getContext();  // Do something with the context! :)


If class B requires a Context to operate, then I don't see any problem having class A provide that to it (through a parameter on the play method, a parameter in a constructor, etc).

I don't think you are doing any poor OOP by providing class B the dependencies that it needs to do it's job.


Passing this around is a viable way of doing things, especially if this is the activity that creates the object in need of a Context. Sometimes, I'll put the Context into the constructor (like public MyObject(Context context){this.context = context;}), so that you don't need to send it every time. However, if your object is shared across multiple Activities, you should probably update the context it is looking at with the new Activity, though I haven't tested what happens if you use the old activity.


I've answered also here.

You can do that using ContextWrapper, as described here.

For example:

public class MyContextWrapper extends ContextWrapper {

    public MyContextWrapper(Context base) {
      super(base);
   }

   public void someMethod() {
      // MediaPlayer.create(this, ...)
   }

}
0

精彩评论

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