2011-08-03 49 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或线程或服务中使用此代码。 –