-3

From my MainActivty I'm trying to call a method of non-activity class with the following line:

Context context;
context = getApplicationContext();
mClient.start(context);

In non activity-class:

 public void start(Context context) {

    final ProgressDialog startDialog;
    startDialog = new ProgressDialog(context);
    startDialog.setMessage("Loading...");
    startDialog.setCancelable(false);
    startDialog.show();

    mHandler.post(new Runnable () {
        @Override
        public void run() {

            Log.d(TAG,"Connecting to the server...");

            try {
                connect();
            } catch (Exception e) {

            }               

      startDialog.dismiss();

 }

The app crashes with the following message:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

Where's the mistake?

user12205
  • 2,684
  • 1
  • 20
  • 40
andreasperelli
  • 1,034
  • 2
  • 11
  • 40

3 Answers3

1

Pass context parameter in ProgressDialog,So Change

startDialog = new ProgressDialog(this);

to

startDialog = new ProgressDialog(context);

And in your mainActivity change

context = getApplicationContext();

to

context = MainActivty.this;
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
  • This seems to work. But I don't understand why context = getApplicationContext(); doesn't work. If I call it from MainActivity.this, it should save 'MainActivity.this' in context variable... – andreasperelli Oct 09 '14 at 10:18
  • 1
    @andreasperelli see this [When to call activity context OR application context?](http://stackoverflow.com/questions/7298731/when-to-call-activity-context-or-application-context) – Giru Bhai Oct 09 '14 at 10:19
1

try to change this in your non-activity class .start(....) method

  startDialog = new ProgressDialog(context);

instead of

  startDialog = new ProgressDialog(this);

also you need to change in your mainActivity

  context = getApplicationContext();

to

 context = MainActivity.this;;

You need to pass context to create Progress Dialog in non-activity class

M D
  • 47,665
  • 9
  • 93
  • 114
0
startDialog = new ProgressDialog(context);
Zied R.
  • 4,964
  • 2
  • 36
  • 67