ArrayList奇怪的行为

时间:2015-01-24 16:49:00

标签: java android arraylist

我正在做一个应用程序,它从xml中获取数据,放在数据库上,并在图片的网格视图中显示这些数据(图片和网址的名称)。 我添加了一个onitemclicklistener来获取url(来自ArrayList),并转移到另一个活动,所以我可以将url转换为位图并显示在imageview中。

   //cursor that returns all items from databse to a arraylist
    final Cursor cursor = entry.getAllRows();

//arraylist
            names = new ArrayList<Post>();

            cursor.moveToFirst();
            //adding all database values to the arraylist
            while (cursor.isAfterLast() == false) {
                names.add(new Post(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("link"))));
                cursor.moveToNext();



            }

现在是onitemclicklistsner代码:

@Override
            public void onItemClick(AdapterView<?> parent, View v, int position,
                    long id) {
                Intent i = new Intent(getApplicationContext(), FullImageActivity.class);

                position++;
            Post text = names.get(position);
            Log.i("POSITION", "Exeption:"+position + " " + text);

                //i.putExtra("id", text);
                //startActivity(i);

            }
        });

我得到了正确的位置,但问题是我无法从该位置获得相应的网址。 它没有显示链接,但显示如下: com.example.partedoxml.Post@42b191d8 问题是我如何从arraylist中获得单个项目位置?

2 个答案:

答案 0 :(得分:0)

你的问题是

names.get(position);

您要做的是获取Post对象而不是名称

所以在你的Post Class中会有一个以名称

命名的字段

得到像

这样的名字 post class中的

为名称创建getter和setter 然后在你的听众中写

String name =names.get(position).getName();

在您的帖子课程中,名称公开

public String name;

然后在你的听众中

 String name =names.get(position).name;

或者你在做什么

   Post text = names.get(position);  
   Log.i("POSITION", "Exeption:"+position + " " + text.name);

答案 1 :(得分:0)

您将按索引获取一个帖子(您在位置变量中指定索引)。

您需要在Post类中实现public String toString(){}方法,以查看Post对象中的字段值。