在android中获取上下文和活动对象null

时间:2014-03-09 07:47:32

标签: android android-activity android-context android-toast

我正在尝试从不是活动的单独类中提供消息。为此,我知道我需要活动的背景。但我不知道为什么我在该类中获得空上下文

这是我的致敬消息的课程

public class Notifier {

public Notifier(){

}

public Notifier(Context ctx, MainActivity activity){
Log.d("Constructor call", "dd");
context = ctx;
activity = activity;
}

public void toast(String message){  
messageData = message;
Log.d("Notifier Data", messageData);

while(context == null || activity == null){
    Log.d("Context", "issue");
    try{
    Thread.sleep(1000);
    } catch(InterruptedException exception){
    exception.printStackTrace();
    }
}
activity.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(context, "messageData", Toast.LENGTH_SHORT).show();
    }
    }); 
}

Context context;
String messageData;
esActivity activity;

}

以下是我对MainActivity的onCreate的调用

     Notifier nt = new Notifier(getApplicationContext, MainActivity.this);

1 个答案:

答案 0 :(得分:0)

我猜activity为空。检查你的构造函数:

public Notifier(Context ctx, MainActivity activity){
Log.d("Constructor call", "dd");
context = ctx;
activity = activity;
}

作业activity = activity;无效。你想要的是

this.activity = activity;