Список доступа Android к GSON в ArrayList

#java #android #list #arraylist #gson

#java #Android #Список #arraylist #gson

Вопрос:

Я использую GSON для анализа канала JSON, подобного этому здесь:

http://dvz.hj.cx/api/get_recent_posts/?dev=1

Мой класс модели выглядит вот так:

 public class Recent {

@Expose
private String status;
@Expose
private int count;
@Expose
private int count_total;
@Expose
private int pages;  
@Expose
private List<Post> posts = new ArrayList<Post>();

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public Recent withStatus(String status) {
    this.status = status;
    return this;
}

public int getCount() {
    return count;
}

public void setCount(int count) {
    this.count = count;
}

public Recent withCount(int count) {
    this.count = count;
    return this;
}

public int getCount_total() {
    return count_total;
}

public void setCount_total(int count_total) {
    this.count_total = count_total;
}

public Recent withCount_total(int count_total) {
    this.count_total = count_total;
    return this;
}

public int getPages() {
    return pages;
}

public void setPages(int pages) {
    this.pages = pages;
}

public Recent withPages(int pages) {
    this.pages = pages;
    return this;
}  

public List<Post> getPosts() {
    return posts;
}

public void setPosts(List<Post> posts) {
    this.posts = posts;
}

public Recent withPosts(List<Post> posts) {
    this.posts = posts;
    return this;
 }
}
  

Как вы можете видеть, я имею в виду другой класс модели называется Post .
Класс Post модели выглядит следующим образом:

 public class Post {

@Expose
private int id;
@Expose
private String url;
@Expose
private String title;
@Expose
private String date;
@Expose
private List<Category> categories = new ArrayList<Category>();
@Expose
private List<Object> tags = new ArrayList<Object>(); 
@Expose
private Author author;
@Expose
private List<Attachment> attachments = new ArrayList<Attachment>();

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public Post withId(int id) {
    this.id = id;
    return this;
}

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

public Post withUrl(String url) {
    this.url = url;
    return this;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public Post withTitle(String title) {
    this.title = title;
    return this;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public Post withDate(String date) {
    this.date = date;
    return this;
}

public List<Category> getCategories() {
    return categories;
}

public void setCategories(List<Category> categories) {
    this.categories = categories;
}

public Post withCategories(List<Category> categories) {
    this.categories = categories;
    return this;
}

public Author getAuthor() {
    return author;
}

public void setAuthor(Author author) {
    this.author = author;
}

public Post withAuthor(Author author) {
    this.author = author;
    return this;
}

public List<Attachment> getAttachments() {
    return attachments;
}

public void setAttachments(List<Attachment> attachments) {
    this.attachments = attachments;
}

public Post withAttachments(List<Attachment> attachments) {
    this.attachments = attachments;
    return this;
 }
}
  

И снова я ссылаюсь на некоторые другие модели. До сих пор все работало идеально, но теперь мне нужно получить доступ к некоторым из этих геттеров и сеттеров в моем BaseAdapter .
Мой класс адаптера выглядит следующим образом:

 public class NewsList extends BaseAdapter {

private List<Recent> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public ImageLoader imageLoader;

public NewsList(Context context, List<Recent> listData) {
    this.listData = listData;
    layoutInflater = LayoutInflater.from(context);
    mContext = context;

    imageLoader = new ImageLoader(context);
}

@Override
public int getCount() {
    return listData.size();
}

@Override
public Object getItem(int position) {
    return listData.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = layoutInflater.inflate(R.layout.news_row_layout, null);
        holder = new ViewHolder();
        holder.headlineView = (TextView) convertView.findViewById(R.id.title);
        holder.commentView = (TextView) convertView.findViewById(R.id.comment);
        holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
        holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    Recent rec = (Recent) listData.get(position);
    Post post = (Post) rec.getPosts();
    Attachment att = (Attachment) post.getAttachments();
    List<Images> img = att.getImages();
    Thumbnail thumb = (Thumbnail) img.getThumbnail();
    Author author = (Author) post.getAuthor();

          if(post != null){

        /* date and time */
        String date = post.getDate().replace("-",".");
        String zeit = date.substring(11,16);
        String datum = date.substring(0, 11);
        String djahr = datum.substring(0,4);
        String dmonat = datum.substring(5,8);
        String dtag = datum.substring(8,10);

        holder.headlineView.setText(Html.fromHtml(post.getTitle()));
        holder.reportedDateView.setText(Html.fromHtml("Am <b>"   dtag "." dmonat djahr " </b>um <b>" zeit "</b>"));
        holder.commentView.setText(Html.fromHtml("Von: <b>"    author.getName()));


        ImageView image = holder.imageView;
        if(post.attachments.getMime_type().contains("image")){
            imageLoader.DisplayImage(thumb.getUrl(), image);
        }
    }
    return convertView;
}


static class ViewHolder {
    TextView headlineView;
    TextView commentView;
    TextView reportedDateView;
    ImageView imageView;
}
}
  

Как вы видите, я пытаюсь получить List<Post> то, что находится внутри ArrayList<Recent> .

Эта строка работает идеально:
Recent rec = (Recent) listData.get(position);

Но как только он доходит до этой строки, он не работает:
Post post = (Post) rec.getPosts();

Я понятия не имею, как это решить. Пожалуйста, помогите, это очень важно для меня. Если у вас есть лучшее решение, его приветствуют.

Когда дело доходит до этой строки Post post = (Post) rec.getPosts(); , LogCat говорит

 Cannot convert ArrayList to List
  

Комментарии:

1. «не работает» как? возможно, прикрепите трассировку стека.

Ответ №1:

Вы неправильно List<T> T интерпретируете, и эта же проблема присутствует в разных частях вашего кода:

getPosts() возвращает List<Post> не Post так, как getImages() возвращает List<Images> нет Images , вам может понадобиться цикл для итерации по вашему List<Post> , получения single Post , а затем получения его данных like List<Attachment> .

Измените его на следующее:

 Recent rec = (Recent) listData.get(position);
List<Post> posts = rec.getPosts();

for(int i = 0; i < posts.size(); i  ){

  Post post = (Post) posts.get(i);
  if(post != null){
    List<Attachment> atts = post.getAttachments();
    Attachment att = (Attachment) atts.get(0) // You can use loop instead of get(0)
    List<Images> imgs = att.getImages();
    Images img = (Images) imgs.get(0); // You can use loop instead of get(0)
    Thumbnail thumb = (Thumbnail) img.getThumbnail();
    Author author = (Author) post.getAuthor();    
    ...
  }
}
  

Комментарии:

1. что вы имеете в виду под «0» в «atts.get (0)»?

2. get(0) означает получение первого элемента массива, 0 — индекс массива, смотрите Здесь