Android Arrays内容无缘无故变化

时间:2011-04-13 20:50:45

标签: android arrays arraylist expandablelistview

我正在尝试在我的活动中创建一个ExpandableListView,显示顶级葡萄酒的类型,以及二级葡萄酒的单瓶装。我正在从我创建的CSV文件中读取我的所有数据,并填充了8个特定的葡萄酒瓶,这些葡萄酒现在属于一个类别。我遇到了一个问题,我正在将我的数据从csv文件读入一个数组,我可以在读取它时将其报告给日志,并且它显示正确。但是一旦我尝试将它放入我的适配器然后进入listview,数组就会填充8个相同的Wine对象,这些对象就是我文件中的最后一个。

以下是我用来读取文件并创建Wine对象数组的代码。

编辑:在while循环完成填充之后,我更改了代码以检查我的数组写入,并得到相同的结果。这是代码的较新版本。

        handler = new Handler()
    {

        @Override
        public void handleMessage(Message msg)
        {
            Log.i(myTag, "Notify Change");
            //By the time I get to here every object in the array is identical
            for(int i = 0; i < chrd.length; i++){
                Log.i(myTag,i + " " + chrd[i].toString());
            }


            super.handleMessage(msg);
        }

    };



    Runnable r = new Runnable(){
        public void run()
        {

            current = new Chardonnay();
            //final int ITEMS = 15;
            int count = 0;

            try {
                File myFile = new File ("/sdcard/chardonnay.txt");
                fis = new FileInputStream(myFile); 
                BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
                String line;
                while ((line = reader.readLine()) != null) {
                     String[] RowData = line.split(",");
                     current.setName(RowData[0]);
                     current.setPlace(RowData[1]);
                     current.setDescription(RowData[2]);
                     current.setYear(Integer.valueOf(RowData[3]));
                     current.setPriceBottle(Integer.valueOf(RowData[4]));
                     current.setPriceGlass(Integer.valueOf(RowData[5]));

                     chrd[count] = current;
                     Log.i(myTag, count + " " + chrd[count]);
                     count++;
                }

                for(int i = 0; i < chrd.length; i++){
                    Log.i(myTag,i + " " + chrd[i]);
                }
            }
            catch (IOException ex) {
                // handle exception
                ex.printStackTrace();
            }


            handler.sendEmptyMessage(1);
            try {
                fis.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }


        }
    };
    Thread thread = new Thread(r);
    thread.start();
}

以下是运行此命令的日志输出:

04-13 15:45:09.390: INFO/One2OneWineMenu(6472): 0 Wine [name=Acre, place=Central Coast, description=Seductive apple pie crust and lemon blossom aromas introduce crisp juicy flavors enriched by a creaminess resulting from surlie barrel aging, year=2008, priceBottle=25, priceGlass=7]
04-13 15:45:09.390: INFO/One2OneWineMenu(6472): 1 Wine [name=Silver Palm, place=North Coast, description=Fermented in stainless steel* this wine's delicate fruit characteristics were preserved without any overbearing flavors that an oak barrel might impart, year=2009, priceBottle=30, priceGlass=10]
04-13 15:45:09.390: INFO/One2OneWineMenu(6472): 2 Wine [name=Franciscan, place=Napa Valley, description=Ripe* generous aromas of apple* pear* and honey with toasty oak. Lively* rich creamy and supple with notes of vanilla on the finish, year=2009, priceBottle=30, priceGlass=-1]
04-13 15:45:09.390: INFO/One2OneWineMenu(6472): 3 Wine [name=Sonoma Cutrer, place=Russian River, description=The 2nd most popular chardonnay in W&S Restaurant Poll* this wine is beautifully balanced with well integrated oak, year=2008, priceBottle=35, priceGlass=11]
04-13 15:45:09.390: INFO/One2OneWineMenu(6472): 4 Wine [name=Matanzas Creek, place=Sonoma, description=92 pts WE* this wine has a silky texture with flavors of lemon cream* peach and pear which feels elegant and creamy on the palate, year=2007, priceBottle=40, priceGlass=-1]
04-13 15:45:09.390: INFO/One2OneWineMenu(6472): 5 Wine [name=Silver by Mer Soleil, place=Santa Lucia Highlands, description=Combines ripe* intense peach* nectarine and tangerine fruit with touches of floral and spice, year=2007, priceBottle=40, priceGlass=-1]
04-13 15:45:09.390: INFO/One2OneWineMenu(6472): 6 Wine [name=Jordan, place=Russian River, description=Voted Best Chardonnay by respected wine journalists who attended 2010 Critics Challenge, year=2008, priceBottle=50, priceGlass=-1]
04-13 15:45:09.390: INFO/One2OneWineMenu(6472): 7 Wine [name=Ramey, place=Santa Lucia Highlands, description=94 pts RP* intense and vibrant* shows full-bodied citrus* melon* and hazelnut flavors that turn subtle and offer hints of fig/tangerine, year=2007, priceBottle=90, priceGlass=-1]
04-13 15:45:09.405: INFO/One2OneWineMenu(6472): Notify Change
04-13 15:45:09.405: INFO/One2OneWineMenu(6472): 0 Wine [name=Ramey, place=Santa Lucia Highlands, description=94 pts RP* intense and vibrant* shows full-bodied citrus* melon* and hazelnut flavors that turn subtle and offer hints of fig/tangerine, year=2007, priceBottle=90, priceGlass=-1]
04-13 15:45:09.405: INFO/One2OneWineMenu(6472): 1 Wine [name=Ramey, place=Santa Lucia Highlands, description=94 pts RP* intense and vibrant* shows full-bodied citrus* melon* and hazelnut flavors that turn subtle and offer hints of fig/tangerine, year=2007, priceBottle=90, priceGlass=-1]
04-13 15:45:09.405: INFO/One2OneWineMenu(6472): 2 Wine [name=Ramey, place=Santa Lucia Highlands, description=94 pts RP* intense and vibrant* shows full-bodied citrus* melon* and hazelnut flavors that turn subtle and offer hints of fig/tangerine, year=2007, priceBottle=90, priceGlass=-1]
04-13 15:45:09.405: INFO/One2OneWineMenu(6472): 3 Wine [name=Ramey, place=Santa Lucia Highlands, description=94 pts RP* intense and vibrant* shows full-bodied citrus* melon* and hazelnut flavors that turn subtle and offer hints of fig/tangerine, year=2007, priceBottle=90, priceGlass=-1]
04-13 15:45:09.405: INFO/One2OneWineMenu(6472): 4 Wine [name=Ramey, place=Santa Lucia Highlands, description=94 pts RP* intense and vibrant* shows full-bodied citrus* melon* and hazelnut flavors that turn subtle and offer hints of fig/tangerine, year=2007, priceBottle=90, priceGlass=-1]
04-13 15:45:09.405: INFO/One2OneWineMenu(6472): 5 Wine [name=Ramey, place=Santa Lucia Highlands, description=94 pts RP* intense and vibrant* shows full-bodied citrus* melon* and hazelnut flavors that turn subtle and offer hints of fig/tangerine, year=2007, priceBottle=90, priceGlass=-1]
04-13 15:45:09.405: INFO/One2OneWineMenu(6472): 6 Wine [name=Ramey, place=Santa Lucia Highlands, description=94 pts RP* intense and vibrant* shows full-bodied citrus* melon* and hazelnut flavors that turn subtle and offer hints of fig/tangerine, year=2007, priceBottle=90, priceGlass=-1]
04-13 15:45:09.405: INFO/One2OneWineMenu(6472): 7 Wine [name=Ramey, place=Santa Lucia Highlands, description=94 pts RP* intense and vibrant* shows full-bodied citrus* melon* and hazelnut flavors that turn subtle and offer hints of fig/tangerine, year=2007, priceBottle=90, priceGlass=-1]

我尝试过相同的逻辑概念但使用ArrayList而不是Wine []并且它有同样的问题。我很难过,我从未见过数组的内容只是因为没有明显的原因而改变了。也许我忽略了一些相对简单的事情,有没有人知道这里会发生什么?

4 个答案:

答案 0 :(得分:1)

您将同一个对象(current)分配给chrd的所有单元格,这就是您最后得到最后一个值的原因。您应该在循环内初始化current以解决此问题。

 while ((line = reader.readLine()) != null) {
                     current = new Chardonnay();
                     String[] RowData = line.split(",");
                     current.setName(RowData[0]);
                     current.setPlace(RowData[1]);
                     current.setDescription(RowData[2]);
                     current.setYear(Integer.valueOf(RowData[3]));
                     current.setPriceBottle(Integer.valueOf(RowData[4]));
                     current.setPriceGlass(Integer.valueOf(RowData[5]));

                     chrd[count] = current;
                     Log.i(myTag, count + " " + chrd[count]);
                     count++;
                }

答案 1 :(得分:1)

问题出在这一行:

current = new Chardonnay();

您只创建一个对象,while的每个循环都会替换此对象中的属性,因此您将以最后一个对象结束。

在while循环中移动对象的创建。

答案 2 :(得分:1)

move“current = new Chardonnay();”到while循环

在您的代码中,数组中的每个项目都指向Chardonnay的同一个实例

答案 3 :(得分:0)

根据我的经验,这就是我必须格式化ExpandableListAdapter组的数据:

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

    ...

    //provided there are entries in the database, iterate through them all. create a hashmap using "company" as the key and 
    //the company as the item and add this hashmap to the array of maps.
    if (cursor.moveToFirst()) {

        do {
            HashMap<String, String> m = new HashMap<String, String>();
            m.put("company", cursor.getString(cursor.getColumnIndex(CompanyAndProductDatabaseAdapter.company_column))); 
            alist.add(m);
        } while (cursor.moveToNext());
    }