无法获取在Android中扩展Application的类中的上下文

时间:2014-05-31 10:00:41

标签: android

亲爱的朋友们,               我目前正在开发一个Android应用程序,我需要显示进度对话框。我需要有一个上下文对象。 这个任务我在扩展应用程序的类中实现。但每次当我尝试访问上下文对象时,它都会向我显示此行的WindowManager.BadTokenException

Dialog dialog=ProgressDialog.show(getApplicationContext(), "Status", "Downloading The master");

请帮助我在哪里做错了

编辑:  以下是我的代码!

public class FlightStatus extends Application {
    private Context context;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();



        SharedPreferences preference=getSharedPreferences("FlightStatus", 1);
        if(preference.getBoolean("firstLaunch", true))
            {

                try {
                    Dialog dialog=ProgressDialog.show(getApplicationContext(), "Status!", "Downloading The master!!");
                    XLSReadHelper excelReader=new XLSReadHelper(getApplicationContext());
                    //excelReader.readExcelFile(Environment.getExternalStorageDirectory()+"/UHCPAudit/cases.xls");  
                    excelReader.readExcelFile();
                    Log.d("Excel Operation ", "records read!!");
                    preference.edit().putBoolean("firstLaunch", false).commit();
                    dialog.dismiss();
                } catch (Exception e) {
                    // TODO: handle exception
                    Log.d("Excel Operation ", e.getMessage());
                }

            }
    }    
}

2 个答案:

答案 0 :(得分:1)

如果您要显示Activity的进度对话框,请使用:

Dialog dialog=ProgressDialog. show( MyActivity.this, "Status", "Downloading The master");

如果您是从Fragment展示,请先将此成员添加到Fragment班级:

private Activity activity;

然后在onCreateView()方法中调用此方法:

activity = getActivity();

最后

Dialog dialog=ProgressDialog. show( activity, "Status", "Downloading The master");

答案 1 :(得分:0)

您可以使用将Activity作为上下文

的构造函数
public class YourClass extends Application{
    private Activity context;

    public YourClass(Activity context){
       this.context = context;
    }
}

然后从您的来电Activity

YourClass yourClass = new YourClass(this);

您还可以尝试使用ProgressDialog本身的Activity,使用可以从自定义类调用的方法:

public void showProgress(){
  //Your progress code
}

在你的自定义课程中:

context.showProgress();