No output on screen after fetching data from JSON and populating with ListView
I am trying to make project using guardian API, which fetch data from JSON and it display all the news on screen in ListView, I have tried all possible methods and also Logs with information to verify the flow of code and all working properly, no errors and crashes, the only issue is that it dont display data on screen, screen is blank please help me
Here is output:
Blank Screen
Here is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hannan.newsfeed">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is MainActivity.java
package com.example.hannan.newsfeed;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String GAURDIAN_URL = "https://content.guardianapis.com/search?api-key=d7262a1a-2583-4342-9b57-85ed0f621416";
private NewsAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.list);
mAdapter = new NewsAdapter(this, new ArrayList<NewsModel>());
listView.setAdapter(mAdapter);
NewsAsyncTask task = new NewsAsyncTask();
task.execute(GAURDIAN_URL);
private class NewsAsyncTask extends AsyncTask<String, Void, List<NewsModel>>
@Override
protected List<NewsModel> doInBackground(String... urls) urls[0] == null)
Log.i(LOG_TAG, "TEST: No urls available");
return null;
List<NewsModel> result = QueryUtils.fetch_data(urls[0]);
Log.i(LOG_TAG, "TEST: In fetch_data() method of QueryUtils class");
return result;
@Override
protected void onPostExecute(List<NewsModel> newsModels)
Log.i(LOG_TAG, "TEST: Completed doInBackground() Method");
mAdapter.clear();
Log.i(LOG_TAG, "TEST: Adapter Cleared");
if (newsModels != null && !newsModels.isEmpty())
Log.i(LOG_TAG, "TEST:Data added to Adapter");
mAdapter.addAll();
else
Log.i(LOG_TAG, "TEST: No data in Model");
Here is NewsAdapter.java
package com.example.hannan.newsfeed;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class NewsAdapter extends ArrayAdapter
private static final String LOG_TAG = MainActivity.class.getSimpleName();
public NewsAdapter(@NonNull Context context, ArrayList<NewsModel> newslist)
super(context, 0, newslist);
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent)
if (convertView == null)
LayoutInflater.from(getContext()).inflate(R.layout.list_news, parent, false);
NewsModel currentNews = (NewsModel) getItem(position);
TextView news_title = convertView.findViewById(R.id.news_title);
TextView news_section = convertView.findViewById(R.id.news_section);
TextView news_date = convertView.findViewById(R.id.news_date);
news_title.setText(currentNews.getmNewsTitle());
news_section.setText(currentNews.getmNewsSection());
news_date.setText(currentNews.getmNewsDate());
return convertView;
Here is NewsModel.java
package com.example.hannan.newsfeed;
public class NewsModel
private String mNewsTitle;
private String mNewsSection;
private String mNewsDate;
private String mNewsUrl;
NewsModel(String news_title,String news_section, String news_date, String news_url)
mNewsTitle = news_title;
mNewsSection = news_section;
mNewsDate = news_date;
mNewsUrl = news_url;
public String getmNewsTitle()
return mNewsTitle;
public String getmNewsSection()
return mNewsSection;
public String getmNewsDate()
return mNewsDate;
public String getmNewsUrl()
return mNewsUrl;
Here is QueryUtils.java
package com.example.hannan.newsfeed;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class QueryUtils
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils()
public static ArrayList<NewsModel> fetch_data(String requestedUrl)
URL url = createURL(requestedUrl);
Log.i(LOG_TAG, "TEST: URL Requested");
String jsonResponse = null;
try
jsonResponse = makeHttpRequest(url);
Log.i(LOG_TAG, "TEST: JSON Response created");
catch (IOException e)
e.printStackTrace();
ArrayList<NewsModel> listnews = extractResponseFromJson(jsonResponse);
return listnews;
private static URL createURL(String stringUrl)
URL url = null;
try
url = new URL(stringUrl);
Log.i(LOG_TAG, "TEST: URL Created " + url);
catch (MalformedURLException e)
Log.e(LOG_TAG, "TEST:Problem Building URL..", e);
return url;
private static String makeHttpRequest(URL url) throws IOException
String jsonResponse = "";
if (url == null)
return jsonResponse;
HttpsURLConnection urlConnection = null;
InputStream is = null;
try
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200)
is = urlConnection.getInputStream();
jsonResponse = readFromStream(is);
Log.i(LOG_TAG, "TEST: Connected with HTTP");
else
Log.e(LOG_TAG, "TEST:Error Response Code:" + urlConnection.getResponseCode());
catch (IOException e)
Log.e(LOG_TAG, "TEST:Problem retrieving Data", e);
finally
if (urlConnection != null)
urlConnection.disconnect();
if (is != null)
is.close();
return jsonResponse;
private static String readFromStream(InputStream inputStream) throws IOException
StringBuilder stringBuilder = new StringBuilder();
Log.i(LOG_TAG, "TEST: String builder created");
if (inputStream != null)
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null)
stringBuilder.append(line);
line = reader.readLine();
Log.i(LOG_TAG, "TEST: returning String builder");
return stringBuilder.toString();
private static ArrayList<NewsModel> extractResponseFromJson(String newsJson)
Log.i(LOG_TAG, "TEST: In extractResponseFromJson() method..");
if (TextUtils.isEmpty(newsJson))
Log.i(LOG_TAG, "TEST: newsJson is empty");
return null;
ArrayList<NewsModel> newslist = new ArrayList<>();
Log.i(LOG_TAG, "TEST: ArrayList created");
try
JSONObject baseObject = new JSONObject(newsJson);
Log.i(LOG_TAG, "TEST: JSON object created");
JSONObject responseArray = baseObject.getJSONObject("response");
Log.i(LOG_TAG, "JSON object fetched" + responseArray);
JSONArray resultArray = responseArray.getJSONArray("results");
for (int i = 0; i < resultArray.length(); i++)
Log.i(LOG_TAG, "TEST: In for loop");
JSONObject currentNews = resultArray.getJSONObject(i);
String title = currentNews.getString("webTitle");
String section_name = currentNews.getString("sectionName");
String published_date = currentNews.getString("webPublicationDate");
String url = currentNews.getString("webUrl");
NewsModel news = new NewsModel(title, section_name, published_date, url);
newslist.add(news);
Log.i(LOG_TAG, "TEST: JSON data Added to Model");
catch (JSONException e)
e.printStackTrace();
Log.e(LOG_TAG, "Error fetching Data from JSON");
return newslist;
Here is main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Here is list_news.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="@+id/news_title"
android:layout_width="match_parent"
android:padding="8dp"
android:textSize="20sp"
android:layout_height="wrap_content"
tools:text="News Title"/>
<TextView
android:id="@+id/news_section"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/news_title"
tools:text="News Section"
android:textSize="14sp"
android:layout_alignParentLeft="true"
android:padding="8dp"/>
<TextView
android:id="@+id/news_date"
android:textSize="12sp"
android:padding="8dp"
tools:text="News Date"
android:layout_below="@id/news_title"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
java android
add a comment |
I am trying to make project using guardian API, which fetch data from JSON and it display all the news on screen in ListView, I have tried all possible methods and also Logs with information to verify the flow of code and all working properly, no errors and crashes, the only issue is that it dont display data on screen, screen is blank please help me
Here is output:
Blank Screen
Here is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hannan.newsfeed">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is MainActivity.java
package com.example.hannan.newsfeed;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String GAURDIAN_URL = "https://content.guardianapis.com/search?api-key=d7262a1a-2583-4342-9b57-85ed0f621416";
private NewsAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.list);
mAdapter = new NewsAdapter(this, new ArrayList<NewsModel>());
listView.setAdapter(mAdapter);
NewsAsyncTask task = new NewsAsyncTask();
task.execute(GAURDIAN_URL);
private class NewsAsyncTask extends AsyncTask<String, Void, List<NewsModel>>
@Override
protected List<NewsModel> doInBackground(String... urls) urls[0] == null)
Log.i(LOG_TAG, "TEST: No urls available");
return null;
List<NewsModel> result = QueryUtils.fetch_data(urls[0]);
Log.i(LOG_TAG, "TEST: In fetch_data() method of QueryUtils class");
return result;
@Override
protected void onPostExecute(List<NewsModel> newsModels)
Log.i(LOG_TAG, "TEST: Completed doInBackground() Method");
mAdapter.clear();
Log.i(LOG_TAG, "TEST: Adapter Cleared");
if (newsModels != null && !newsModels.isEmpty())
Log.i(LOG_TAG, "TEST:Data added to Adapter");
mAdapter.addAll();
else
Log.i(LOG_TAG, "TEST: No data in Model");
Here is NewsAdapter.java
package com.example.hannan.newsfeed;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class NewsAdapter extends ArrayAdapter
private static final String LOG_TAG = MainActivity.class.getSimpleName();
public NewsAdapter(@NonNull Context context, ArrayList<NewsModel> newslist)
super(context, 0, newslist);
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent)
if (convertView == null)
LayoutInflater.from(getContext()).inflate(R.layout.list_news, parent, false);
NewsModel currentNews = (NewsModel) getItem(position);
TextView news_title = convertView.findViewById(R.id.news_title);
TextView news_section = convertView.findViewById(R.id.news_section);
TextView news_date = convertView.findViewById(R.id.news_date);
news_title.setText(currentNews.getmNewsTitle());
news_section.setText(currentNews.getmNewsSection());
news_date.setText(currentNews.getmNewsDate());
return convertView;
Here is NewsModel.java
package com.example.hannan.newsfeed;
public class NewsModel
private String mNewsTitle;
private String mNewsSection;
private String mNewsDate;
private String mNewsUrl;
NewsModel(String news_title,String news_section, String news_date, String news_url)
mNewsTitle = news_title;
mNewsSection = news_section;
mNewsDate = news_date;
mNewsUrl = news_url;
public String getmNewsTitle()
return mNewsTitle;
public String getmNewsSection()
return mNewsSection;
public String getmNewsDate()
return mNewsDate;
public String getmNewsUrl()
return mNewsUrl;
Here is QueryUtils.java
package com.example.hannan.newsfeed;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class QueryUtils
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils()
public static ArrayList<NewsModel> fetch_data(String requestedUrl)
URL url = createURL(requestedUrl);
Log.i(LOG_TAG, "TEST: URL Requested");
String jsonResponse = null;
try
jsonResponse = makeHttpRequest(url);
Log.i(LOG_TAG, "TEST: JSON Response created");
catch (IOException e)
e.printStackTrace();
ArrayList<NewsModel> listnews = extractResponseFromJson(jsonResponse);
return listnews;
private static URL createURL(String stringUrl)
URL url = null;
try
url = new URL(stringUrl);
Log.i(LOG_TAG, "TEST: URL Created " + url);
catch (MalformedURLException e)
Log.e(LOG_TAG, "TEST:Problem Building URL..", e);
return url;
private static String makeHttpRequest(URL url) throws IOException
String jsonResponse = "";
if (url == null)
return jsonResponse;
HttpsURLConnection urlConnection = null;
InputStream is = null;
try
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200)
is = urlConnection.getInputStream();
jsonResponse = readFromStream(is);
Log.i(LOG_TAG, "TEST: Connected with HTTP");
else
Log.e(LOG_TAG, "TEST:Error Response Code:" + urlConnection.getResponseCode());
catch (IOException e)
Log.e(LOG_TAG, "TEST:Problem retrieving Data", e);
finally
if (urlConnection != null)
urlConnection.disconnect();
if (is != null)
is.close();
return jsonResponse;
private static String readFromStream(InputStream inputStream) throws IOException
StringBuilder stringBuilder = new StringBuilder();
Log.i(LOG_TAG, "TEST: String builder created");
if (inputStream != null)
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null)
stringBuilder.append(line);
line = reader.readLine();
Log.i(LOG_TAG, "TEST: returning String builder");
return stringBuilder.toString();
private static ArrayList<NewsModel> extractResponseFromJson(String newsJson)
Log.i(LOG_TAG, "TEST: In extractResponseFromJson() method..");
if (TextUtils.isEmpty(newsJson))
Log.i(LOG_TAG, "TEST: newsJson is empty");
return null;
ArrayList<NewsModel> newslist = new ArrayList<>();
Log.i(LOG_TAG, "TEST: ArrayList created");
try
JSONObject baseObject = new JSONObject(newsJson);
Log.i(LOG_TAG, "TEST: JSON object created");
JSONObject responseArray = baseObject.getJSONObject("response");
Log.i(LOG_TAG, "JSON object fetched" + responseArray);
JSONArray resultArray = responseArray.getJSONArray("results");
for (int i = 0; i < resultArray.length(); i++)
Log.i(LOG_TAG, "TEST: In for loop");
JSONObject currentNews = resultArray.getJSONObject(i);
String title = currentNews.getString("webTitle");
String section_name = currentNews.getString("sectionName");
String published_date = currentNews.getString("webPublicationDate");
String url = currentNews.getString("webUrl");
NewsModel news = new NewsModel(title, section_name, published_date, url);
newslist.add(news);
Log.i(LOG_TAG, "TEST: JSON data Added to Model");
catch (JSONException e)
e.printStackTrace();
Log.e(LOG_TAG, "Error fetching Data from JSON");
return newslist;
Here is main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Here is list_news.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="@+id/news_title"
android:layout_width="match_parent"
android:padding="8dp"
android:textSize="20sp"
android:layout_height="wrap_content"
tools:text="News Title"/>
<TextView
android:id="@+id/news_section"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/news_title"
tools:text="News Section"
android:textSize="14sp"
android:layout_alignParentLeft="true"
android:padding="8dp"/>
<TextView
android:id="@+id/news_date"
android:textSize="12sp"
android:padding="8dp"
tools:text="News Date"
android:layout_below="@id/news_title"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
java android
Did you try debugging? Check what are you passing adapter.to your ListView adapter.
– Kunu
Nov 12 at 13:57
Shouldn't you be passing the list you fetched into your adapter. In your NewsAsyncTask-> onPostExecute. mAdapter.addAll() has no argument.
– Rishabh876
Nov 12 at 14:07
I tried but it not adding to adapter
– Hannan Shaikh
Nov 12 at 14:11
add a comment |
I am trying to make project using guardian API, which fetch data from JSON and it display all the news on screen in ListView, I have tried all possible methods and also Logs with information to verify the flow of code and all working properly, no errors and crashes, the only issue is that it dont display data on screen, screen is blank please help me
Here is output:
Blank Screen
Here is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hannan.newsfeed">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is MainActivity.java
package com.example.hannan.newsfeed;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String GAURDIAN_URL = "https://content.guardianapis.com/search?api-key=d7262a1a-2583-4342-9b57-85ed0f621416";
private NewsAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.list);
mAdapter = new NewsAdapter(this, new ArrayList<NewsModel>());
listView.setAdapter(mAdapter);
NewsAsyncTask task = new NewsAsyncTask();
task.execute(GAURDIAN_URL);
private class NewsAsyncTask extends AsyncTask<String, Void, List<NewsModel>>
@Override
protected List<NewsModel> doInBackground(String... urls) urls[0] == null)
Log.i(LOG_TAG, "TEST: No urls available");
return null;
List<NewsModel> result = QueryUtils.fetch_data(urls[0]);
Log.i(LOG_TAG, "TEST: In fetch_data() method of QueryUtils class");
return result;
@Override
protected void onPostExecute(List<NewsModel> newsModels)
Log.i(LOG_TAG, "TEST: Completed doInBackground() Method");
mAdapter.clear();
Log.i(LOG_TAG, "TEST: Adapter Cleared");
if (newsModels != null && !newsModels.isEmpty())
Log.i(LOG_TAG, "TEST:Data added to Adapter");
mAdapter.addAll();
else
Log.i(LOG_TAG, "TEST: No data in Model");
Here is NewsAdapter.java
package com.example.hannan.newsfeed;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class NewsAdapter extends ArrayAdapter
private static final String LOG_TAG = MainActivity.class.getSimpleName();
public NewsAdapter(@NonNull Context context, ArrayList<NewsModel> newslist)
super(context, 0, newslist);
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent)
if (convertView == null)
LayoutInflater.from(getContext()).inflate(R.layout.list_news, parent, false);
NewsModel currentNews = (NewsModel) getItem(position);
TextView news_title = convertView.findViewById(R.id.news_title);
TextView news_section = convertView.findViewById(R.id.news_section);
TextView news_date = convertView.findViewById(R.id.news_date);
news_title.setText(currentNews.getmNewsTitle());
news_section.setText(currentNews.getmNewsSection());
news_date.setText(currentNews.getmNewsDate());
return convertView;
Here is NewsModel.java
package com.example.hannan.newsfeed;
public class NewsModel
private String mNewsTitle;
private String mNewsSection;
private String mNewsDate;
private String mNewsUrl;
NewsModel(String news_title,String news_section, String news_date, String news_url)
mNewsTitle = news_title;
mNewsSection = news_section;
mNewsDate = news_date;
mNewsUrl = news_url;
public String getmNewsTitle()
return mNewsTitle;
public String getmNewsSection()
return mNewsSection;
public String getmNewsDate()
return mNewsDate;
public String getmNewsUrl()
return mNewsUrl;
Here is QueryUtils.java
package com.example.hannan.newsfeed;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class QueryUtils
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils()
public static ArrayList<NewsModel> fetch_data(String requestedUrl)
URL url = createURL(requestedUrl);
Log.i(LOG_TAG, "TEST: URL Requested");
String jsonResponse = null;
try
jsonResponse = makeHttpRequest(url);
Log.i(LOG_TAG, "TEST: JSON Response created");
catch (IOException e)
e.printStackTrace();
ArrayList<NewsModel> listnews = extractResponseFromJson(jsonResponse);
return listnews;
private static URL createURL(String stringUrl)
URL url = null;
try
url = new URL(stringUrl);
Log.i(LOG_TAG, "TEST: URL Created " + url);
catch (MalformedURLException e)
Log.e(LOG_TAG, "TEST:Problem Building URL..", e);
return url;
private static String makeHttpRequest(URL url) throws IOException
String jsonResponse = "";
if (url == null)
return jsonResponse;
HttpsURLConnection urlConnection = null;
InputStream is = null;
try
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200)
is = urlConnection.getInputStream();
jsonResponse = readFromStream(is);
Log.i(LOG_TAG, "TEST: Connected with HTTP");
else
Log.e(LOG_TAG, "TEST:Error Response Code:" + urlConnection.getResponseCode());
catch (IOException e)
Log.e(LOG_TAG, "TEST:Problem retrieving Data", e);
finally
if (urlConnection != null)
urlConnection.disconnect();
if (is != null)
is.close();
return jsonResponse;
private static String readFromStream(InputStream inputStream) throws IOException
StringBuilder stringBuilder = new StringBuilder();
Log.i(LOG_TAG, "TEST: String builder created");
if (inputStream != null)
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null)
stringBuilder.append(line);
line = reader.readLine();
Log.i(LOG_TAG, "TEST: returning String builder");
return stringBuilder.toString();
private static ArrayList<NewsModel> extractResponseFromJson(String newsJson)
Log.i(LOG_TAG, "TEST: In extractResponseFromJson() method..");
if (TextUtils.isEmpty(newsJson))
Log.i(LOG_TAG, "TEST: newsJson is empty");
return null;
ArrayList<NewsModel> newslist = new ArrayList<>();
Log.i(LOG_TAG, "TEST: ArrayList created");
try
JSONObject baseObject = new JSONObject(newsJson);
Log.i(LOG_TAG, "TEST: JSON object created");
JSONObject responseArray = baseObject.getJSONObject("response");
Log.i(LOG_TAG, "JSON object fetched" + responseArray);
JSONArray resultArray = responseArray.getJSONArray("results");
for (int i = 0; i < resultArray.length(); i++)
Log.i(LOG_TAG, "TEST: In for loop");
JSONObject currentNews = resultArray.getJSONObject(i);
String title = currentNews.getString("webTitle");
String section_name = currentNews.getString("sectionName");
String published_date = currentNews.getString("webPublicationDate");
String url = currentNews.getString("webUrl");
NewsModel news = new NewsModel(title, section_name, published_date, url);
newslist.add(news);
Log.i(LOG_TAG, "TEST: JSON data Added to Model");
catch (JSONException e)
e.printStackTrace();
Log.e(LOG_TAG, "Error fetching Data from JSON");
return newslist;
Here is main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Here is list_news.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="@+id/news_title"
android:layout_width="match_parent"
android:padding="8dp"
android:textSize="20sp"
android:layout_height="wrap_content"
tools:text="News Title"/>
<TextView
android:id="@+id/news_section"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/news_title"
tools:text="News Section"
android:textSize="14sp"
android:layout_alignParentLeft="true"
android:padding="8dp"/>
<TextView
android:id="@+id/news_date"
android:textSize="12sp"
android:padding="8dp"
tools:text="News Date"
android:layout_below="@id/news_title"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
java android
I am trying to make project using guardian API, which fetch data from JSON and it display all the news on screen in ListView, I have tried all possible methods and also Logs with information to verify the flow of code and all working properly, no errors and crashes, the only issue is that it dont display data on screen, screen is blank please help me
Here is output:
Blank Screen
Here is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hannan.newsfeed">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is MainActivity.java
package com.example.hannan.newsfeed;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String GAURDIAN_URL = "https://content.guardianapis.com/search?api-key=d7262a1a-2583-4342-9b57-85ed0f621416";
private NewsAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.list);
mAdapter = new NewsAdapter(this, new ArrayList<NewsModel>());
listView.setAdapter(mAdapter);
NewsAsyncTask task = new NewsAsyncTask();
task.execute(GAURDIAN_URL);
private class NewsAsyncTask extends AsyncTask<String, Void, List<NewsModel>>
@Override
protected List<NewsModel> doInBackground(String... urls) urls[0] == null)
Log.i(LOG_TAG, "TEST: No urls available");
return null;
List<NewsModel> result = QueryUtils.fetch_data(urls[0]);
Log.i(LOG_TAG, "TEST: In fetch_data() method of QueryUtils class");
return result;
@Override
protected void onPostExecute(List<NewsModel> newsModels)
Log.i(LOG_TAG, "TEST: Completed doInBackground() Method");
mAdapter.clear();
Log.i(LOG_TAG, "TEST: Adapter Cleared");
if (newsModels != null && !newsModels.isEmpty())
Log.i(LOG_TAG, "TEST:Data added to Adapter");
mAdapter.addAll();
else
Log.i(LOG_TAG, "TEST: No data in Model");
Here is NewsAdapter.java
package com.example.hannan.newsfeed;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class NewsAdapter extends ArrayAdapter
private static final String LOG_TAG = MainActivity.class.getSimpleName();
public NewsAdapter(@NonNull Context context, ArrayList<NewsModel> newslist)
super(context, 0, newslist);
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent)
if (convertView == null)
LayoutInflater.from(getContext()).inflate(R.layout.list_news, parent, false);
NewsModel currentNews = (NewsModel) getItem(position);
TextView news_title = convertView.findViewById(R.id.news_title);
TextView news_section = convertView.findViewById(R.id.news_section);
TextView news_date = convertView.findViewById(R.id.news_date);
news_title.setText(currentNews.getmNewsTitle());
news_section.setText(currentNews.getmNewsSection());
news_date.setText(currentNews.getmNewsDate());
return convertView;
Here is NewsModel.java
package com.example.hannan.newsfeed;
public class NewsModel
private String mNewsTitle;
private String mNewsSection;
private String mNewsDate;
private String mNewsUrl;
NewsModel(String news_title,String news_section, String news_date, String news_url)
mNewsTitle = news_title;
mNewsSection = news_section;
mNewsDate = news_date;
mNewsUrl = news_url;
public String getmNewsTitle()
return mNewsTitle;
public String getmNewsSection()
return mNewsSection;
public String getmNewsDate()
return mNewsDate;
public String getmNewsUrl()
return mNewsUrl;
Here is QueryUtils.java
package com.example.hannan.newsfeed;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class QueryUtils
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils()
public static ArrayList<NewsModel> fetch_data(String requestedUrl)
URL url = createURL(requestedUrl);
Log.i(LOG_TAG, "TEST: URL Requested");
String jsonResponse = null;
try
jsonResponse = makeHttpRequest(url);
Log.i(LOG_TAG, "TEST: JSON Response created");
catch (IOException e)
e.printStackTrace();
ArrayList<NewsModel> listnews = extractResponseFromJson(jsonResponse);
return listnews;
private static URL createURL(String stringUrl)
URL url = null;
try
url = new URL(stringUrl);
Log.i(LOG_TAG, "TEST: URL Created " + url);
catch (MalformedURLException e)
Log.e(LOG_TAG, "TEST:Problem Building URL..", e);
return url;
private static String makeHttpRequest(URL url) throws IOException
String jsonResponse = "";
if (url == null)
return jsonResponse;
HttpsURLConnection urlConnection = null;
InputStream is = null;
try
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200)
is = urlConnection.getInputStream();
jsonResponse = readFromStream(is);
Log.i(LOG_TAG, "TEST: Connected with HTTP");
else
Log.e(LOG_TAG, "TEST:Error Response Code:" + urlConnection.getResponseCode());
catch (IOException e)
Log.e(LOG_TAG, "TEST:Problem retrieving Data", e);
finally
if (urlConnection != null)
urlConnection.disconnect();
if (is != null)
is.close();
return jsonResponse;
private static String readFromStream(InputStream inputStream) throws IOException
StringBuilder stringBuilder = new StringBuilder();
Log.i(LOG_TAG, "TEST: String builder created");
if (inputStream != null)
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null)
stringBuilder.append(line);
line = reader.readLine();
Log.i(LOG_TAG, "TEST: returning String builder");
return stringBuilder.toString();
private static ArrayList<NewsModel> extractResponseFromJson(String newsJson)
Log.i(LOG_TAG, "TEST: In extractResponseFromJson() method..");
if (TextUtils.isEmpty(newsJson))
Log.i(LOG_TAG, "TEST: newsJson is empty");
return null;
ArrayList<NewsModel> newslist = new ArrayList<>();
Log.i(LOG_TAG, "TEST: ArrayList created");
try
JSONObject baseObject = new JSONObject(newsJson);
Log.i(LOG_TAG, "TEST: JSON object created");
JSONObject responseArray = baseObject.getJSONObject("response");
Log.i(LOG_TAG, "JSON object fetched" + responseArray);
JSONArray resultArray = responseArray.getJSONArray("results");
for (int i = 0; i < resultArray.length(); i++)
Log.i(LOG_TAG, "TEST: In for loop");
JSONObject currentNews = resultArray.getJSONObject(i);
String title = currentNews.getString("webTitle");
String section_name = currentNews.getString("sectionName");
String published_date = currentNews.getString("webPublicationDate");
String url = currentNews.getString("webUrl");
NewsModel news = new NewsModel(title, section_name, published_date, url);
newslist.add(news);
Log.i(LOG_TAG, "TEST: JSON data Added to Model");
catch (JSONException e)
e.printStackTrace();
Log.e(LOG_TAG, "Error fetching Data from JSON");
return newslist;
Here is main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Here is list_news.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="@+id/news_title"
android:layout_width="match_parent"
android:padding="8dp"
android:textSize="20sp"
android:layout_height="wrap_content"
tools:text="News Title"/>
<TextView
android:id="@+id/news_section"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/news_title"
tools:text="News Section"
android:textSize="14sp"
android:layout_alignParentLeft="true"
android:padding="8dp"/>
<TextView
android:id="@+id/news_date"
android:textSize="12sp"
android:padding="8dp"
tools:text="News Date"
android:layout_below="@id/news_title"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
java android
java android
edited Nov 12 at 15:08
Fantômas
32.3k156288
32.3k156288
asked Nov 12 at 13:55
Hannan Shaikh
11
11
Did you try debugging? Check what are you passing adapter.to your ListView adapter.
– Kunu
Nov 12 at 13:57
Shouldn't you be passing the list you fetched into your adapter. In your NewsAsyncTask-> onPostExecute. mAdapter.addAll() has no argument.
– Rishabh876
Nov 12 at 14:07
I tried but it not adding to adapter
– Hannan Shaikh
Nov 12 at 14:11
add a comment |
Did you try debugging? Check what are you passing adapter.to your ListView adapter.
– Kunu
Nov 12 at 13:57
Shouldn't you be passing the list you fetched into your adapter. In your NewsAsyncTask-> onPostExecute. mAdapter.addAll() has no argument.
– Rishabh876
Nov 12 at 14:07
I tried but it not adding to adapter
– Hannan Shaikh
Nov 12 at 14:11
Did you try debugging? Check what are you passing adapter.to your ListView adapter.
– Kunu
Nov 12 at 13:57
Did you try debugging? Check what are you passing adapter.to your ListView adapter.
– Kunu
Nov 12 at 13:57
Shouldn't you be passing the list you fetched into your adapter. In your NewsAsyncTask-> onPostExecute. mAdapter.addAll() has no argument.
– Rishabh876
Nov 12 at 14:07
Shouldn't you be passing the list you fetched into your adapter. In your NewsAsyncTask-> onPostExecute. mAdapter.addAll() has no argument.
– Rishabh876
Nov 12 at 14:07
I tried but it not adding to adapter
– Hannan Shaikh
Nov 12 at 14:11
I tried but it not adding to adapter
– Hannan Shaikh
Nov 12 at 14:11
add a comment |
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53263669%2fno-output-on-screen-after-fetching-data-from-json-and-populating-with-listview%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53263669%2fno-output-on-screen-after-fetching-data-from-json-and-populating-with-listview%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Did you try debugging? Check what are you passing adapter.to your ListView adapter.
– Kunu
Nov 12 at 13:57
Shouldn't you be passing the list you fetched into your adapter. In your NewsAsyncTask-> onPostExecute. mAdapter.addAll() has no argument.
– Rishabh876
Nov 12 at 14:07
I tried but it not adding to adapter
– Hannan Shaikh
Nov 12 at 14:11