78

I have an EditText which takes a String from the user and a searchButton. When the searchButton is clicked, it will search through the XML file and display it in the ListView.

I am able to take input from the user, search through the XML file and display the usersearched value in the ListView also.

What I want is to display a ProgressDialog after the searchButton is clicked like "PLEASE WAIT...RETRIEVING DATA..." or something like that and dismiss it when the data is shown.

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

        }
    });
}
Willi Mentzel
  • 21,499
  • 16
  • 88
  • 101
captaindroid
  • 2,645
  • 6
  • 28
  • 43
  • 2
    ProgressDialog has been deprecated since API Level O https://developer.android.com/reference/android/app/ProgressDialog.html – Varvara Kalinina Apr 25 '17 at 16:12
  • 2
    It says "Use a progress indicator such as ProgressBar inline inside of an activity rather than using this modal dialog." Why don't they simply show us how to do it ? :) – Wolf359 Apr 27 '17 at 03:29

5 Answers5

265

Declare your progress dialog:

ProgressDialog progress;

When you're ready to start the progress dialog:

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

and to make it go away when you're done:

progress.dismiss();

Here's a little thread example for you:

// 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();
dldnh
  • 8,745
  • 3
  • 33
  • 50
  • I have write below code but doesnot work: '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(); progress.show(Tab1Activity.this, "Dialog Title", "Please wait...loading"); readXml(searchTextString); progress.dismiss(); } });' – captaindroid Mar 22 '12 at 00:40
  • nup,it takes very small time as you can see above i have write readXML method also. – captaindroid Mar 22 '12 at 00:43
  • I wonder if readXML runs so quickly that you don't see the progress dialog. if you were doing something over the network that really took a couple seconds -- well first of all, you'd do that in a separate thread, but then you'd see the full effect of the progress dialog. if you do end up adding threads, make sure you `show` and `dismiss` the progress dialog in the UI thread. – dldnh Mar 22 '12 at 00:44
  • But i think it has enough time to show progressDialog. When i clicked searchButton it takes about 2-3 seconds approx. – captaindroid Mar 22 '12 at 00:47
  • you know what, it's probably because `readXML` isn't allowing the UI to catch its breath. you might want to put it in its own thread -- either with simple `new Thread(...)` (which I prefer) or with `AsyncTask`, as Win Myo Htet suggests. – dldnh Mar 22 '12 at 00:52
  • I've added a snippet of threading from my app into the answer – dldnh Mar 22 '12 at 00:56
  • I am getting progresDialog for some time but gives force close error without any result. – captaindroid Mar 22 '12 at 01:20
  • I have tried this on button click but gives same force close error:
    `new Thread() { public void run() { try { sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } progress.dismiss(); } }.start();`
    – captaindroid Mar 22 '12 at 01:22
  • `progress.dismiss` needs to be in the UI thread -- see `runOnUiThread` in my answer – dldnh Mar 22 '12 at 01:23
  • Tried this but same error: `new Thread(new Runnable() { public void run() { readXml(searchTextString); runOnUiThread(new Runnable() { public void run() { progress.dismiss(); } }); } }).start();` ProgressDialog appears but gives force close error without any search result. – captaindroid Mar 22 '12 at 01:48
  • Not in code, when i run the program progress dialog appears but close with in a time and says "THE APPLIATION BBS HAS STOPPED UNPECTEDLY.PLEASE TRY AGAIN. FORCE CLOSE" – captaindroid Mar 22 '12 at 01:55
  • `adb logcat` from the shell/command line will help you determine where the crash was. – dldnh Mar 22 '12 at 01:56
  • readxml method update ui here. I think thats the reason why it gives force close error. – captaindroid Mar 22 '12 at 02:04
  • AFAICS, `dismiss()` can be called safely from any thread. :-) See http://developer.android.com/reference/android/app/Dialog.html#dismiss() – darrenp Apr 23 '15 at 17:09
  • This works for me but I'm trying to understand why you are creating a new Thread? Because it shouldn't be on the main thread potentially freezing the UI? – Bob Dec 21 '16 at 14:00
  • there are a couple new threads @Bob - which one are you referring to? – dldnh Dec 21 '16 at 16:16
8

I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.

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

}
the_gesslar
  • 195
  • 8
6

While creating the object for the progressbar check the following.

This fails:

dialog = new ProgressDialog(getApplicationContext());

While adding the activities context works..

dialog = new ProgressDialog(MainActivity.this);
Dani
  • 3,518
  • 4
  • 25
  • 35
amalBit
  • 11,489
  • 6
  • 71
  • 89
2

You should not execute resource intensive tasks in the main thread. It will make the UI unresponsive and you will get an ANR. It seems like you will be doing resource intensive stuff and want the user to see the ProgressDialog. You can take a look at http://developer.android.com/reference/android/os/AsyncTask.html to do resource intensive tasks. It also shows you how to use a ProgressDialog.

JDJ
  • 4,198
  • 3
  • 22
  • 43
Win Myo Htet
  • 5,267
  • 3
  • 34
  • 53
1

I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.

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

    }

and execute it in OnCreate Method like new GetData().execute();

where Calendar is my calendarActivity and i have also created a CalendarAdapter to set these values to a list view.

AndroidGeek
  • 30,803
  • 14
  • 212
  • 262