java访问Arraylist项
我想从onItemClickListener
中的bookList
访问项目。我想访问特定的书籍并从中获取特定的项目如何做到这一点
代码是:
// Creating volley request obj
final JsonArrayRequest bookrequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj =(JSONObject) response.getJSONObject(i);
Book book = new Book();
book.setTitle(obj.getString("BTitle"));
book.setThumbnailUrl(obj.getString("BCoverpath"));
book.setAuthor(obj.getString("BAuthor"));
book.setEdition(obj.getString("BEdition"));
book.setCategory(obj.getString("Bcategory"));
book.setLanguage(obj.getString("BLanguage"));
book.setDescription(obj.getString("BDescription"));
book.setCover(obj.getString("BCover"));
book.setOwner(obj.getString("UserFN"));
// adding book to books array
bookList.add(book);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
}
);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(bookrequest);
// setting an onItem click listener in order to open the view book activity
listView.setOnItemClickListener(new 安卓.widget.AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
bookname=((TextView)view.findViewById(R.id.title)).getText().toString();
Bauthor=((TextView)view.findViewById(R.id.author)).getText().toString();
Bedition=((TextView)view.findViewById(R.id.edition)).getText().toString();
// intent to take the viewbook activity as its next dextination
Intent i = new Intent(getApplicationContext(), ViewBook.class);
// putting the name of the book with the inten extra package to use it as
// a key to retrieve the book info from the database and display it
i.putExtra("bookname",bookname);
i.putExtra("category",Bcategory);
i.putExtra("Bauthor",Bauthor);
i.putExtra("Bedition",Bedition);
startActivity(i);
}
});
我尝试了许多方法,其中大多数都以越界异常和索引越界结束
# 1 楼答案
在
onItemClick(...)
中,您可以访问被单击的项目的位置和项目的来源,以便使用该信息获取被单击的实际项目我将这些参数重命名为
onItemClick()
,为它们提供了一个更具描述性的名称,并假设Book
中的字段有匹配的getter方法