2011-05-24 66 views
1

我试图将上下文从一个类传递到另一个类。传递上下文时出错

调用类:

mForgotPatternButton.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      new ListOfAccounts(v.getContext()); 
     } 
    }); 

称为类:

public ListOfAccounts(Context context) { 
    super(context); 
    mAccounts = new ArrayList<String>(); 
     AlertDialog.Builder builder = new AlertDialog.Builder(context); 
     builder.setTitle("Select the account");      
     ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),R.layout.list_all_accounts, mAccounts); 
     AccountManager.get(context).addOnAccountsUpdatedListener(ListOfAccounts.this, null, true);    
     builder.setAdapter(adapter, new DialogInterface.OnClickListener(){ 
      public void onClick(DialogInterface dialogInterface, int item) { 
        mCallback.forgotPattern(true); 
        return; 
       } 
     }); 
     builder.create().show();    
    } 

不是传递 “v.getContext()” 中,我甚至试图让 “的getContext()”。但是在所有情况下,我会得到以下例外

05-24 16:11:27.087: ERROR/AndroidRuntime(4429): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application 

请为此提供解决方案。

在这方面的任何帮助将不胜感激。

最好的问候, 罗尼

+1

可能重复的[Android:ProgressDialog.show()崩溃与getApplicationContext](http://stackoverflow.com/questions/1561803/android-progressdialog-show-crashes-with-getapplicationcontext) – 2011-05-25 11:02:14

回答

1

尝试通过YourActivityName.this而不是getContext()。希望这可以帮助。

2

有时getContext()或者甚至getApplicationContext()会导致此异常。尝试通过

this 

YourActivity.this 

活动从上下文继承所以它的工作原理,但我真的不知道为什么得到上下文它应该做它不会工作,给予该怪异例外。

+0

嗨费德里科和叶戈尔,谢谢为你的答复..但调用类的语法不允许我通过'this'或'YourActivity.this',因为它不扩展活动。这里是我的调用类定义 - 类'PatternUnlockScreen extends LinearLayoutWithDefaultTouchRecepient implements Implement KeyguardScreen,KeyguardUpdateMonitor.InfoCallback, KeyguardUpdateMonitor.SimStateCallback'请原谅我不正确的格式。 – user264953 2011-05-24 17:54:23

+0

然后你有一个问题!不,实际上,这看起来像是一个错误。它发生在我身上,通过做一个getContext并通过传递一个对Activity的引用来解决这个异常。而且没有其他方法来检索上下文或当前正在运行的活动的上下文。我所能想到的就是让你将Activity引用传递给你的类的构造函数或类似的东西,以确保你通过你所有的方法获得了正确的上下文。 – ferostar 2011-05-24 18:01:14

+0

当我尝试使用我告诉的不同方法获取上下文时,我始终获得相同的值。即使我通过三种不同的方法记录了上下文对象的输出,并且三个上下文对象也是相同的(并且不是空的)。我对这个问题感到困惑,至于导致这个错误的原因是什么。 – user264953 2011-05-24 18:16:09