Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MainFragment extends Fragment
- {
- protected RecyclerView recyclerView;
- protected NewsAdapter adapter;
- protected String API_KEY;
- String sourceTitle, sourceID;
- List<Articles> articleList;
- public MainFragment() {
- }
- @Nullable
- @Override
- public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState)
- {
- ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_main, null);
- sourceTitle = "ABC News";
- sourceID = "abc-news";
- getActivity().setTitle(sourceTitle);
- API_KEY = getString(R.string.API_KEY);
- recyclerView = root.findViewById(R.id.recyclerview);
- RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
- recyclerView.setLayoutManager(mLayoutManager);
- recyclerView.setItemAnimator(new DefaultItemAnimator());
- ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
- Call<News> call = apiService.getArticles(sourceID, API_KEY);
- call.enqueue(new Callback<News>()
- {
- @Override
- public void onResponse(Call<News> call, Response<News> response)
- {
- //This is where the error occurs
- articleList = response.body().getArticles();
- }
- @Override
- public void onFailure(Call<News> call, Throwable t)
- {
- Toast.makeText(getActivity(), "Error in API Call", Toast.LENGTH_SHORT).show();
- }
- });
- if(articleList.isEmpty() || articleList.size() == 0)
- {
- recyclerView.setAdapter(null);
- Toast.makeText(getActivity(), "Error in List", Toast.LENGTH_SHORT).show();
- }
- else
- {
- adapter = new NewsAdapter(articleList, getActivity());
- recyclerView.setAdapter(adapter);
- }
- recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity().getApplicationContext(), recyclerView, new ClickListener() {
- @Override
- public void onClick(View view, int position)
- {
- //onclick code
- }
- @Override
- public void onLongClick(View view, int position) {
- }
- }));
- return root;
- }
- public interface ApiInterface
- {
- @GET("top-headlines")
- Call<List<News>> getArticles(@Query("sources") String source, @Query("apiKey") String apiKey);
- }
- public class ApiClient
- {
- public static final String BASE_URL = "https://newsapi.org/v2/";
- private static Retrofit retrofit = null;
- public static Retrofit getClient()
- {
- if (retrofit==null)
- {
- retrofit = new Retrofit.Builder()
- .baseUrl(BASE_URL)
- .addConverterFactory(GsonConverterFactory.create())
- .build();
- }
- return retrofit;
- }
- }
Add Comment
Please, Sign In to add comment