3

I am new to android. I am trying to build a simple android application: User clicks the button and a progress dialog appears for 5 seconds. I used ProgressDialog.show() and got a problem with the context parameter. Here is my xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/btnDialog2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btnDialog2" />
</LinearLayout>

And here is my code:

public class Dialog22Activity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btnDialog2 = (Button)findViewById(R.id.btnDialog2);
        btnDialog2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                final ProgressDialog dialog = ProgressDialog.show(getBaseContext(), 
                        "Progress dialog", "Loading...", true);
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                            dialog.dismiss();
                        } catch (InterruptedException e) {

                        }

                    }
                }).start();
            }           
        });
    }
}

If i change the context parameter of ProgressDialog.show() from getBaseContext() to v.getContext() my program run normally. So I wanna ask what is the meanning of context parameter here? Thanks for your helps.

user1756202
  • 63
  • 1
  • 6

7 Answers7

2

Just use Dialog22Activity.this instead of getContext() or WhatEverContextFunction() you want, when ever you are within this class and you'll be cool :)

Cehm
  • 1,502
  • 1
  • 12
  • 14
0

You can refer the android docs for these explanations please see this

http://developer.android.com/reference/android/content/Context.html

Juned
  • 6,290
  • 7
  • 45
  • 93
0

getContext() is not defined in an Activity. It's used in a View (or View subclass) to get a reference to the enclosing context (an Activity).

Amit Hooda
  • 2,133
  • 3
  • 23
  • 37
0

If you are showing the progress dialog on current Activity, use classname.class or 'this' keyword for context.

TraceIt
  • 71
  • 2
  • 11
0

The context in ProgressDialog.show(context) refers to the parent context of this ProgressDialog.

BaseContext effectively returns which ever context is being wrapped by ContextWrapper. By looking at the code, I can say that this is likely an Activity or Application however ContextWrapper has over 40 known direct and indirect children.

The problem is that this means that what the method returns may be ambiguous and I would rather use getContext() or the Activity, FragmentActivity, ActionBarActivity etc. directly, so that I know what I’m holding on to and that I’m holding a reference to something that can cause a memory leak. Also, I have the additional benefit of being able to take advantage of methods that are provided by these classes.

In case you want to use a ProgressDialog in an external class to an activity, you would create an instance of a Context inside this class and ProgressDialog would use its context:

public class DownloadTask extends AsyncTask<URL, Integer, Void>{

ProgressDialog progressDialog;
private Context context;

@Override
protected void onPreExecute() {
    super.onPreExecute();

    progressDialog = new ProgressDialog(context);


}
Ko Ga
  • 856
  • 15
  • 25
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Isma Nov 23 '17 at 21:14
  • Context will be null if there is not a constructor with the Activity valid context as parameter. – Pelanes Nov 23 '17 at 21:23
0
        import androidx.appcompat.app.AppCompatActivity;
        import android.app.ProgressDialog;
        import android.os.Bundle;
        import android.webkit.WebView;
        import android.view.View;
        import android.webkit.WebViewClient;
        import android.webkit.WebChromeClient;
        import android.webkit.WebSettings;
        import android.webkit.JsResult;
        import android.widget.Toast;


        public class MainActivity extends AppCompatActivity {


        private WebView webView;
        private ProgressDialog progressDialog;

        startWebView("http://.../mobile/");

        }

        private void startWebView(String url) {

        WebSettings settings = webView.getSettings();

        settings.setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);

        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);

        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Loading...");
        progressDialog.setMessage("Wait while loading...");
        progressDialog.setCancelable(false); // disable dismiss by tapping outside of the dialog
        progressDialog.show();

        webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
        if (progressDialog.isShowing()) {
        progressDialog.dismiss();
        }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        Toast.makeText(getApplicationContext(), "Error:" + description, Toast.LENGTH_SHORT).show();

        }
        });

        webView.loadUrl(url);
        }
        }
Zahoor
  • 1
  • 3
-1

its the activity context. use:

public class Dialog22Activity extends Activity {
    private Activity activity;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        activity = this;

        Button btnDialog2 = (Button)findViewById(R.id.btnDialog2);
        btnDialog2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                final ProgressDialog dialog = ProgressDialog.show(activity, 
                        "Progress dialog", "Loading...", true);
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                            dialog.dismiss();
                        } catch (InterruptedException e) {

                        }

                    }
                }).start();
            }           
        });
    }
}

information about context: What is 'Context' on Android?

Community
  • 1
  • 1
noxius
  • 144
  • 10