2011-08-03 167 views
-1

我在android編程中有一個簡單的疑問。我不熟悉Java編碼,因此它可能是一個簡單的問題。在java中創建對象

在前兩行我檢索一個數組,我從另一個活動傳遞給此活動...然後我創建一個數組列表。我在第四行創建一個對象。現在問題來了... 我必須運行一個for循環來獲取url值,我必須將它傳遞給BaseFeedParser類。但我不能使用第四行,即在循環中創建對象,因爲它會每次創建一個新對象......這不應該發生......我該如何解決這個問題?

    Intent myintent = getIntent(); 
     String[] ActiveURL = myintent.getStringArrayExtra("URL"); 

     List<String> titles = new ArrayList<String>(); 
     BaseFeedParser parser = new BaseFeedParser(url); 

     // fetching all active URLs 
     for (int i = 0; i < ActiveURL.length + 1; i++) { 
      url = ActiveURL[i]; 
      messages.addAll(parser.parse()); 
     } 

     // now getting the titles out of the messages for display 
     for (Message msg : messages) { 
      titles.add(msg.getTitle()); 
     } 

在此先感謝...

+0

如果您不想每次都創建basefeedParse對象,那麼您必須刪除BasefeedParser中的構造函數,然後可以將該URL傳遞給XMLParser類中的parser.parser(URL)方法,並且必須將其傳遞給BasefeedParser通過創建另一種方法來爲basefeedparser URL分配值。但這也可能導致錯誤。 –

+0

有一個java約定,變量從小寫開始。所以將ActiveUrl改爲活動的Url。 Actualy我不明白你的代碼...我在互聯網上找到的BaseFeedParser是一個抽象類。爲什麼你不能創建新的對象? – gregory561

+0

Java(我認爲Android也是)創建對象沒有任何主要問題。一個問題只會是如果創建一個BaseFeedParser是非常昂貴的,但我不明白爲什麼這應該是這種情況。 (雖然我不知道該API) –

回答

3

有在Java代碼中的一些問題:

Intent myintent = getIntent(); 
    //variables are named in camel case, starting with a lower case letter 
    String[] activeURL = myintent.getStringArrayExtra("URL"); 

    List<String> titles = new ArrayList<String>(); 
    //we will use parser later, see below 
    //BaseFeedParser parser = new BaseFeedParser(url); 

    // fetching all active URLs 
    //it's very easy to loop through a table in java/C/C++ 
    //learn the pattern, it's the simplest, you got confused with the final index 
    for (int i = 0; i < activeURL.length ; i++) { 
     //here you don't change the former object url was referencing, 
     //you are saying that you give the name url to another object in the array 
     //it doesn't create any new item, change giving them a name to use them 
     url = activeURL[i]; 
     //create a new parser for each url, except if they can be recycled 
     //i.e they have a property setUrl 
     messages.addAll(new BaseFeedParser(url).parse()); 
    } 

    // now getting the titles out of the messages for display 
    for (Message msg : messages) { 
     titles.add(msg.getTitle()); 
    } 

事實上,你甚至可以通過縮短整個事情

Intent myintent = getIntent(); 
    String[] activeURL = myintent.getStringArrayExtra("URL"); 
    List<String> titles = new ArrayList<String>(); 

    // fetching all active URLs 
    //use a for each loop 
    for (String url : activeURL) { 
     //loop through messages parsed from feed to add titles 
     for (Message msg : new BaseFeedParser(url).parse()) { 
      titles.add(msg.getTitle()); 
     } 
    } 

如果你不需要消息列表,你稱爲消息。

+1

+1嗯解釋了 –

+0

非常感謝你Stéphane..非常感謝 – ps00131

+0

對於不錯的代碼。但是這會讓應用程序掛起並顯示ANR對話框,因爲這個會導致for循環訪問UI線程本身的網絡操作,所以我建議@ ps00131在AsyncTask或線程或服務中使用此代碼。 –