Android:不确定我的方法为什么不返回ArrayList <hashmap <string,string =“”>&gt; </hashmap <string,>

时间:2014-08-18 13:15:07

标签: java android arraylist android-asynctask

嘿,我的问题是在我的AsyncTask方法中,doInBackground我定义了一个返回类型ArrayList<HashMap<String, String>>,然后在我的代码中我返回了类型为ArrayList<HashMap<String, String>>的menuItems。我已经看到了类似的情况,它说并非所有出口都支持返回ArrayList<HashMap<String, String>>,但是看着我的代码,我无法看到除了ArrayList<HashMap<String, String>>以外的任何其他任何帮助都将被大大适用。这是我的doInBackground代码

protected ArrayList<HashMap<String, String>> doInBackground(String...petrolPriceURL){

                 ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

            {

                for(int i = 0; i < 100; i++){


                    publishProgress(1);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }


                String urlString = petrolPriceURL.toString();
                String result = "";
                InputStream anInStream = null;
                int response = -1;
                URL url = null;

                try {
                    url = new URL(urlString);
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    return null;
                }
                URLConnection conn = null;
                try {
                    conn = url.openConnection();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    return null;
                }

                // Check that the connection can be opened
                if (!(conn instanceof HttpURLConnection))
                    try {
                        throw new IOException("Not an HTTP connection");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        return null;
                    }
                try
                {
                    // Open connection
                    HttpURLConnection httpConn = (HttpURLConnection) conn;
                    httpConn.setAllowUserInteraction(false);
                    httpConn.setInstanceFollowRedirects(true);
                    httpConn.setRequestMethod("GET");
                    httpConn.connect();
                    response = httpConn.getResponseCode();
                    // Check that connection is OK
                    if (response == HttpURLConnection.HTTP_OK)
                    {
                        // Connection is OK so open a reader 
                        anInStream = httpConn.getInputStream();
                        InputStreamReader in= new InputStreamReader(anInStream);
                        BufferedReader bin= new BufferedReader(in);

                        // Read in the data from the RSS stream
                        String line = new String();
                        while (( (line = bin.readLine())) != null)
                        {
                            result = result + "\n" + line;
                            Log.v(TAG, "index=" + result);

                        }
                    }
                }
                catch (IOException ex)
                {
                        try {
                            throw new IOException("Error connecting");
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        Handler parser = new Handler();
                        String xml = result.toString(); // getting XML
                        Document doc = parser.getDomElement(xml); // getting DOM element

                        NodeList nl = doc.getElementsByTagName(KEY_FUEL);
                        // looping through all item nodes <item>
                        for (int i = 0; i < nl.getLength(); i++) {
                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();
                            Element e = (Element) nl.item(i);
                            // adding each child node to HashMap key => value
                            map.put(KEY_HIGHEST, parser.getValue(e, KEY_HIGHEST));
                            map.put(KEY_AVERAGE, parser.getValue(e, KEY_AVERAGE));
                            map.put(KEY_LOWEST, "Rs." + parser.getValue(e, KEY_LOWEST));
                            map.put(KEY_LINK, parser.getValue(e, KEY_LINK));

                            // adding HashList to ArrayList
                            menuItems.add(map);
                        }
                        return menuItems;
                }
            }

       }

我得到的错误是

This method must return a result of type ArrayList<HashMap<String,String>>  PetrolPriceActivity.java    /PetrolpriceTestProject/src/org/me/myandroidstuff   line 78 

重新评估的代码:

 @Override
protected ArrayList<HashMap<String, String>> doInBackground(String...petrolPriceURL) {

    for(int i = 0; i < 100; i++) {
        publishProgress(1);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    String urlString = petrolPriceURL.toString();
    String result = "";
    InputStream anInStream = null;
    int response = -1;
    URL url = null;

    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        return null;
    }
    URLConnection conn = null;
    try {
        conn = url.openConnection();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        return null;
    }

    // Check that the connection can be opened
    if (!(conn instanceof HttpURLConnection)) {
        try {
            throw new IOException("Not an HTTP connection");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            return null;
        }
    }

    try {
        // Open connection
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        response = httpConn.getResponseCode();
        // Check that connection is OK
        if (response == HttpURLConnection.HTTP_OK) {
            // Connection is OK so open a reader
            anInStream = httpConn.getInputStream();
            InputStreamReader in= new InputStreamReader(anInStream);
            BufferedReader bin= new BufferedReader(in);

            // Read in the data from the RSS stream
            String line = new String();
            while (( (line = bin.readLine())) != null) {
                result = result + "\n" + line;
                Log.v(TAG, "index=" + result);


                ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

                Handler parser = new Handler();
                String xml = result.toString(); // getting XML
                Document doc = parser.getDomElement(xml); // getting DOM element

                NodeList nl = doc.getElementsByTagName(KEY_FUEL);
                // looping through all item nodes <item>
                for (int i = 0; i < nl.getLength(); i++) {
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    Element e = (Element) nl.item(i);
                    // adding each child node to HashMap key => value
                    map.put(KEY_HIGHEST, parser.getValue(e, KEY_HIGHEST));
                    map.put(KEY_AVERAGE, parser.getValue(e, KEY_AVERAGE));
                    map.put(KEY_LOWEST, "Rs." + parser.getValue(e, KEY_LOWEST));
                    map.put(KEY_LINK, parser.getValue(e, KEY_LINK));

                    // adding HashList to ArrayList
                    menuItems.add(map);
                    return menuItems;
                }
            }
        }
    } catch (IOException ex) {
        try {
            throw new IOException("Error connecting");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //return menuItems;
}

1 个答案:

答案 0 :(得分:2)

您不会在try {}区块中返回任何内容:

try {
                // Open connection
                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setAllowUserInteraction(false);
                httpConn.setInstanceFollowRedirects(true);
                httpConn.setRequestMethod("GET");
                httpConn.connect();
                response = httpConn.getResponseCode();
                // Check that connection is OK
                if (response == HttpURLConnection.HTTP_OK)
                {
                    // Connection is OK so open a reader
                    anInStream = httpConn.getInputStream();
                    InputStreamReader in= new InputStreamReader(anInStream);
                    BufferedReader bin= new BufferedReader(in);

                    // Read in the data from the RSS stream
                    String line = new String();
                    while (( (line = bin.readLine())) != null)
                    {
                        result = result + "\n" + line;
                        Log.v(TAG, "index=" + result);

                    }
                }
            }

这意味着如果没有引发IOException,则不会返回任何内容。

似乎你的catch (IOException ex)子句中有太多的逻辑,这可能表明你应该重构你的代码(尝试从这个catch子句中获取整个menuItems)。


编辑以下重新评估的代码:

让我们来看看你最后的try-catch块,这也是你方法的结束:

try {
        // Open connection
        HttpURLConnection httpConn = (HttpURLConnection) conn;

        // remainder omitted

    } catch (IOException ex) {
        try {
            throw new IOException("Error connecting");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //return menuItems;

在try块中,您确实返回menuItemsArrayList<HashMap<String, String>>类型),但是你在 a for循环中执行,这将最终导致循环迭代一次将menuItems对象返回给调用者,结束方法调用(因为它可能不是你想要的,你应该从for循环中得到menuItems。)

然后考虑如果在返回menuItems对象之前抛出会发生什么情况会发生什么?(之后不可能发生)?异常将在你的catch子句中捕获,你抛出另一个异常只是为了在打印当前堆栈跟踪之后立即捕获它然后...... 没有。该函数将在不返回任何正是编译器抱怨的内容的情况下结束。

所以你应该找到一种方法来获取menuItems无论如何返回(提示:因为java变量是块范围的,所以从for循环中获取menuItems声明可能是不够的。但是你在最后一个代码行上走得很好!)