Android ProgressDialog

2019-09-15 00:17发布

问题:

how can I display a ProgressDialog for this code?

 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();
                } 

specifically for the getURL() method:

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;
   }

The method getURL is always in the same class, how can I properly insert a ProgressDialog? Thank you.

回答1:

You can do it using different Thread for Network operations as follows

 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();

Please make sure that object of ProgressDialog will be class variable here