2013-02-22 95 views
0

如何顯示此代碼的ProgressDialog?Android ProgressDialog

try{ 

      leggiNews = Pattern.compile("<p><a href='(.*?)' class='rossobig'>(.*?)</a><br/>(.*?)</p>"); 


      leggi = leggiNews.matcher(getURL("http://www.example.com/")); 

         } catch(UnknownHostException tt){ 
          Toast t=Toast.makeText(MainActivity.this, "NESSUNA CONNESSIONE DISPONIBILE!\nATTIVA LA RETE PER QUESTO SERVIZIO.", Toast.LENGTH_LONG); 
          t.setGravity(Gravity.TOP, 0, 240); 
          t.show(); 
         }catch (Exception e) { 
           Toast t=Toast.makeText(MainActivity.this, "[ERRORE GENERICO!]\n"+e, Toast.LENGTH_LONG); 
           t.setGravity(Gravity.TOP, 0, 240); 
           t.show(); 
       } 
專門爲使用getURL()方法

static final String getURL(String u)throws IOException { 
    URL url = new URL(u); 
    InputStream content = (InputStream) url.getContent(); 
     BufferedReader in = new BufferedReader(new InputStreamReader(content)); 
     String line; 
     String a=""; 
     while ((line = in.readLine()) != null) { 
      a+=line; 
      } 
     in.close(); 
     content.close(); 
    return a; 
    } 

方法的getURL總是在同一個班級,我怎麼能正確地插入ProgressDialog?謝謝。

+0

在我看來,你正在做一些網絡可以做到這一點使用不同主題的網絡操作?我對嗎?如果是這種情況,請查看AsyncTask。 – 2013-02-22 11:55:05

+0

是的,但AsyncTask類必須是外部的還是內部的? – Enzo 2013-02-22 11:57:37

+0

這基本上取決於你。你可以創建一個擴展AsyncTask的類,或者你可以創建一個擴展AsynctTask的interal私有類。它只是一個最適合你的問題。 – 2013-02-22 12:00:58

回答

0

如下

ProgressDialog progress = ProgressDialog.show(this, "", "Loading ...", true); 
new Thread(new Runnable(){ 
     @Override 
     public void run(){ 
      try{ 
       leggiNews = Pattern.compile("<p><a href='(.*?)' class='rossobig'>(.*?)</a><br/>(.*?)</p>"); 
       leggi = leggiNews.matcher(getURL("http://www.example.com/")); 
      } catch(UnknownHostException tt){ 
         tt.printStackTrace(); 
      } catch (Exception e) { 
          e.printStackTrace(); 
      } 
      runOnUiThread(new Runnable() { 

        @Override 
        public void run() { 
         progress.dismiss(); 
        } 
       }); 

     } 
}).start(); 

請確保ProgressDialog的對象將是類變量,這裏

+0

使用此代碼,應用程序崩潰!我聲明ProgressDialog是這樣的:final ProgressDialog progress; progress = ProgressDialog.show(this,「」,「Loading ...」,true); – Enzo 2013-02-22 12:20:00