2016-02-11 62 views
0

如何創建ProgressDialog而不顯示它?當WebView開始嘗試打開頁面時,如果頁面在兩秒後未加載(如果它在30秒後仍未加載,則消失),我想要顯示一個進度對話框。以下代碼失敗,因爲ProgressDialog progress = new ProgressDialog(MainActivity.this);,儘管我在各種SO答案中看到了,但會引發NullPointerException錯誤。Android - 創建ProgressDialog而不顯示它

public class MainActivity extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener { 

    // ProgressDialog progress = new ProgressDialog(MainActivity.this); // gives NullPointerException 
    ProgressDialog progress; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     WebView webView = (WebView) findViewById(R.id.webView); 
     webView.getSettings().setJavaScriptEnabled(true); 
     webView.loadUrl("http://www.google.com"); 

     webView.setWebViewClient(new WebViewClient() { 
      DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
      @Override 
      public boolean shouldOverrideUrlLoading(WebView view, String url) { 
       view.loadUrl(url); 
       return false; 
      } 
      @Override 
      public void onPageStarted(WebView view, String url, Bitmap facIcon) { 
       timerBeginDialog(2000, progress); 
       progress.setCancelable(true); 
       timerRemoveDialog(30000, progress); 
      } 
      @Override 
      public void onPageFinished(WebView view, String url) { 
       drawer.closeDrawer(GravityCompat.START); 
       progress.dismiss(); 
      } 
      public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 
       view.loadUrl("file:///android_asset/www/error.html"); 
       drawer.openDrawer(GravityCompat.START); 
       progress.dismiss(); 
      } 
     }); 
     . 
     . 
    } 

    public void timerBeginDialog(long time, final ProgressDialog pd){ 
     new Handler().postDelayed(new Runnable() { 
      public void run() { 
       pd = ProgressDialog.show(MainActivity.this, "", "Loading...", true); // gives error "Cannot assign a value to final variable pd" 
      } 
     }, time); 
    } 

    public void timerRemoveDialog(long time, final ProgressDialog pd){ 
     new Handler().postDelayed(new Runnable() { 
      public void run() { 
       pd.dismiss(); 
      } 
     }, time); 
    } 

回答

4

這是因爲在初始化器運行時尚未創建上下文。 只需將onCreate方法中的初始化。

+0

我把它裏面'onCreate',也有聲明它爲final:'最終ProgressDialog progress = new ProgressDialog(MainActivity.this);',並且還更改不必要的第二個聲明'pd = ProgressDialog.show(MainActivity.this,「」,「Loading ...」,true) ;'timerBeginDialog'內部到'pd.show();'。 – Bazley

1

移動

ProgressDialog progress = new ProgressDialog(MainActivity.this); 

裏面的onCreate

0

您無法通過Java的引用傳遞變量,所以你需要做的就是定義類,你apparantly做了內變量,它的名字是進步的,但是通過方法調用你指的是變量'pd',它是一個參數。

而應該設置的「進步」到新ProgressDialog這樣的值:

progress = ProgressDialog.show(MainActivity.this, "", "Loading...", true); 

,然後在其他方法

progress.dismiss();