“警告:不要将Android上下文类放在静态字段中;这是一个内存泄漏(也会破坏即时运行)”
这里,这里和这里都问过类似的问题,但上下文与此完全不同,而且从此错误中给出的代码是由Android和Android Studio的制造商编写的。
这是代码:
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
发出警告的行是:
private static MySingleton mInstance;
private static Context mCtx;
现在,如果我删除关键字,请更改为错误消除器,但会出现另一个问题。static
public static synchronized MySingleton getInstance(Context...
public synchronized MySingleton getInstance(Context...
我在 RecyclerView 中使用。所以这条线MySingleton
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
ImageLoader imageLoader = MySingleton.getInstance(mContext).getImageLoader();
告诉我
非静态方法'getInstance(android.content.Context)'不能从静态上下文中折射。
请有人知道如何解决这个问题?