skip to Main Content
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RequestQueue requestQueue;
        requestQueue = Volley.newRequestQueue(this);
        List<news_Objects> newsList = new ArrayList<>();
 
        //url for News API 

        String url="https://newsapi.org/v2/everything?q=apple&from=2021-08-31&to=2021-08-31&sortBy=popularity&apiKey=ca3d6c89eff24db2a8ef78868f0af555";

//making json object request
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONArray jsonArr = response.getJSONArray("articles");

                    for (int i = 0; i < jsonArr.length(); i++) {
                        JSONObject newsDetail = jsonArr.getJSONObject(i);

//class name news_Objects created 

                        news_Objects news = new news_Objects();

                        String imtUrl = newsDetail.getString("urlToImage");
                        String title = newsDetail.getString("title");
                        String detail = newsDetail.getString("description");
                        String newsUrl = newsDetail.getString("url");
                        String content = newsDetail.getString("content");

                        news.setNewsImageUrl(imtUrl);
                        news.setNewsTitle(title);
                        news.setNewsDetail(detail);
                        news.setNewsUrl(newsUrl);
                        news.setContent(content);
                        newsList.add(news);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("fine", "Something Wrong"+error);
                Toast.makeText(MainActivity.this, "Something Wrong "+error, Toast.LENGTH_SHORT).show();
                error.printStackTrace();
            }
        });
        requestQueue.add(request);

    }
}

2

Answers


  1. Your API Key is Invalid please check your API key. Getting this response:
    {"status":"error","code":"apiKeyInvalid","message":"Your API key is invalid or incorrect. Check your key, or go to https://newsapi.org to create a free API key."}

    Login or Signup to reply.
  2. Maybe Your API key is not live, please check your API key status than again hit the api.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search