开发者

Android - Progress Dialog

开发者 https://www.devze.com 2023-04-05 23:00 出处:网络
I\'m a having a problem. I want to make a progress dialog while my app download some news from a feed.

I'm a having a problem. I want to make a progress dialog while my app download some news from a feed. This is my code at the moment:

public class NyhedActivity extends Activity {
    String streamTitle = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nyheder);

        TextView result = (TextView)findViewById(R.id.result);

           try {
       URL rssUrl = new URL("http://rss.tv2sport.dk/rss/*/*/*/248/*/*");
       SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
       SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
       XMLReader myXMLReader = mySAXParser.getXMLReader();
       RSSHandler myRSSHandler = new RSSHandler();
       myXMLReader.setContentHandler(myRSSHandler);
       InputSource myInputSource = new InputSource(rssUrl.openStream());
       myXMLReader.parse(myInputSource);

       result.setText(streamTitle);

      } catch (MalformedURLException e) {
       // TODO Auto-generated catch bloc开发者_Go百科k
       e.printStackTrace();
       result.setText("Cannot connect RSS!");
      } catch (ParserConfigurationException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       result.setText("Cannot connect RSS!");
      } catch (SAXException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       result.setText("Cannot connect RSS!");
      } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       result.setText("Cannot connect RSS!");
      }


       }

       private class RSSHandler extends DefaultHandler
       {
        final int stateUnknown = 0;
        final int stateTitle = 1;
        int state = stateUnknown;

        int numberOfTitle = 0;
        String strTitle = "";
        String strElement = "";

      @Override
      public void startDocument() throws SAXException {
       // TODO Auto-generated method stub
       strTitle = "Nyheder fra ";
      }

      @Override
      public void endDocument() throws SAXException {
       // TODO Auto-generated method stub
       strTitle += "";
       streamTitle = "" + strTitle;
      }

      @Override
      public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {
       // TODO Auto-generated method stub
       if (localName.equalsIgnoreCase("title"))
       {
        state = stateTitle;
        strElement = "";
        numberOfTitle++;
       }
       else
       {
        state = stateUnknown;
       }
      }

      @Override
      public void endElement(String uri, String localName, String qName)
        throws SAXException {
       // TODO Auto-generated method stub
       if (localName.equalsIgnoreCase("title"))
       {
        strTitle += strElement + "\n"+"\n";
       }
       state = stateUnknown;
      }

      @Override
      public void characters(char[] ch, int start, int length)
        throws SAXException {
       // TODO Auto-generated method stub
       String strCharacters = new String(ch, start, length);
       if (state == stateTitle)
       {
        strElement += strCharacters;
       }
      }
    }

}

I can't figure out how to use the progress dialog. Is it possible for anyone to show my where to define the progressdialog and least but not most how to implement it. I've looked a lot of places, but everyone seems to do it different ways, and I can't get any of them to work :(

I've even tried to make a fake one which runs on sleep, but I can't figure out what I'm doing wrong.


My preferred way:

class MyActivity extends Activity{

final static int PROGRESS_DIALOG = 1;

ProgressDialog dialog;

@Override
protected Dialog onCreateDialog(int id){
   switch(id){
   case PROGRESS_DIALOG:
      dialog = new ProgressDialog(this);
      dialog.setMessage("Whatever you want to tell them.");
      dialog.setIndeterminate(true);
      dialog.setCancelable(true); // if you want people to be able to cancel the download
      dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
         @Override
         public void onCancel(DialogInterface dialog)
         {
             **** cleanup.  Not needed if not cancelable ****
         }});
      return dialog;
   default:
      return null;
   }
}

When you want it to appear, you can do showDialog(PROGRESS_DIALOG) and when you want it to go away you can do dialog.dismiss().


Don't do any long-running stuff like network IO in the UI thread (that's what calls your onCreate()), Android will force close your app. Use an AsyncTask instead, check out the linked javadoc for an example.

  • Create and show your progress dialog in onPreExecute() and keep a reference to it in a field
  • Update progress by calling publishProgress() from your doInBackground() and handle that in onProgressUpdate(), e.g. like the example linked above
  • Close your progress dialog and update your UI (text fields, etc.) in onPostExecute()

To create the dialog in onPreExecute(), pass a Context to your AsyncTask constructor, e.g. your activity this and store it in a field.

If you want your data to survive orientation changes or persist across activity restarts, let your AsyncTask write your parsed data into a SQLite database and then display it only the database contents in your activity.


As for the actual "showing a progress dialog" part, use one of its static factory methods show(...):

ProgressDialog dialog = ProgressDialog.show(
    this, // a context, e.g. your activity
    "Downloading...", // title
    "Downloading RSS feed.", // message
);

This will create and show a dialog in one step.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号