ArrayList 奇怪的行为

ArrayList strange behavior

我正在做一个从 xml 中获取数据的应用程序,将其放入数据库中,然后在图片的网格视图中显示此数据(图片名称和 url)。 我添加了一个 onitemclicklistener 来获取 url(从 ArrayList),并转移到另一个 activity,这样我就可以将 url 转换为位图并显示在图像视图中。

   //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);

            }
        });

我得到了正确的位置,但问题是我无法从该位置得到相应的url。 它不显示 link,而是显示这个: com.example.partedoxml.Post@42b191d8 问题是我怎么不能从数组列表中获取单个项目的位置?

你的问题是

names.get(position);

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

所以在您的 Post Class 中会有一个由 Name

命名的文件

这样的名字

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

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

在你的 post class 中命名 public

public String name;

然后在你的监听器中

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

或者你在做什么

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

您将通过索引获得一个 post(索引是您在位置变量中指定的)。

您需要在 Post class 中实施 public String toString(){} 方法才能查看 Post 对象中的字段值。