在Android中无法看到进度条上的进度

时间:2015-01-18 11:55:31

标签: android xml android-progressbar android-toast

点击按钮我正在调用openChannel函数

fetchXML是一个下载xml并设置变量的线程。虽然加载新视图需要2-5秒,但我可以看到进度条直接从0跳到100。

在openchannel中也是Toast ...它只在加载新视图后才加载,即在loadView之后加载...这会破坏它的写入目的。

Toast应该在showNews()之前运行,但它会在它之后执行!!!!

为什么会延迟? 任何帮助都得到了回报。

更新:

HandleXML.java

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

public class HandleXML
{
   private List<String> title = new ArrayList<String>();
   private List<String> description = new ArrayList<String>();
   private int totalNews = 0;

   private String urlString = null;
   private XmlPullParserFactory xmlFactoryObject = null;
   public volatile boolean parsingComplete = true;

   public HandleXML(String url)
   {
      this.urlString = url;
   }

   public List<String> getTitle()
   {
      return title;
   }
   public List<String> getDescription()
   {
      return description;
   }

   public int getTotalNews()
   {
       return totalNews;
   }

   public void parseXMLAndStoreIt(XmlPullParser myParser) 
   {
      int event;
      String text=null;
      boolean isItem = false, isTitle = false;

      try 
      {
         event = myParser.getEventType();
         while (event != XmlPullParser.END_DOCUMENT && totalNews < 10) 
         {
             String name=myParser.getName();
             switch (event)
             {
                case XmlPullParser.START_TAG:   
                    if(name.equals("item"))
                    {
                        isItem = true;
                    }
                    break;
                case XmlPullParser.TEXT:    
                    text = myParser.getText();
                    text = text.replaceAll("<.*?>", "");
                    break;
                case XmlPullParser.END_TAG:
                    if(name.equals("title") && isItem)
                    {
                        title.add(text);
                        isItem = false;
                        isTitle = true;
                    }
                    else if(name.equals("description") && isTitle)
                    {
                        description.add(text);
                        totalNews++;
                        isTitle = false;
                    }
                    break;
             }       
             event = myParser.next(); 
         }
         parsingComplete = false;

      } 
      catch (Exception e) 
      {
         e.printStackTrace();
      }
   }

   public void fetchXML()
   {
       Thread thread = new Thread(new Runnable(){
           @Override
           public void run() 
           {
              try 
              {
                 URL url = new URL(urlString);
                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                 conn.connect();                 
                 InputStream stream = conn.getInputStream();
                 xmlFactoryObject = XmlPullParserFactory.newInstance();
                 XmlPullParser myparser = xmlFactoryObject.newPullParser();
                 myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                 myparser.setInput(stream, null);
                 parseXMLAndStoreIt(myparser);
                 stream.close();
              } 
              catch (Exception e) 
              {
                  e.printStackTrace();
              }
           }
          });
      thread.start(); 
   }

}

MainActivity.java

import java.util.Date;
import java.util.List;
import java.util.Random;

import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    private int titleIds[] = {R.id.news1,R.id.news2,R.id.news3,R.id.news4,R.id.news5,R.id.news6,R.id.news7,R.id.news8,R.id.news9,R.id.news10};  
    private int descIds[] = {R.id.desc1,R.id.desc2,R.id.desc3,R.id.desc4,R.id.desc5,R.id.desc6,R.id.desc7,R.id.desc8,R.id.desc9,R.id.desc10};  
    private int colorIds[] = {R.color.DarkSalmon,R.color.DarkCyan,R.color.CornflowerBlue,R.color.BlueViolet,R.color.Goldenrod,R.color.Orchid,R.color.IndianRed,R.color.MediumAquamarine,R.color.LightCoral,R.color.Teal};

    private ProgressBar progress;
    private HandleXML obj = null;

    private int currCnt = 0;
    private int rand_color = new Random().nextInt(10);
    private int rand_color2 = new Random().nextInt(10);
    private boolean inMain = true, inChannel = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        findViewById(R.id.newsScroll).setVisibility(View.GONE);
        findViewById(R.id.newsChannels).setVisibility(View.VISIBLE);

        progress = (ProgressBar) findViewById(R.id.progressBar);
        progress.setMax(100);

    }

    public void showNews(String url)
    {       
        currDesc = null;    
        currTitle = null;
        obj = null;

        progress.setProgress(30);
        System.out.println("30 : "+new Date());

        rand_color = new Random().nextInt(10);
        rand_color2 = new Random().nextInt(10);

        if(rand_color == rand_color2 && rand_color == 9)
            rand_color2 = 0;
        else if(rand_color == rand_color2)
            rand_color2 = rand_color+1;

        obj = new HandleXML(url);
        obj.fetchXML();    

        progress.setProgress(50);  

        while(obj.parsingComplete);

        progress.setProgress(70);

        if(obj.getTitle().size() >0 && obj.getDescription().size() >0)
        {
            List<String> title = obj.getTitle();
            List<String> description = obj.getDescription();


            for(int i=0; i<obj.getTotalNews(); i++)
            {
                Button twT = (Button) findViewById(titleIds[i]);
                twT.setText(title.get(i).trim());
                twT.setBackground(new ColorDrawable(getResources().getColor(colorIds[rand_color])));

                Button twD = (Button) findViewById(descIds[i]);
                twD.setText(description.get(i).trim());
                twD.setVisibility(View.GONE);
            }
        }
        else
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("AHL NEWS ALERT")
              .setMessage("FAILED TO LOAD NEWS !!")
              .setCancelable(false)
              .setNegativeButton("Close",new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int id) {
                      dialog.cancel();
                  }
              });
              AlertDialog alert = builder.create();
              alert.show();
        }

        progress.setProgress(90);
    }

    public void openChannel(View view)
    {       
        progress.setProgress(10);
        Toast.makeText(getBaseContext(), "Loading Please Wait ... ", Toast.LENGTH_SHORT).show();

        showNews("http://example.com/news.xml");

        progress.setProgress(100);

        findViewById(R.id.newsScroll).setVisibility(View.VISIBLE);
        findViewById(R.id.newsChannels).setVisibility(View.GONE);
        findViewById(R.id.newsScroll).scrollTo(0, 0);

        inMain = false;
        inChannel = true;
    }
}

1 个答案:

答案 0 :(得分:1)

如果fetchXML正在使用线程,那么它应该如何工作。您将进度设置为10,然后调用loadNews调用其中有一个Thread的fetchXML。 为您创建一个Thread只需要几分之一秒。

我建议您使用AsyncTask,这样可以更好地控制获取和解析xml的过程。您应该从AsyncTask内部更新ProgressBar。有两种方法。一个是onProgressUpdate,另一个是onPostExecute