Java solves the problem of No enclosing instance of type XXX is accessible, enclosinginstance
Sometimes we need to move some implementation classes of the Activity to java classes for implementation. For example, we need to write the following two classes:
In the LifeCircle class:
public class LifeCircle {public class Mybroadcast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {}}}
If you go to new like this in Activity:
public class Settings extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.test_layout);LifeCircle lifeCircle = new LifeCircle(this);Mybroadcast cast = new Mybroadcast();}}
The compiler reports an error:
- No enclosing instance of type LifeCircle is accessible. Must qualify the allocation with an enclosing instance of type LifeCircle (e.g. x.new A() where x is an instance of LifeCircle).
One solution is to define Mybroadcast as static class.
Let's make it like this:
package com.example.shoplistdownload;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;public class LifeCircle {Context mContext;private static LifeCircle sInstance;private Mybroadcast mBroadcast; private Settings mInstance;LifeCircle(Context context) {mContext = context;mInstance = (Settings)context;}public static LifeCircle getIntance(Context context) {if (sInstance == null) {sInstance = new LifeCircle(context);}return sInstance;}public class Mybroadcast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {}}public void registerBroadcaster() {mBroadcast = new Mybroadcast();IntentFilter filter = new IntentFilter();filter.addAction("com.example.action");mInstance.registerReceiver(mBroadcast, filter);}}
public class Settings extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.test_layout);LifeCircle lifeCircle = new LifeCircle(this);lifeCircle.registerBroadcaster();}}
No enclosing instance of type ChuangKou is accessible java Programming Problem
Change to static class MyMonitor implements ActionListener {
Or define MyMonitor outside ChuangKou.
The non-static nested class must be constructed in the non-static member of the coat class.
A problem in java, super: No enclosing instance of type
According to your code, is your class B an internal class of?
If it is an internal class, the statement is incorrect.