2012-03-22 148 views
76

我有一個EditText從用戶和一個searchButton獲取一個字符串。 單擊searchButton時,它將搜索XML文件並將其顯示在ListView中。顯示ProgressDialog Android

我能夠從用戶那裏接受輸入,搜索XML文件,並在ListView中顯示usersearched值。

我想要的是顯示一個ProgressDialog後searchButton被點擊像「請等待...檢索數據...」或類似的東西,並在數據顯示時解僱它。

public class Tab1Activity extends ListActivity { 
private Button okButton; 
private Button searchButton; 
Toast toast; 
String xml; 

private TextView searchText; 
private String searchTextString; 
HashMap<String, String> o; 
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.tab1); 

    searchButton = (Button) findViewById(R.id.search_button); 
    searchButton.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      System.out.print("hello"); 

      searchText = (TextView) findViewById(R.id.search_text); 
      searchTextString = searchText.getText().toString(); 
      readXml(searchTextString); 

     } 
    }); 

} 

private void readXml(String searchTextString1) { 
    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); 

    String xml = XMLfunctions.getXML(); 
      //Here XMLfunctions is class name which parse xml 
    Document doc = XMLfunctions.XMLfromString(xml); 

    int numResults = XMLfunctions.numResults(doc); 

    if ((numResults <= 0)) { 
     Toast.makeText(Tab1Activity.this, "Testing xmlparser", 
       Toast.LENGTH_LONG).show(); 
     finish(); 
    } 

    NodeList nodes = doc.getElementsByTagName("result"); 

    for (int i = 0; i < nodes.getLength(); i++) { 
     HashMap<String, String> map = new HashMap<String, String>(); 

     Element e = (Element) nodes.item(i); 
     String nameMapString = XMLfunctions.getValue(e, "name"); 



     if (nameMapString.toLowerCase().indexOf(searchTextString1.toLowerCase()) != -1) // != -1 means string is present in the search string 
      { 
       map.put("id", XMLfunctions.getValue(e, "id")); 
       map.put("name", XMLfunctions.getValue(e, "name")); 
       map.put("Score", XMLfunctions.getValue(e, "score")); 
       mylist.add(map); 
      } 
    } 

    ListAdapter adapter = new SimpleAdapter(this, mylist, 
      R.layout.parsexml, new String[] { "name", "Score" }, new int[] { 
        R.id.item_title, R.id.item_subtitle }); 

    setListAdapter(adapter); 

    final ListView lv = getListView(); 
    lv.setTextFilterEnabled(true); 
    lv.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, 
       int position, long id) { 
      @SuppressWarnings("unchecked") 
      HashMap<String, String> o = (HashMap<String, String>) lv 
        .getItemAtPosition(position); 


       Toast.makeText(Tab1Activity.this, 
         "Name "+o.get("name")+" Clicked", Toast.LENGTH_LONG) 
         .show();     

     } 
    }); 
} 
+1

ProgressDialog一直以來API級別Øhttps://developer.android.com/reference/棄用android/app/ProgressDialog.html – 2017-04-25 16:12:23

+1

它說:「在活動內部使用ProgressBar等進度指示器,而不是使用此模式對話框。」他們爲什麼不簡單告訴我們如何去做? :) – MehmetGunacti 2017-04-27 03:29:43

回答

261

聲明你的進度對話框:

ProgressDialog progress; 

當你準備好開始進度對話框:

progress = ProgressDialog.show(this, "dialog title", 
    "dialog message", true); 

,並使它消失時,即可大功告成:

progress.dismiss(); 

這裏有一個小螺紋例子給你:

// Note: declare ProgressDialog progress as a field in your class. 

progress = ProgressDialog.show(this, "dialog title", 
    "dialog message", true); 

new Thread(new Runnable() { 
    @Override 
    public void run() 
    { 
    // do the thing that takes a long time 

    runOnUiThread(new Runnable() { 
     @Override 
     public void run() 
     { 
     progress.dismiss(); 
     } 
    }); 
    } 
}).start(); 
+0

我寫下面的代碼,但沒有工作: 'searchButton。setOnClickListener(新View.OnClickListener(){ \t \t \t公共無效的onClick(視圖v){ \t \t \t \t // TODO自動生成方法存根 \t \t \t \t是System.out.print( 「你好」) ; \t \t \t \t SEARCHTEXT =(TextView的)findViewById(R.id.search_text); \t \t \t \t searchTextString = searchText.getText()的toString (); \t \t \t \t progress.show(Tab1Activity.this,「Dialog Title」,「Please wait ... loading」); \t \t \t \t readXml(searchTextString); \t \t \t \t progress.dismiss(); \t \t \t \t \t \t} \t \t});」 – captaindroid 2012-03-22 00:40:02

+0

'readXML'需要很長時間嗎? – dldnh 2012-03-22 00:42:03

+0

nup,它需要很短的時間,你可以看到上面我也寫了readXML方法。 – captaindroid 2012-03-22 00:43:08

1

在主線程,則不應執行資源密集型任務。它會使界面無響應,你會得到一個ANR。看起來你會做資源密集型的東西,並希望用戶看到ProgressDialog。你可以看看http://developer.android.com/reference/android/os/AsyncTask.html來完成資源密集型任務。它還會告訴你如何使用ProgressDialog

7

我在當前的項目中使用下面的代碼,我從互聯網上下載數據。這一切都在我的活動課內。

// ---------------------------- START DownloadFileAsync // -----------------------// 
class DownloadFileAsync extends AsyncTask<String, String, String> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class 
     showDialog(DIALOG_DOWNLOAD_PROGRESS); 
    } 

    @Override 
    protected String doInBackground(String... urls) { 
     try { 
      String xmlUrl = urls[0]; 

      URL u = new URL(xmlUrl); 
      HttpURLConnection c = (HttpURLConnection) u.openConnection(); 
      c.setRequestMethod("GET"); 
      c.setDoOutput(true); 
      c.connect(); 

      int lengthOfFile = c.getContentLength(); 

      InputStream in = c.getInputStream(); 

      byte[] buffer = new byte[1024]; 
      int len1 = 0; 
      long total = 0; 

      while ((len1 = in.read(buffer)) > 0) { 
       total += len1; // total = total + len1 
       publishProgress("" + (int) ((total * 100)/lengthOfFile)); 
       xmlContent += buffer; 
      } 
     } catch (Exception e) { 
      Log.d("Downloader", e.getMessage()); 
     } 
     return null; 
    } 

    protected void onProgressUpdate(String... progress) { 
     Log.d("ANDRO_ASYNC", progress[0]); 
     mProgressDialog.setProgress(Integer.parseInt(progress[0])); 
    } 

    @Override 
    protected void onPostExecute(String unused) { 
     dismissDialog(DIALOG_DOWNLOAD_PROGRESS); 
    } 

} 

@Override 
protected Dialog onCreateDialog(int id) { 
    switch (id) { 
    case DIALOG_DOWNLOAD_PROGRESS: 
     mProgressDialog = new ProgressDialog(this); 
     mProgressDialog.setMessage("Retrieving latest announcements..."); 
     mProgressDialog.setIndeterminate(false); 
     mProgressDialog.setMax(100); 
     mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     mProgressDialog.setCancelable(true); 
     mProgressDialog.show(); 
     return mProgressDialog; 
    default: 
     return null; 
    } 

} 
+1

現在嘗試更改設備的方向,而AsyncTask執行... – Vladimir 2012-03-22 01:13:02

+0

方向改變對我來說很好。我剛剛在2.3.3 AVD和我的ICS手機上進行了測試。 – 2012-03-22 02:03:33

+0

我該如何實施? – user1708134 2013-03-01 11:19:44

1

我使用在我從互聯網上下載的數據我目前的項目之一下面的代碼。這一切都在我的活動課內。

private class GetData extends AsyncTask<String, Void, JSONObject> { 

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

      progressDialog = ProgressDialog.show(Calendar.this, 
        "", ""); 

     } 

     @Override 
     protected JSONObject doInBackground(String... params) { 

      String response; 

      try { 

       HttpClient httpclient = new DefaultHttpClient(); 

       HttpPost httppost = new HttpPost(url); 

       HttpResponse responce = httpclient.execute(httppost); 

       HttpEntity httpEntity = responce.getEntity(); 

       response = EntityUtils.toString(httpEntity); 

       Log.d("response is", response); 

       return new JSONObject(response); 

      } catch (Exception ex) { 

       ex.printStackTrace(); 

      } 

      return null; 
     } 

     @Override 
     protected void onPostExecute(JSONObject result) 
     { 
      super.onPostExecute(result); 

      progressDialog.dismiss(); 

      if(result != null) 
      { 
       try 
       { 
        JSONObject jobj = result.getJSONObject("result"); 

        String status = jobj.getString("status"); 

        if(status.equals("true")) 
        { 
         JSONArray array = jobj.getJSONArray("data"); 

         for(int x = 0; x < array.length(); x++) 
         { 
          HashMap<String, String> map = new HashMap<String, String>(); 

          map.put("name", array.getJSONObject(x).getString("name")); 

          map.put("date", array.getJSONObject(x).getString("date")); 

          map.put("description", array.getJSONObject(x).getString("description")); 

          list.add(map); 
         } 

         CalendarAdapter adapter = new CalendarAdapter(Calendar.this, list); 

         list_of_calendar.setAdapter(adapter); 
        } 
       } 
       catch (Exception e) 
       { 
        e.printStackTrace(); 
       } 
      } 
      else 
      { 
       Toast.makeText(Calendar.this, "Network Problem", Toast.LENGTH_LONG).show(); 
      } 
     } 

    } 

和onCreate方法執行它像new GetData().execute();

其中日曆是我calendarActivity,我也創建了一個CalendarAdapter這些值設置爲列表視圖。

6

在爲進度條創建對象時,請檢查以下內容。

這種失敗:

dialog = new ProgressDialog(getApplicationContext()); 

同時加入了活動的背景下工程..

dialog = new ProgressDialog(MainActivity.this); 
+3

解釋在這裏:http://www.doubleencore.com/2013/06/context/ :) – 2014-12-22 15:31:48