package Classes.api; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import org.json.JSONArray; import org.json.JSONObject; import Classes.Event; import Interfaces.Callback; import model.NewsListModel; import model.NewsModel; public class fetchArticles implements Callback{ private NewsListModel context; private String nextQuery; public fetchArticles(NewsListModel context, String nextQuery){ this.context = context; this.nextQuery = nextQuery; } @Override public void onSuccess(JSONObject response){ /* (1) Création des NewsModel depuis le json ---------------------------------------------------------*/ /* (1) Init. news list */ ArrayList newsArr = new ArrayList(); /* (2) Get article list */ JSONArray article_list = response.getJSONArray("articles"); /* (3) For each article -> create corresponding NewsModel */ for( int i = 0, il = article_list.length() ; i < il ; i++ ){ // {3.1} Get local copy of the JSON // JSONObject news_i = (JSONObject) article_list.get(i); // {3.2} Create new NewsModel // NewsModel news = new NewsModel(); // {3.3} Set attributes // news.setAuthor( news_i.getString("author") ) .setDescription( news_i.getString("description") ) .setTitle( news_i.getString("title") ) .setNewsURL( news_i.getString("url") ) .setImageURL( news_i.getString("urlToImage") ) .setSource( news_i.getJSONObject("source").getString("name") ) .addTag( this.context.getCategory() ); // {3.4} Add the date (can throw Ex) // try { news.setDate(news_i.getString("publishedAt")); } catch( ParseException e ){ news.setDate(new Date()); } // {3.5} Add to the set // newsArr.add(news); } /* (4) Apply to Context */ this.context.setNews( newsArr ); this.context.setQuery( this.nextQuery ); /* (5) Remove observers */ this.context.removeObserver("newsApiCall"); this.context.notifyObservers(new Event("NewsModel","NewsQuerySuccess")); } @Override public void onError(String errDesc) { System.out.println("Error: "+errDesc); this.context.removeObserver("newsApiCall"); this.context.notifyObservers(new Event("NewsModel","NewsQueryFailed")); } }