Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use this way to pass context to non-context classes

I have read several articles about passing context to adapter or something else and i made some kind of contextholder for getting application context:

import android.content.Context;

public class ContextHolder {
    private static ContextHolder ourInstance = new ContextHolder();
    private Context context;

    public static ContextHolder getInstance() {
        return ourInstance;
    }

    private ContextHolder() {
        context = null;
    }

    public void setContext(Context context){
        this.context = context;
    }

    public Context getApplicationContext(){
        return context;
    }
}

then in MainActivity i`m creating ContextHolder object and setting context like this:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ContextHolder contextHolder = ContextHolder.getInstance();
        contextHolder.setContext(this.getApplicationContext());
    }

in some other class, where i need to use contex:

ContextHolder contextHolder = ContextHolder.getInstance();
Resources resources = contextHolder.getApplicationContext().getResources();

The question is, am i doing right thing? Can it cause memory leaks or other nasty stuff?

like image 374
Ontoshgo Avatar asked Jan 07 '23 19:01

Ontoshgo


1 Answers

in MainActivity i`m creating ContextHolder

But what for? Activity is subclass of Context already:

java.lang.Object
  ↳ android.content.Context
    ↳ android.content.ContextWrapper
      ↳ android.view.ContextThemeWrapper
        ↳ android.app.Activity

so you could just use this (or MainActivity.this). Not to mention contextHolder variable you put your holder object in shown code is of local scope and visible in onCreate() only.

Can it cause memory leaks or other nasty stuff?

I recommend using LeakCanary to catch catch all the memory leaks in your code. See: https://github.com/square/leakcanary

In some other class, where i need to use contex:

ContextHolder contextHolder = ContextHolder.getInstance();
Resources resources = contextHolder.getApplicationContext().getResources();

This is all unnecessary and over-engineered. If all you need to get the application context, subclass Application class:

class MyApplication extends Application {
    protected static Context mContext;

    @Override
    public void onCreate() {
       super.onCreate();

       mContext = this;
    }

    public static Context getAppContext() {
       return mContext;
    }
}

set it as your app application class in Manifest:

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

and then whenever you need the context you can't get other way, can just call:

MyApplication.getAppContext();
like image 173
Marcin Orlowski Avatar answered Jan 10 '23 10:01

Marcin Orlowski