2012-05-03 29 views
0

當我按下按鈕時,它應該從網頁中檢索數據並根據我的佈局顯示它。它做得很好,但只有當我點擊後,返回到我的主要活動(家庭活動)並再次按下按鈕。Android:從網站檢索XML信息時如何加快加載時間?

加載第一次按下按鈕並且有時不起作用需要花費很長時間。但第二次是瞬間加載[正常工作]。

下面的代碼 - 三個班 - HomeActivity.java,News.Java和MyNewsHandler.java

public class HomeActivity extends Activity 
{ 
String username = " "; 
Button alog; 
Button news; 
Button forumTime; 
EditText usernameEntry; 
SharedPreferences preferences; 
ImageView image; 
TextView usernametv; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.home); 

    forumTime = (Button)findViewById(R.id.timeButton); 
    news = (Button) findViewById(R.id.newsButton); // <--- Heres the problem 
    alog = (Button) findViewById(R.id.alogButton); 
    usernameEntry = (EditText) findViewById(R.id.username); 


    //For news button 
    OnClickListener newsListener = new OnClickListener() 
    { 
     public void onClick(View v) 
     { 
      Intent intent = new Intent(HomeActivity.this, News.class); 
      startActivity(intent); 
     } 
    }; 

    //Attaching listeners 
    //forumTime.setOnClickListener(timeListener); 
    //alog.setOnClickListener(alogListener); 
    news.setOnClickListener(newsListener); 
} 

public void display(String string) 
{ 
    Toast.makeText(getBaseContext(), string, 300000).show(); 
} 

}

public class MyNewsHandler extends DefaultHandler 
{ 
private Boolean inTitle = false; 
private Boolean inDescription = false; 
private Boolean inItem = false; 
private Boolean inCategory = false; 
static public ArrayList<String> title = new ArrayList<String>(), 
    description = new ArrayList<String>(), category = new ArrayList<String>(); 
private StringBuilder buff = null; 
// All methods auto called in this order - start, characters, end 
/* 
* Called when an xml tag starts 
* imgView.setImageResource(R.drawable.newImage); 
*/ 
@Override 
public void startElement(String uri, String localName, String qName,Attributes attributes) 
{ 
    if (inItem) 
    { 
     if (localName.equals("title")) 
     { 
      inTitle = true; 
      buff = new StringBuilder(); 
     } 
     if (localName.equals("description")) 
     { 
      inDescription = true; 
      buff = new StringBuilder(); 
     } 
     if (localName.equals("category")) 
     { 
      inCategory = true; 
      buff = new StringBuilder(); 
     } 

    } 
    if (localName.equals("item")) 
    { 
     inItem = true; 
    } 
} 
/* 
* Called when an xml tag ends 
*/ 
@Override 
public void endElement(String uri, String localName, String qName)throws SAXException 
{ 
    if (!inTitle && !inDescription && !inCategory) 
    { 
     inItem = false; 
    } 
    else 
    { 
     if (inTitle) 
     { 
      String check = buff.toString().trim(); 
      title.add(check); 
      inTitle = false; 
      buff = null; 
     } 
     if (inDescription) 
     { 
      String check2 = buff.toString().trim(); 
      String array []; 
      int index = 0; 
      if (check2.contains("/>")) 
      { 
       array = check2.split("/>"); 
       index = check2.indexOf("10;"); 
       description.add(array[array.length - 1].trim()); 
      } 

      else description.add(check2); 
      //description.add(array[1]); 
      inDescription = false; 
      buff = null; 
     } 
     if(inCategory) 
     { 
      String check = buff.toString().trim(); 
      category.add(check); 
      inCategory = false; 
      buff = null; 
     } 
    } 
} 
/* 
* Called to get tag characters 
*/ 
@Override 
public void characters(char ch[], int start, int length) 
{ 
    if (buff != null) 
    { 
     for (int i = start; i < start + length; i++) 
     { 
      buff.append(ch[i]); 
     } 
    } 
} 

}

public class News extends ListActivity 
{ 
String url; 
TextView text1; 
TextView text2; 
static ImageView img; 
// newsList contains the list items 
static ArrayList<HashMap<String, Object>> newsList = new ArrayList<HashMap<String, Object>>(); 
// to store drawable id's 
static HashMap<String, Integer> images = new HashMap<String, Integer>(); 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    //Load xml containing image view and a linear layout with 2 textviews 
    setContentView(R.layout.aloglistview); 

    img = (ImageView)findViewById(R.id.imageView2); 
    text1 = (TextView) findViewById(R.id.text1); 
    text2 = (TextView) findViewById(R.id.text2); 

    // url we are retrieving from 
    url = "http://services.runescape.com/m=news/latest_news.rss"; 

    HttpClient httpclient = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet(url); 
    String result = ""; // result of http Post 
    try 
    { 
     // Execute HTTP get Request 
     HttpResponse response = httpclient.execute(httpget); 

     // Extract the page content returned from the response 
     BufferedReader in = new BufferedReader(new InputStreamReader(
       response.getEntity().getContent())); 
     StringBuffer sb = new StringBuffer(""); 
     String line = ""; 
     String NL = System.getProperty("line.separator"); 
     while ((line = in.readLine()) != null) 
     { 
      sb.append(line + NL); 
     } 
     in.close(); 
     result = sb.toString(); // resulting content of the page 
    } catch (ClientProtocolException e) 
    { 
     Log.d("ERROR", "ClientProtocolException=" + e); 
     System.err.println("ClientProtocolException=" + e); 
    } catch (IOException e) 
    { 
     Log.d("ERROR", "IOException=" + e); 
     System.err.println("IOException=" + e); 
    } 
    try 
    { 
     //Parse the resulting page 
     Xml.parse(result, new MyNewsHandler()); 
    } catch (SAXException e) 
    { 
     e.printStackTrace(); 
    } catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
    //needs to match formulate list thing 
    SimpleAdapter adapter = new SimpleAdapter(this, newsList, 
      R.layout.newsitem, new String[] { "Title", "Description", "Image"}, 
      new int[] { R.id.textnews1, R.id.textnews2, R.id.imageView2}); 

    populateList(); //Add all items to the newslist 
    setListAdapter(adapter); 
} 
public void populateList() 
{ 
    //Method to add to images hashmap 
    initMap(); 
    //reset each time the list is populated 
    newsList = new ArrayList<HashMap<String, Object>>(); 
    //Display 10 items 
    for (int i = 0; i < 11; i++) 
    { 
     HashMap<String, Object> temp = new HashMap<String, Object>(); 
     String title = MyNewsHandler.title.get(i); 
     String category = MyNewsHandler.category.get(i); 
     //default drawable 
     int drawable = R.drawable.item; 
     //Match title text to hash keys to set correct image 
     for (Map.Entry<String, Integer> entry : images.entrySet()) 
     { 
      String key = entry.getKey(); 
      Object value = entry.getValue(); 
      if(category.contains(entry.getKey())) 
      { 
       drawable = entry.getValue(); 
       break; 
      } 
      else drawable = R.drawable.item; 
     } 
     temp.put("Title", title); 
     temp.put("Description", " " + MyNewsHandler.description.get(i)); 
     temp.put("Image",drawable); 
     newsList.add(temp); 
    } 
} 
public void display(String string) 
{ 
    Toast.makeText(getBaseContext(), string, 1000202).show(); 
} 
public void initMap() 
{ 
    images.put("Behind the Scenes News",R.drawable.behindthescenes); 
    images.put("Customer Support News",R.drawable.customerservice); 
    images.put("Game Update News",R.drawable.gameupdate); 
    images.put("Website News",R.drawable.devblog); 
    images.put("Technical News",R.drawable.technicalnews); 
} 

}

對不起,代碼是如此ong ..問題在於它的工作原理(哈..),但是當我第一次需要它的時候它不會立即加載。

爲此,它會: 開始應用>打新聞按鈕>「犯規負荷,黑屏」

,但我這樣做時,它的工作原理: 啓動應用>打新聞按鈕>回擊>打新聞按鈕> 「立即加載」

我跟着一個建議,我在按下按鈕之前先進行了解析,也做了另一次嘗試,我完全擺脫了圖像(認爲可能是延遲)。沒有不同。仍然是同樣的行爲。

任何建議表示讚賞!

+0

我認爲你的問題在於第2步。每次新聞活動加載時,您是否都訪問過網站?你是否在單獨的線程中進行HTTP連接?你能顯示連接和檢索響應的代碼嗎? –

+0

很難說沒有看到代碼可能是什麼問題......我知道你認爲它是標準的東西,但由於你的解釋沒有任何明顯的錯誤,所以我們需要看看你實際上是什麼盡力提供有用的建議。 –

+0

在代碼中添加了你們。 – ryvianstyron

回答

1

樹幾點:

  1. 使用AsyncTask任何內容沒有直接關係的UI
  2. 緩存一切。從網站獲取XML後,在開始下載之前將其保存在某處並在下次從文件加載時。
  3. 預加載。不要等待用戶點擊按鈕。只要您的應用程序啓動,請啓動AsyncTask(請參閱第1頁)以執行後臺下載和XML解析。當用戶按下按鈕時,結果將準備就緒。
+0

您好我嘗試預先加載xml,在用戶點擊按鈕之前。但行爲沒有改變。 – ryvianstyron

+0

那麼你可能會遇到DNS設置問題,首先請求超時或需要很長時間,因爲沒有關於你試圖從中下載數據的服務器位置的數據。並且第二次它已經在緩存中,所以它幾乎立即工作。您可以嘗試在XML請求中使用數字地址(123.234.123.234)而不是域名,並查看會發生什麼情況。 – lenik

+0

對不起,花了我很長時間才接受這個...... !!我得到了這個工作很久以前! – ryvianstyron

1

一切lenik說。

我的解決方案稍有不同。我做了這樣的事情:

  1. 開(按下按鈕或其他觸發事件)發出意圖是 揭開序幕的IntentService(代替的AsyncTask)。爲什麼?它的語法 更簡單,我想從幾個地方調用它。
  2. 立即開始顯示結果,並在結果中填入結果,因爲它們的輸入爲 。我這樣做是通過一個 ContentProvider將所有數據公開並將ListFragment關閉。
+0

嘿傢伙感謝所有的幫助!我確實嘗試了幾乎所有人都提出的建議,但我總是被別人卡住。我今天發現了這個偉大的網站 - > http://www.ibm.com/developerworks/xml/tutorials/x-androidrss/,它真的解決了這個問題,現在我要做的就是弄清楚如何將圖像添加到實際的ListView ... – ryvianstyron