在java中创建一个对象

时间:2011-08-03 11:42:24

标签: java android object

我对android编程有一个简单的疑问。我不熟悉java编码。所以它可能是一个简单的问题。

在前两行中,我正在检索一个数组,我从另一个活动传递给了这个活动......然后我创建了一个数组列表。我在第4行创建了一个对象。问题来了...... 我必须运行for循环来获取url值,我必须在BaseFeedParser类中传递它。但是我不能使用第4行,即在循环中创建对象,因为它每次都会创建一个新对象......这不应该发生......我该如何解决这个问题呢?

                    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());
        }

提前致谢...

1 个答案:

答案 0 :(得分: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());
        }
    }

如果您不需要消息列表,则调用消息。