【问题标题】:Pass value from public method to private array将值从公共方法传递到私有数组
【发布时间】:2011-11-27 10:44:45
【问题描述】:

我需要存储从 http 检索到的大量内容。我创建了一种检索内容的方法。但我需要将它存储在一个在外部声明的数组中。我在做返回值时遇到了麻烦。

我的问题是:

1)我在哪里放置退货声明?

2)如何将 searchInfo 中的内容存储到数组 mStrings[] 中?

这是我的代码。

public class MainActivity extends Activity
{
ListView list;
Adapter adapter;

private static final String targetURL ="http://www.google.com/images";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    list=(ListView)findViewById(R.id.list);
    adapter=new Adapter(this, mStrings);
    list.setAdapter(adapter);
    }

    public String searchInfo()
{
    try {
        // Get the URL from text box and make the URL object

        URL url = new URL(targetURL);

        // Make the connection
        URLConnection conn = url.openConnection();
        BufferedReader reader = new BufferedReader(
         new InputStreamReader(conn.getInputStream()));

        // Read the contents line by line (assume it is text),
        // storing it all into one string
        String content ="";
        String line = reader.readLine();  
        Pattern sChar = Pattern.compile("&.*?;");
        Matcher msChar = sChar.matcher(content);
        while (msChar.find()) content = msChar.replaceAll("");

        while (line != null) {

            if(line.contains("../../"))
            {                   
                content += xyz;
                line = reader.readLine();                   
            }

            else if (line.contains("../../") == false)
            {
                line = reader.readLine();
            }

        }

        // Close the reader
        reader.close();

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

}

private String[] mStrings={searchImage()};

}

【问题讨论】:

    标签: java android arrays class methods


    【解决方案1】:

    你有几个选择:

    1. 您可以将 mStrings[] 声明为实例变量(将 protected String[] mStrings; 放在声明适配器的行之后)然后在您的 onCreate 方法 (mStrings = new String[SIZE];) 中对其进行初始化你的阵列。之后,您的 searchInfo 方法可以只将项目添加到 mString 而不必返回任何内容(因为实例变量对类的所有成员都是可见的)。

    2. 您可以更改 searchInfo 的签名,使其返回 String[],然后在该方法中声明一个临时字符串数组,向其中添加项目并将其返回给调用者 (mStrings = searchInfo();)

      李>

    在上述两种情况下,它都假定您知道数组的长度(因此您可以对其进行初始化)。您可以使用 ArrayList 而不是 String 数组,因为它们可以动态增长。然后,您可以将 arrayList 转换为数组:

    yourArrayList.toArray(mStrings);
    

    只要您将 mStrings 初始化为非空值(即mStrings = new String[1];

    【讨论】:

    • 谢谢。我想我坚持使用字符串数组。因为它来自我得到的一个例子。如何将字符串存储到字符串数组中?我有一个 String[] 数组;必须将 String xyz 存储到数组中。以及有关返回值的错误。但是如果我想改成ArrayList,我在其他类文件中的代码会不会有太大的变化?
    猜你喜欢
    • 2012-05-05
    • 2016-03-16
    • 1970-01-01
    • 2011-09-19
    • 2020-11-21
    • 1970-01-01
    • 2018-04-19
    • 2012-10-11
    • 1970-01-01
    相关资源
    最近更新 更多