2012-03-22 7 views
76

Ho un EditText che accetta una stringa dall'utente e un searchButton. Quando viene fatto clic su searchButton, cercherà nel file XML e lo visualizzerà in ListView.Mostra ProgressDialog Android

Sono in grado di ricevere input dall'utente, cercare nel file XML e visualizzare anche il valore cercato dagli utenti nel ListView.

Quello che voglio è visualizzare un ProgressDialog dopo che il pulsante di ricerca è stato cliccato come "PER FAVORE ATTENDERE ... RECUPERO DATI ..." o qualcosa del genere e chiuderlo quando i dati sono mostrati.

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 è stata deprecata dal API Level O https://developer.android.com/reference/ android/app/ProgressDialog.html –

+1

Si dice "Utilizzare un indicatore di avanzamento come ProgressBar in linea all'interno di un'attività piuttosto che utilizzare questa finestra di dialogo modale." Perché non ci mostrano semplicemente come si fa? :) – MehmetGunacti

risposta

261

dichiarare la vostra finestra di avanzamento:

ProgressDialog progress; 

Quando si è pronti per avviare la finestra di avanzamento:

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

e per farlo andare via quando il gioco è fatto:

progress.dismiss(); 

Ecco un piccolo esempio filo per voi:

// 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

Ho scritto sotto il codice ma non funziona: 'searchButton.setOnClickListener (nuova View.OnClickListener() { \t \t \t public void onClick (Visualizza v) { \t \t \t \t // TODO generato automaticamente stub \t \t \t \t System.out.print ("ciao") ; \t \t \t \t Testo di ricerca = (TextView) findViewById (R.id.search_text);. \t \t \t \t searchTextString = searchText.getText() toString(); \t \t \t \t progress.show (Tab1Activity.questo, "Titolo finestra di dialogo", "Attendere prego ... caricamento"); \t \t \t \t readXml (searchTextString); \t \t \t \t progress.dismiss(); \t \t \t \t \t \t} \t \t});' – captaindroid

+0

il 'readXML' richiede molto tempo? – dldnh

+0

nup, ci vuole molto poco tempo come puoi vedere sopra ho anche il metodo readXML di scrittura. – captaindroid

1

Si consiglia di non eseguire le attività ad alta intensità di risorse nel thread principale. Renderà l'interfaccia utente non rispondente e otterrete un ANR. Sembra che tu stia facendo cose che richiedono molte risorse e vuoi che l'utente veda lo ProgressDialog. È possibile dare un'occhiata a http://developer.android.com/reference/android/os/AsyncTask.html per eseguire attività che richiedono molte risorse. Mostra anche come usare un ProgressDialog.

7

Sto utilizzando il seguente codice in uno dei miei progetti attuali in cui scarico i dati da Internet. È tutto nella mia classe di attività.

// ---------------------------- 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

E ora prova a cambiare l'orientamento del dispositivo mentre AsyncTask sta eseguendo ... – Vladimir

+0

L'orientamento è cambiato bene per me. Ho appena testato su un AVD 2.3.3 e sul mio telefono ICS. –

+0

Come posso implementarlo? – user1708134

1

Sto utilizzando il seguente codice in uno dei miei progetti attuali in cui scarico i dati da Internet. È tutto nella mia classe di attività.

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

    } 

ed eseguirlo nel metodo OnCreate come new GetData().execute();

cui calendario è il mio calendarActivity e ho anche creato un CalendarAdapter per impostare questi valori per una visualizzazione elenco.

6

Durante la creazione dell'oggetto per la barra di avanzamento, verificare quanto segue.

Questo fallisce:

dialog = new ProgressDialog(getApplicationContext()); 

Mentre l'aggiunta di contesto attività funziona ..

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

la spiegazione è qui: http://www.doubleencore.com/2013/06/context/ :) –

Problemi correlati