我正在尝试使用特定newspaper_id查询新闻节点中的最后一项。 基本上,我希望始终使用新闻的ID作为查询来获取特定报纸的最新消息。查询是在FirebaseRecyclerAdpter populateViewHolder((中完成的,我得到了
java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1 at java.util.ArrayList.get(ArrayList.java:310( at com.simpumind.e_tech_news.adapter.VendorNewAdapter$1.onDataChange(VendorNewAdapter.java:100(
{
"news": {
"-HDRKDDGKSD56": {
"caption" : "Hail Mary",
"content" : "some contents"
"newspaper_id" : "-Kg9UvxyiuI4G3r6fCgU",
thumbnail: "some base64 encoded image"
},
"newspaper": {
"-Kg9UvxyiuI4G3r6fCgU" : {
"content_provider" : 1,
"cost" : "200",
"logo" : "some base64 encoded image"
"user": "The user"
}
}
这就是我尝试过的
@Override
protected void populateViewHolder(final NewsPaperHolder viewHolder, NewsPaper model, int position) {
viewHolder.vendorName.setText(model.getPaper_name());
mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("news");
String oneChildRef = getRef(position).getKey();
mDatabaseRef.orderByChild("newspaper_id")
.equalTo(oneChildRef)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<News> newsList = new ArrayList();
for (DataSnapshot d : dataSnapshot.getChildren()){
News n = d.getValue(News.class);
newsList.add(n);
}
newsList.toString();
News news = newsList.get(newsList.size() - 1);
updateUI(viewHolder, news);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Picasso.with(context).load(model.getLogo()).into(viewHolder.vendorIcon);
}
public void updateUI(NewsPaperHolder holder, News news){
holder.firstNewsTitle.setText(news.getCaption());
Picasso.with(context).load(news.getThumbnail()).into(holder.firstNewsImage);
}
新闻
public class News {
public String caption;
public String content;
public String newspaper_id;
public String thumbnail;
public String user;
public News(){
}
public News(String caption, String content, String newspaper_id, String thumbnail, String user) {
this.caption = caption;
this.content = content;
this.newspaper_id = newspaper_id;
this.thumbnail = thumbnail;
this.user = user;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getNewspaper_id() {
return newspaper_id;
}
public void setNewspaper_id(String newspaper_id) {
this.newspaper_id = newspaper_id;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
}
可能是在数据库不包含子数据库时遇到该错误。尝试通过以下方式逃避它:
public void onDataChange(DataSnapshot dataSnapshot) {
...
if (newsList.size() > 0) {
News news = newsList.get(newsList.size() - 1);
updateUI(viewHolder, news);
}
}
希望这有帮助