質問

As I'm really annoyed of passing the Context for most of the operations in Android (Database, Toast, Preferences). I was wondering if it's a good way of programming to initialize these elements once (e.g. in Application-Class).

It works quite good, I don't have to pass the element from Class to class and I can't see any disadvantages. Thats the reason why I wanted to ask you guys. Why shouldn't I use this?

For the people who don't know what I mean:

MainApplication:

public class MainApplication extends Application {

  @Override
  public void onCreate() {
    super.onCreate();
    VolleySingleton.init(this);
    Toaster.init(this);
    PrefUtilities.init(this);
  }
}

Toaster:

public class Toaster {
   private static Toaster mInstance = null;
   private Context context;
   private Toast currentToast;

   private Toaster(Context context) {
      this.context = context;
   }

   public static void init(Context context) {
      mInstance = new Toaster(context);
   }

   public static void toast(String message){
      if (mInstance.currentToast != null){
          mInstance.currentToast.cancel();
      }
      mInstance.currentToast = Toast.makeText(mInstance.context, message, Toast.LENGTH_SHORT);
      mInstance.currentToast.show();
   }
}

I'm also interested in the question, why the context for Toast or other stuff is needed? I can use the application context for the Toast and have access in every single Activity / Fragment. Why has the Android-Team implemented it this way?

So basically two questions:

1. Do I have any disadvantages with my implementation (memory, time) ?

2. Why do classes like Toast require a context at all?

役に立ちましたか?

解決

1. Do I have any disadvantages with my implementation (memory, time) ?

Well, you are always initiating your db, even if you dont use it at all during that session, same goes for the other classes. Couldnt think of anything else, since you would use application context anyways, at least for database.

2. Why do classes like Toast require a context at all?

Toast requires a context since it touches the UiThread, so it needs a reference to access the thread.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top