问题
this is the class i am using
public class ContactsXmpp extends SherlockFragmentActivity {
private static Context ctx;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_xmpp_sip);
ctx = this;
}
i am getting error when i call asynctask from this method. this is the error
No enclosing instance of type ContactsXmpp is accessible. Must qualify the allocation with an enclosing instance of type ContactsXmpp (e.g. x.new A() where x is an instance of ContactsXmpp).
private static void alert( String str, final String name ) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctx);
alertDialogBuilder.setMessage(str + ": " + name);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Subscription(name);
new ColorsXMPP_AfterLogin().execute(); ///** error getting here..
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
unSubscribe(name);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
Asynctask here
public class ColorsXMPP_AfterLogin extends AsyncTask<AfterLogging, Void, Void> {
private ProgressDialog _dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.e(TAG, " GmailXMPP_AfterLogin onPreExecute" );
}
@Override
protected void onPostExecute(Void feed) {
//ProgressBar_hide();
_dialog.dismiss();
Log.e(TAG, " GmailXMPP_AfterLogin onPostExecute" );
}
@Override
protected Void doInBackground(AfterLogging... arg0) {
Log.e(TAG, " GmailXMPP_AfterLogin doInBackground" );
return null;
}
}
回答1:
You can't instantiate the ColorsXMPP_AfterLogin
class in the static
method of alert
(I'm assuming that both are in the ContactsXmpp
activity). The problem is that ColorsXMPP_AfterLogin
is declared as being an inner class and inner classes need an instance of the enclosing class to be created(they require this connection). In the static alert
method you don't have this instance so the compiler throws that error. You have several options to solve the problem, the one I would recommend is to either make ColorsXMPP_AfterLogin
as a nested class in ContactsXmpp
(declared like public static class ColorsXMPP_AfterLogin...
) or completely move it in its own java file(if you need a connection to the Activity
's Context
simply pass a reference to that ctx
in the AsyncTask
's constructor).
You could also use the ctx
variable to create the instance of ColorsXMPP_AfterLogin
like:
ctx.new ColorsXMPP_AfterLogin();
来源:https://stackoverflow.com/questions/14107999/no-enclosing-instance-of-type-contactsxmpp-is-accessible