My previous tutorial Android Custom ListView covers customizing android list view with image and text. In this tutorial I am going to explain even more customized list view like Facebook, Google+ news feed where it contains multiple images and texts.

I used android volley network library to make http calls and download the images. As volley comes with powerful image caching mechanism, we don’t have to much worry about caching the requests and images.

android facebook like custom news feed view

Final Output

Following is the screenshot of final output of this tutorial.

android facebook like feed view

Example feed Json

To demonstrate this tutorial I created an example json feed which contains an array of json feed object. Each object defines single feed row where it contains information like feed id, profile pic, profile name, timestamp, status message and feed image.

You can access the json from here.

{
    "feed": [
        {
            "id": 1,
            "name": "National Geographic Channel",
            "image": "https://api.androidhive.info/feed/img/cosmos.jpg",
            "status": "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
            "profilePic": "https://api.androidhive.info/feed/img/nat.jpg",
            "timeStamp": "1403375851930",
            "url": null
        },
        {
            "id": 2,
            "name": "TIME",
            "image": "https://api.androidhive.info/feed/img/time_best.jpg",
            "status": "30 years of Cirque du Soleil's best photos",
            "profilePic": "https://api.androidhive.info/feed/img/time.png",
            "timeStamp": "1403375851930",
            "url": "http://ti.me/1qW8MLB"
        }
    ]
}

In real world scenario, this feed json should be generated dynamically by reading a database.

1. Planning the Layout

Before start writing the code, I would like to plan the layout first. If you observe the feed view, it has information like name,timestamp, profile pic, feed image and url. For this we need TextView, ImageView and a listview to display the feed. Using the LinearLayout’s orientation property I have alligned the elements vertically and horizontally.

android facebook like list view layout

2. Downloading Volley.jar

If you are new to android volley library, I suggest you go through my previous article Android Volley Tutorial to understand what volley library is actually for. (In simple words volley is a networking library used to make HTTP calls)

Download the volley.jar and keep it aside.

Now let’s start by creating a new project.

3. Creating new project

1. Create a new project in Eclipse from File ⇒ New ⇒ Android Application Project and fill all the required information.

2. Open res ⇒ values ⇒ dimens.xml and add following dimensions. If you don’t have dimens.xml, create a new file and add these values.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    
    
    <dimen name="feed_item_margin">10dp</dimen>
    <dimen name="feed_item_padding_top_bottom">20dp</dimen>
    <dimen name="feed_item_padding_left_right">15dp</dimen>
    <dimen name="feed_item_profile_pic">50dp</dimen>
    <dimen name="feed_item_profile_info_padd">10dp</dimen>
    <dimen name="feed_item_profile_name">15dp</dimen>
    <dimen name="feed_item_timestamp">13dp</dimen>
    <dimen name="feed_item_status_pad_left_right">15dp</dimen>
    <dimen name="feed_item_status_pad_top">13dp</dimen>
    <dimen name="feed_item_corner_radius">3dp</dimen>
    <dimen name="feed_item_border_width">1dp</dimen>

</resources>

3. Also create another xml file named colors.xml under res ⇒ values and add following colors.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="white">#ffffff</color>
    <color name="feed_bg">#d3d6db</color>
    <color name="feed_item_bg">#ffffff</color>
    <color name="feed_item_border">#c2c3c8</color>
    <color name="link">#0a80d1</color>
    <color name="timestamp">#a0a3a7</color>    
</resources>

4. Under res ⇒ drawable, create a new file called bg_parent_rounded_corner.xml and paste the below code. This xml will give a rounded corner background to feed item.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- view background color -->
    <solid android:color="@color/feed_item_bg" >
    </solid>

    <!-- view border color and width -->
    <stroke
        android:width="@dimen/feed_item_border_width"
        android:color="@color/feed_item_border" >
    </stroke>

    <!-- Here is the corner radius -->
    <corners android:radius="@dimen/feed_item_corner_radius" >
    </corners>

</shape>

5. To keep the project well organized, I am creating required packages first. Create 4 packages named app, adapter, data and volley. To create new package, right click on src ⇒ New ⇒ Package and give package name. Example: info.androidhive.listview.app.

Following is the project structure I am trying to achieve.

facebook_feed_eclipse_project

6. Now paste the volley.jar in project libs folder.

7. Create a class named LruBitmapCache.java under volley package and add the following code. This class takes care of caching network images on disk.

package info.androidhive.listviewfeed.volley;

import com.android.volley.toolbox.ImageLoader.ImageCache;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

public class LruBitmapCache extends LruCache<String, Bitmap> implements
		ImageCache {
	public static int getDefaultLruCacheSize() {
		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
		final int cacheSize = maxMemory / 8;

		return cacheSize;
	}

	public LruBitmapCache() {
		this(getDefaultLruCacheSize());
	}

	public LruBitmapCache(int sizeInKiloBytes) {
		super(sizeInKiloBytes);
	}

	@Override
	protected int sizeOf(String key, Bitmap value) {
		return value.getRowBytes() * value.getHeight() / 1024;
	}

	@Override
	public Bitmap getBitmap(String url) {
		return get(url);
	}

	@Override
	public void putBitmap(String url, Bitmap bitmap) {
		put(url, bitmap);
	}
}

8. Under app package create class named AppController.java and paste the following content. This is a singleton class which initializes global instances of required classes. All the objects related to volley are initialized here.

package info.androidhive.listviewfeed.app;

import info.androidhive.listviewfeed.volley.LruBitmapCache;
import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

	public static final String TAG = AppController.class.getSimpleName();

	private RequestQueue mRequestQueue;
	private ImageLoader mImageLoader;
	LruBitmapCache mLruBitmapCache;

	private static AppController mInstance;

	@Override
	public void onCreate() {
		super.onCreate();
		mInstance = this;
	}

	public static synchronized AppController getInstance() {
		return mInstance;
	}

	public RequestQueue getRequestQueue() {
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(getApplicationContext());
		}

		return mRequestQueue;
	}

	public ImageLoader getImageLoader() {
		getRequestQueue();
		if (mImageLoader == null) {
			getLruBitmapCache();
			mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
		}

		return this.mImageLoader;
	}

	public LruBitmapCache getLruBitmapCache() {
		if (mLruBitmapCache == null)
			mLruBitmapCache = new LruBitmapCache();
		return this.mLruBitmapCache;
	}

	public <T> void addToRequestQueue(Request<T> req, String tag) {
		req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
		getRequestQueue().add(req);
	}

	public <T> void addToRequestQueue(Request<T> req) {
		req.setTag(TAG);
		getRequestQueue().add(req);
	}

	public void cancelPendingRequests(Object tag) {
		if (mRequestQueue != null) {
			mRequestQueue.cancelAll(tag);
		}
	}
}

9. Now open your AndroidManifest.xml file and add Application.java class in <application> tag. Also we need to add INTERNET permission as this app makes network calls.

    <application
        android:name="info.androidhive.listviewfeed.app.AppController"> ....</application>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.listviewfeed"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name="info.androidhive.listviewfeed.app.AppController"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="info.androidhive.listviewfeed.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

10. The main challenge in this project is adjusting the aspect ratio of feed image once it is downloaded. Unfortunately volley doesn’t provide any callback method once the NetworkImageView is loaded. So I created a custom ImageView class with callback methods. This class automatically adjusts the image height to prevent image aspect ratio distortion.

Under your project main package create a class named FeedImageView.java and paste the below code. I took the code from this stackoverflow answer and made few tweaks.

You can use this FeedImageView in your xml layout like this

<info.androidhive.listviewfeed.FeedImageView
            android:id="@+id/feedImage1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
package info.androidhive.listviewfeed;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;

public class FeedImageView extends ImageView {

	public interface ResponseObserver {
		public void onError();

		public void onSuccess();
	}

	private ResponseObserver mObserver;

	public void setResponseObserver(ResponseObserver observer) {
		mObserver = observer;
	}

	/**
	 * The URL of the network image to load
	 */
	private String mUrl;

	/**
	 * Resource ID of the image to be used as a placeholder until the network
	 * image is loaded.
	 */
	private int mDefaultImageId;

	/**
	 * Resource ID of the image to be used if the network response fails.
	 */
	private int mErrorImageId;

	/**
	 * Local copy of the ImageLoader.
	 */
	private ImageLoader mImageLoader;

	/**
	 * Current ImageContainer. (either in-flight or finished)
	 */
	private ImageContainer mImageContainer;

	public FeedImageView(Context context) {
		this(context, null);
	}

	public FeedImageView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public FeedImageView(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
	}

	/**
	 * Sets URL of the image that should be loaded into this view. Note that
	 * calling this will immediately either set the cached image (if available)
	 * or the default image specified by
	 * {@link VolleyImageView#setDefaultImageResId(int)} on the view.
	 * 
	 * NOTE: If applicable, {@link VolleyImageView#setDefaultImageResId(int)}
	 * and {@link VolleyImageView#setErrorImageResId(int)} should be called
	 * prior to calling this function.
	 * 
	 * @param url
	 *            The URL that should be loaded into this ImageView.
	 * @param imageLoader
	 *            ImageLoader that will be used to make the request.
	 */
	public void setImageUrl(String url, ImageLoader imageLoader) {
		mUrl = url;
		mImageLoader = imageLoader;
		// The URL has potentially changed. See if we need to load it.
		loadImageIfNecessary(false);
	}

	/**
	 * Sets the default image resource ID to be used for this view until the
	 * attempt to load it completes.
	 */
	public void setDefaultImageResId(int defaultImage) {
		mDefaultImageId = defaultImage;
	}

	/**
	 * Sets the error image resource ID to be used for this view in the event
	 * that the image requested fails to load.
	 */
	public void setErrorImageResId(int errorImage) {
		mErrorImageId = errorImage;
	}

	/**
	 * Loads the image for the view if it isn't already loaded.
	 * 
	 * @param isInLayoutPass
	 *            True if this was invoked from a layout pass, false otherwise.
	 */
	private void loadImageIfNecessary(final boolean isInLayoutPass) {
		final int width = getWidth();
		int height = getHeight();

		boolean isFullyWrapContent = getLayoutParams() != null
				&& getLayoutParams().height == LayoutParams.WRAP_CONTENT
				&& getLayoutParams().width == LayoutParams.WRAP_CONTENT;
		// if the view's bounds aren't known yet, and this is not a
		// wrap-content/wrap-content
		// view, hold off on loading the image.
		if (width == 0 && height == 0 && !isFullyWrapContent) {
			return;
		}

		// if the URL to be loaded in this view is empty, cancel any old
		// requests and clear the
		// currently loaded image.
		if (TextUtils.isEmpty(mUrl)) {
			if (mImageContainer != null) {
				mImageContainer.cancelRequest();
				mImageContainer = null;
			}
			setDefaultImageOrNull();
			return;
		}

		// if there was an old request in this view, check if it needs to be
		// canceled.
		if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {
			if (mImageContainer.getRequestUrl().equals(mUrl)) {
				// if the request is from the same URL, return.
				return;
			} else {
				// if there is a pre-existing request, cancel it if it's
				// fetching a different URL.
				mImageContainer.cancelRequest();
				setDefaultImageOrNull();
			}
		}

		// The pre-existing content of this view didn't match the current URL.
		// Load the new image
		// from the network.
		ImageContainer newContainer = mImageLoader.get(mUrl,
				new ImageListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						if (mErrorImageId != 0) {
							setImageResource(mErrorImageId);
						}

						if (mObserver != null) {
							mObserver.onError();
						}
					}

					@Override
					public void onResponse(final ImageContainer response,
							boolean isImmediate) {
						// If this was an immediate response that was delivered
						// inside of a layout
						// pass do not set the image immediately as it will
						// trigger a requestLayout
						// inside of a layout. Instead, defer setting the image
						// by posting back to
						// the main thread.
						if (isImmediate && isInLayoutPass) {
							post(new Runnable() {
								@Override
								public void run() {
									onResponse(response, false);
								}
							});
							return;
						}

						int bWidth = 0, bHeight = 0;
						if (response.getBitmap() != null) {

							setImageBitmap(response.getBitmap());
							bWidth = response.getBitmap().getWidth();
							bHeight = response.getBitmap().getHeight();
							adjustImageAspect(bWidth, bHeight);

						} else if (mDefaultImageId != 0) {
							setImageResource(mDefaultImageId);
						}

						if (mObserver != null) {
							mObserver.onSuccess();

						}
					}
				});

		// update the ImageContainer to be the new bitmap container.
		mImageContainer = newContainer;

	}

	private void setDefaultImageOrNull() {
		if (mDefaultImageId != 0) {
			setImageResource(mDefaultImageId);
		} else {
			setImageBitmap(null);
		}
	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		super.onLayout(changed, left, top, right, bottom);
		loadImageIfNecessary(true);
	}

	@Override
	protected void onDetachedFromWindow() {
		if (mImageContainer != null) {
			// If the view was bound to an image request, cancel it and clear
			// out the image from the view.
			mImageContainer.cancelRequest();
			setImageBitmap(null);
			// also clear out the container so we can reload the image if
			// necessary.
			mImageContainer = null;
		}
		super.onDetachedFromWindow();
	}

	@Override
	protected void drawableStateChanged() {
		super.drawableStateChanged();
		invalidate();
	}

	/*
	 * Adjusting imageview height
	 * */
	private void adjustImageAspect(int bWidth, int bHeight) {
		LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();

		if (bWidth == 0 || bHeight == 0)
			return;

		int swidth = getWidth();
		int new_height = 0;
		new_height = swidth * bHeight / bWidth;
		params.width = swidth;
		params.height = new_height;
		setLayoutParams(params);
	}
}

11. Open your layout for main activity (activity_main.xml) and add a list view element for the feed list.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="@null" />

</LinearLayout>

12. Create another layout file named feed_item.xml under res ⇒ layout folder. This layout file represents each individual feed item row in the list view.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/feed_bg"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"

        android:layout_marginLeft="@dimen/feed_item_margin"
        android:layout_marginRight="@dimen/feed_item_margin"
        android:layout_marginTop="@dimen/feed_item_margin"
        android:background="@drawable/bg_parent_rounded_corner"
        android:orientation="vertical"
        android:paddingBottom="@dimen/feed_item_padding_top_bottom"
        android:paddingTop="@dimen/feed_item_padding_top_bottom" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingLeft="@dimen/feed_item_padding_left_right"
            android:paddingRight="@dimen/feed_item_padding_left_right" >

            <com.android.volley.toolbox.NetworkImageView
                android:id="@+id/profilePic"
                android:layout_width="@dimen/feed_item_profile_pic"
                android:layout_height="@dimen/feed_item_profile_pic"
                android:scaleType="fitCenter" >
            </com.android.volley.toolbox.NetworkImageView>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:paddingLeft="@dimen/feed_item_profile_info_padd" >

                <TextView
                    android:id="@+id/name"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:textSize="@dimen/feed_item_profile_name"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/timestamp"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:textColor="@color/timestamp"
                    android:textSize="@dimen/feed_item_timestamp" />
            </LinearLayout>
        </LinearLayout>

        <TextView
            android:id="@+id/txtStatusMsg"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="5dp"
            android:paddingLeft="@dimen/feed_item_status_pad_left_right"
            android:paddingRight="@dimen/feed_item_status_pad_left_right"
            android:paddingTop="@dimen/feed_item_status_pad_top" />

        <TextView
            android:id="@+id/txtUrl"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:linksClickable="true"
            android:paddingBottom="10dp"
            android:paddingLeft="@dimen/feed_item_status_pad_left_right"
            android:paddingRight="@dimen/feed_item_status_pad_left_right"
            android:textColorLink="@color/link" />

        <info.androidhive.listviewfeed.FeedImageView
            android:id="@+id/feedImage1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:scaleType="fitXY"
            android:visibility="visible" />
    </LinearLayout>

</LinearLayout>

13. Under data package, create a class named FeedItem.java. This is a POJO class used to create objects for each feed item while parsing the json. The feed item object contains information like profile pic, name, timestamp, status message, url and feed image.

package info.androidhive.listviewfeed.data;

public class FeedItem {
	private int id;
	private String name, status, image, profilePic, timeStamp, url;

	public FeedItem() {
	}

	public FeedItem(int id, String name, String image, String status,
			String profilePic, String timeStamp, String url) {
		super();
		this.id = id;
		this.name = name;
		this.image = image;
		this.status = status;
		this.profilePic = profilePic;
		this.timeStamp = timeStamp;
		this.url = url;
	}

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getImge() {
		return image;
	}

	public void setImge(String image) {
		this.image = image;
	}

	public String getStatus() {
		return status;
	}

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

	public String getProfilePic() {
		return profilePic;
	}

	public void setProfilePic(String profilePic) {
		this.profilePic = profilePic;
	}

	public String getTimeStamp() {
		return timeStamp;
	}

	public void setTimeStamp(String timeStamp) {
		this.timeStamp = timeStamp;
	}

	public String getUrl() {
		return url;
	}

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

14. Now under adapter package create a class named FeedListAdapter.java. This is a custom adapter class for feed list view. This adapter class takes care following things.

> Displaying feed data like name, timestamp, profile pic, status message and feed image.
> Converts timestamp into x minutes/hours/days ago format
> Makes URL clickable by using url.setMovementMethod(LinkMovementMethod.getInstance())

package info.androidhive.listviewfeed.adapter;

import info.androidhive.listviewfeed.FeedImageView;
import info.androidhive.listviewfeed.R;
import info.androidhive.listviewfeed.app.AppController;
import info.androidhive.listviewfeed.data.FeedItem;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

public class FeedListAdapter extends BaseAdapter {	
	private Activity activity;
	private LayoutInflater inflater;
	private List<FeedItem> feedItems;
	ImageLoader imageLoader = AppController.getInstance().getImageLoader();

	public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
		this.activity = activity;
		this.feedItems = feedItems;
	}

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

	@Override
	public Object getItem(int location) {
		return feedItems.get(location);
	}

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		if (inflater == null)
			inflater = (LayoutInflater) activity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (convertView == null)
			convertView = inflater.inflate(R.layout.feed_item, null);

		if (imageLoader == null)
			imageLoader = AppController.getInstance().getImageLoader();

		TextView name = (TextView) convertView.findViewById(R.id.name);
		TextView timestamp = (TextView) convertView
				.findViewById(R.id.timestamp);
		TextView statusMsg = (TextView) convertView
				.findViewById(R.id.txtStatusMsg);
		TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
		NetworkImageView profilePic = (NetworkImageView) convertView
				.findViewById(R.id.profilePic);
		FeedImageView feedImageView = (FeedImageView) convertView
				.findViewById(R.id.feedImage1);

		FeedItem item = feedItems.get(position);

		name.setText(item.getName());

		// Converting timestamp into x ago format
		CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
				Long.parseLong(item.getTimeStamp()),
				System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
		timestamp.setText(timeAgo);

		// Chcek for empty status message
		if (!TextUtils.isEmpty(item.getStatus())) {
			statusMsg.setText(item.getStatus());
			statusMsg.setVisibility(View.VISIBLE);
		} else {
			// status is empty, remove from view
			statusMsg.setVisibility(View.GONE);
		}

		// Checking for null feed url
		if (item.getUrl() != null) {
			url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
					+ item.getUrl() + "</a> "));

			// Making url clickable
			url.setMovementMethod(LinkMovementMethod.getInstance());
			url.setVisibility(View.VISIBLE);
		} else {
			// url is null, remove from the view
			url.setVisibility(View.GONE);
		}

		// user profile pic
		profilePic.setImageUrl(item.getProfilePic(), imageLoader);

		// Feed image
		if (item.getImge() != null) {
			feedImageView.setImageUrl(item.getImge(), imageLoader);
			feedImageView.setVisibility(View.VISIBLE);
			feedImageView
					.setResponseObserver(new FeedImageView.ResponseObserver() {
						@Override
						public void onError() {
						}

						@Override
						public void onSuccess() {
						}
					});
		} else {
			feedImageView.setVisibility(View.GONE);
		}

		return convertView;
	}

}

15. Now we have all the required classes in place. Open your main activity class MainActivity.java and add the following code. Here using volley JsonObjectRequest I fetched the json, parsed it(created array of feed item objects) and passed the data to list view adapter.

package info.androidhive.listviewfeed;

import info.androidhive.listviewfeed.adapter.FeedListAdapter;
import info.androidhive.listviewfeed.app.AppController;
import info.androidhive.listviewfeed.data.FeedItem;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;

import com.android.volley.Cache;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;

public class MainActivity extends Activity {
	private static final String TAG = MainActivity.class.getSimpleName();
	private ListView listView;
	private FeedListAdapter listAdapter;
	private List<FeedItem> feedItems;
	private String URL_FEED = "https://api.androidhive.info/feed/feed.json";

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

		listView = (ListView) findViewById(R.id.list);

		feedItems = new ArrayList<FeedItem>();

		listAdapter = new FeedListAdapter(this, feedItems);
		listView.setAdapter(listAdapter);
		
		// These two lines not needed,
		// just to get the look of facebook (changing background color & hiding the icon)
		getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
		getActionBar().setIcon(
				   new ColorDrawable(getResources().getColor(android.R.color.transparent)));

		// We first check for cached request
		Cache cache = AppController.getInstance().getRequestQueue().getCache();
		Entry entry = cache.get(URL_FEED);
		if (entry != null) {
			// fetch the data from cache
			try {
				String data = new String(entry.data, "UTF-8");
				try {
					parseJsonFeed(new JSONObject(data));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

		} else {
			// making fresh volley request and getting json
			JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
					URL_FEED, null, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							VolleyLog.d(TAG, "Response: " + response.toString());
							if (response != null) {
								parseJsonFeed(response);
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							VolleyLog.d(TAG, "Error: " + error.getMessage());
						}
					});

			// Adding request to volley request queue
			AppController.getInstance().addToRequestQueue(jsonReq);
		}

	}

	/**
	 * Parsing json reponse and passing the data to feed view list adapter
	 * */
	private void parseJsonFeed(JSONObject response) {
		try {
			JSONArray feedArray = response.getJSONArray("feed");

			for (int i = 0; i < feedArray.length(); i++) {
				JSONObject feedObj = (JSONObject) feedArray.get(i);

				FeedItem item = new FeedItem();
				item.setId(feedObj.getInt("id"));
				item.setName(feedObj.getString("name"));

				// Image might be null sometimes
				String image = feedObj.isNull("image") ? null : feedObj
						.getString("image");
				item.setImge(image);
				item.setStatus(feedObj.getString("status"));
				item.setProfilePic(feedObj.getString("profilePic"));
				item.setTimeStamp(feedObj.getString("timeStamp"));

				// url might be null sometimes
				String feedUrl = feedObj.isNull("url") ? null : feedObj
						.getString("url");
				item.setUrl(feedUrl);

				feedItems.add(item);
			}

			// notify data changes to list adapater
			listAdapter.notifyDataSetChanged();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

Now run the project and test it once. Make sure that your emulator/device is having internet connect before you test.

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • erik suprayogi

    Awesome

  • Jose Ricardo Dainese

    Dude, congratulations, this site has helped me a lot

  • ayajibo

    Thanks man. This site helped me a lot. It is like everything I was looking for exists here.

  • Suumit Shah

    This is damn awesome article Ravi! I wanted ask you one thing, is it possible to build such app which can fetch articles from some RSS feed and render same on screen?

  • Guest

    I like your emulator. how to change it?

  • Zoloo

    very good! i like your emulator. how to change it?

  • Nagesh Kulkarni

    Wow awesome, I really liked it…!!

  • krishnalalstha

    How to show image in popup like facebook did ?

    • Create another activity with a NetworkImageView in it’s layout file.

      Implement onClick listener on image on list view and pass the image url to full screen image view activity.

      • krishnalalstha

        ya i know that but i want to achieve that kind of effect on click image. i hope you have noticed that effect.

        • Then you can have the networkimageview in the same layout below listview and do toggle hiding b/w listview and imageview. So that you can add any kind of effects while showing fullscreen image.

        • Filipe

          You can achieve it using Rebound library https://github.com/facebook/rebound

  • baha_odeh

    thank you man , but i think loopj.com/android-async-http/ work better thank volley ?

  • cost

    How can I “take” a real json file from facebook.com??? (real time facebook list)
    That would be cool

  • Pedro Pedro

    hi Ravi, first of all I ‘ll like to thanks U for all the help you provide.I’ m a new android developper and your site is very helpfull.I would like to use the custom imageview you gave in a ViewPager, it works fine but the image isn’t displayed at the center how can I change it( the position of the image),Previously i did it in the XML layout.

    • can you paste your layout code here?

      • Pedro Pedro

        thank’s

        • what is com.brasserie.cap.adapters.fullscreenimageview?

          • Pedro Pedro

            it’s the same java class as the one you gave in your tutorial “FeedImageView” I only changed the method “adjustImageAspect” by adding

            RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) getLayoutParams();

          • Try using LinearLayout.LayoutParams and use

            params.gravity=Gravity.CENTER;

            Also to display a fullscreen image we don’t have to create a custom imageview class. Use NetworkImageView directly in xml layout.

          • Pedro Pedro

            I’ve try it but i got an Exception
            when i tried LinearLayout.params
            java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams, I think it is because the layout has a Relativelayout

          • Pedro Pedro

            yep fine,I did it as you said, change to linearlayout and I also modified my PageAdapter by overriding the “isViewFromObject” returning a linearlayout too.
            thks a lot once more

          • I am glad you solved it 🙂

          • Pedro Pedro

            Sorry Ravi from disturbing once more 🙂 But I’m facing another matter once more 🙁
            I would like to display a GIF image while downloading the image I put the image in the drawable folder, and use the “setDefaultImageResId” in my custom adapter, but the gif work as expected ,It behave like a normal Bitmap. I ‘ll like it to be as in your previous tuto on Volley. thks

          • In my volley tutorial, I used ProgressDialog element not GIF image. If you want to use gif image with animation use this library.
            https://github.com/Hipmob/gifanimateddrawable

          • Pedro Pedro

            thks man I will try it 🙂

          • Pedro Pedro

            hi ravi, I’ve been around the Web and I found that sometimes displaying a GIF can cause an OOM exception, so i decided to use a progress bar( PB) while the image will be loading.I just added the PB in my layout then in the BaseAdapter class. I can show it but, how can I hide it once the download is done?

          • Which element you are using to display the image?

          • Pedro Pedro

            sorry I didn’t understand what U mean

          • Pedro Pedro

            If this could help I would like to display an Image while downloading, so I firstly planned to use a gif but I’m afraied of an OOM excep.so I would like to display a progress bar instead of that gif

          • Ok

          • I mean ImageView or NetworkImageView ?

          • Pedro Pedro

            I used the custom one U gave in this tutorial.

          • Then it has callback methods onSuccess() and onError(). You can hide your PD in these methods.

            .setResponseObserver(new FeedImageView.ResponseObserver() {
            @Override
            public void onError() {
            // hide the PD here
            }

            @Override
            public void onSuccess() {
            // hide the PD here
            }
            })

          • Pedro Pedro

            thks man:) but I’ve tried your suggestion, in fact the real matter is how to show the PD, I would like to display it under the every single DefaultImage of my Custom Gridview , so the advice you gave me will hide it, but how to display the PD

          • Guest

            I have been all the day looking how I can resolve that, but I didn’t found, If i didn’t hide the PD in the observer, it still display, but if I hide it, it doesn’t even display during the downloading with volley, it is normal it think.The only way to resolve it, it think I’m not sure, it will be if i could check if the default image is remplace by the one download, do U have an idea on how check it please.
            thank’s

  • Pravesh Choudhary

    in my MainActivity.java, automatically MainActivity is extending ActionBarActivity and also appcompatv7 named folder is generating when I am creating the project which is not there in your code…why ?

    • Its because you have updated your android SDK it to latest build tools version. You can revert your MainActivity to normal (like extending from activity), it will work. You can remove appcompatv7 too from build libraries.

      I still need to study what ActionBarActivity is for, that’s why I posted this tutorial in older fashion.

      • Pravesh Choudhary

        can I send my project to you on facebook in .zip format so that you can make the correction ? I tried many times but I think there is some very small mistake.

        • Pravesh Choudhary

          Done successfully…found the problem !! Thanks ! 🙂

      • Prathap

        ActionBarActivity is a class in AppCompat Library(from Android team) which is an extension of the support library designed to facilitate the use of the action bar design pattern across all versions of Android with a single API.

        Similar to ActionBarSherlock Library.

  • Guest

    Hello ravi sir ! this is a very useful tutorial ! thankyou soo much !
    can you plz tell is there any short way to run this in a fragment and not in an activity ?
    waiting for your reply !

    • Pedro Pedro

      hi! your fragment is for the listView? normally there is no great difference

      • Guest

        please elaborate the method to show this Custom ListView Feed into a fragment 🙂
        regards

        • Pedro Pedro

          first of all you will need create another activity, which will contain your fragment,
          and the main activity (the one which ravi gave in this tutorial) you change
          it to fragment that means it will extend Fragment or Listfragment as you like
          You will have to do some changes in your code because the fragment do not react the same as activity
          I hope U get what I mean(french speaker and android’s newby so 🙂 )

  • Hi Ravi,
    Is this feed dynamic, that is, uploading the latest post from every feed?
    As far as I can see it is set to certain links. Is there a way to set it to websites’ RSS feed?

  • Subhendu Pratap Singh

    Hi Ravi,
    Yet another amazing post for all the android enthusiasts. Double thumbs up to your post.
    One small thing, i think layout height should be fill parent in activity_main.xml otherwise in case of single item in the list view, image doesn’t show up properly.

    • Hmm, I didn’t think about it. Thanks for the suggestion.

  • IMRAN

    Thanks Ravi Tamada …………. i have a simple query …. can i upload file using “volley” .

  • badname

    what this format ? “timeStamp”: “1403375851930”,
    how i insert now ?
    14 year ?
    pls help for insert this true 🙂

    • It is linux time stamp. You can generate it easily in java.

      • badname

        thx man
        also feed.json not raed from my host i fix it now with “?” 🙂
        url…”………com/file/feed.json?”

  • Faiz

    Really it is great site. I am learning android. It will be great if you can write new article to demonstrate RSS using volley capabilities.

    Thanks in advance

  • Lubulwa Ric

    Ravi thanks for the post, how can i use this volley library to retrieve articles from any website and this information should be updated as the website gets updated

  • jorge david

    thank you man, i’m making an university project and it help me a lot.

  • IMRAN

    Ravi i want to ask a question which is not relevant ………any idea how we can develop app like “WhatsApp”……… thanks

    • I can’t say it in one sentence. Lot of things involves like REST API, server side database, GCM.

      • IMRAN

        Ravi i already worked with REST API, server side database(MySQL , MSSQL), GCM
        but as per my experience ….i think …we can’t develop IM app with these as fast as “whatsApp” or “viber”

        • No, we can develop.I developed a prototype a long time back, but couldn’t post on blog as it is somewhat lengthy article.

          • André

            Any way we can see the code?

          • Sorry, I don’t have it right now.

      • IMRAN

        i am learning lot of things from your bog …… have you any platform where we can put our queries .
        Thanks

  • Tuan Hoang Anh

    please help me, i use stringrequest of volley library with VietNam language from web, after response my result error font. Any solution?

  • hi ravi

    just a question

    i want to make an rss app to save sqlite db with this method and i only have a question

    how does the app knows if the json feed is updated?

    FYI the app should update automatic when user opens it

    i figured that i can compare the id of last data i added to db with the first id of what is being parsed from json

    is it ok or there is a better way other than that?

  • jorge david

    i have a question, how can use this with fragments?, i mean that a fragment content a listview

    • Bala Vishnu

      Its almost the same, Put the contents of the onCreate() in MainActivity to onActivity Created() of a fragment and then place the fragment on top of an Activity

  • akin

    hello Ravi, You have been doing a great work here. Most of what I can do on android was from android hive. But Please i want you to make a tutorial on User profiles. where a user logs in and uploads his/her picture, post articles and also comment on another user’s article. hope am not asking too much…… am an oliver twist.

  • Rajesh Jaiswal

    Wowww!!! What a blog.

    Awesome… Everything is working fine

    Thanks

    • Thanks for the appreciation.

      • silentmind

        thank you sir , its working like a charm.
        i am able to upload my file using filezila And CAN parse json also from my json url.

        sir you are great , first nd last resort for many android app developer.

    • silentmind

      ravi’s magic

      • 🙂

        • silentmind

          ravi sir please help me out

          i don’t know how to parse my own json file in my app

          i purchased domain name and hosting also

          but i don’t know how to upload json file and you have api.androidhive…….
          this url , i don’t how to get api.mywebsite…..
          please help me out .

          • Which hosting you bought?

          • silentmind

            sir , i have bought it from godaddy , i have cpanel also .

          • silentmind

            sir i have of godaddy , with that i have cpanel also.

          • silentmind

            i have of godaddy , with which i got cpanel also.

          • silentmind

            i have hosting godaddy and i have cpanel also

          • Then to upload a file you need to follow these steps.
            1. Create an FTP user in cpanel
            2. Download filezilla software to connect to ftp
            3. After connecting through filezilla upload your json file www folder (it might changes depending on your server)
            4. Access the file via url in browser

            If you want to access like me i.e api.yourdomain, you need to create a subdomain in godday’s admin panel. Create a new cRecord.

          • silentmind

            sir you are great , i am gonna try this .
            thanks a lot.

  • Bodo Riffer

    Hello!

    This really is a great article. I would like to download the source but have no afford in registering with android hive. Tried 4 times by now but do not get any email. Maybe a permanent problem?

    • youming2007

      You just need to type your email when downloading and click Download Code again!

    • Yeah, I have noticed it. Please check your SPAM folder. It should be there.

  • PISOT

    Ravi, How can I put the json request inside my model class? Hoping for your response

    • What do you mean by keeping json request in model class. Could you elaborate?

  • amin

    Hi Ravi, could you make an tutorial to how to create a messenger program like viber, line , what app or…. ? your works are so nice, thanks.

    • Yeah, I am preparing it. But in order to post that I have to cover lot of other topics first.

      • IMRAN

        great ………… we are waiting Ravi

      • silentmind

        eagerly waiting

  • Lewis Munene

    how do you produce that timestamp?

  • Nikhil Shete

    Thanx for this tutorial. I want to refresh or update feed items of the list view. Refresh button click. i used //Calendar calendar = Calendar.getInstance();

    //long serverDate = AppController.getInstance().getRequestQueue().getCache().get(URL_FEED).serverDate;

    //AppController.getInstance().getRequestQueue().getCache().invalidate(URL_FEED, true);

    //AppController.getInstance().getRequestQueue().getCache().remove(URL_FEED);

    Nothing works. Works only when go to app setting and clear cache. Please help me

    • Simple fix is to replace

      Cache cache = AppController.getInstance().getRequestQueue().getCache();
      Entry entry = cache.get(URL_FEED);
      if (entry != null) {
      // fetch the data from cache
      try {
      String data = new String(entry.data, “UTF-8”);
      try {
      parseJsonFeed(new JSONObject(data));
      } catch (JSONException e) {
      e.printStackTrace();
      }
      } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      }
      } else {
      // making fresh volley request and getting json
      JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
      URL_FEED, null, new Response.Listener() {
      @Override
      public void onResponse(JSONObject response) {
      VolleyLog.d(TAG, “Response: ” + response.toString());
      if (response != null) {
      parseJsonFeed(response);
      }
      }
      }, new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {
      VolleyLog.d(TAG, “Error: ” + error.getMessage());
      }
      });
      // Adding request to volley request queue
      AppController.getInstance().addToRequestQueue(jsonReq);
      }
      }

      with

      JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
      URL_FEED, null, new Response.Listener() {
      @Override
      public void onResponse(JSONObject response) {
      VolleyLog.d(TAG, “Response: ” + response.toString());
      if (response != null) {
      parseJsonFeed(response);
      }
      }
      }, new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {
      VolleyLog.d(TAG, “Error: ” + error.getMessage());
      }
      });
      // Adding request to volley request queue
      AppController.getInstance().addToRequestQueue(jsonReq);
      }

      this will however remove the benefits of having cache.
      To effectively use cache you need to implement

      private boolean isNetworkAvailable() {
      ConnectivityManager connectivityManager
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
      return activeNetworkInfo != null && activeNetworkInfo.isConnected();
      }

      and call isNetworkAvailable() in onCreate such that

      if(isNetworkAvailable()){
      //the Call for server comes here
      }
      else{
      //Call the cache here
      }

      I hope you can figure it out. If not, I’ll try to explain further

  • ketul

    Hi Ravi,

    This is really good article and I want to use in my porject and for that I try to modify it,
    I have tried to change Feedimage to view pager with dynamic height like facebook but i stuck and its not working, can you help me to solve out this.

    Thanks

  • Z

    hi Ravi, i just want to display list of imageview and if i click one the selected imageview will zoom.
    how can i do that?
    thanks 🙂

  • JAmes

    How do you force it to refresh the feed each time on load not load from cache.

  • nana

    Ravi i downloaded the source code and tried running the apk file in the bin folder…but it is not working

  • EmileH2000

    Hi Ravi I really appreciate how you help all of us with these tutorials. I’m a young coder (16) and want to know how i can refresh this feed, or better still, how can i make it auto refresh itself like facebook does?

    • Hi Emile,

      May be you need to make a call to server on onResume() method to get latest feed. You need to have a server side mechanism to change the expiry headers, otherwise volley won’t fetch updated json from the url.

      • EmileH2000

        Ok thanks!

      • saeed

        how can i do it ?

  • Charbel Hassrouny

    Hey, i created Android Sliding Menu (it is done by androidhive also, http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/)
    this thing is that each item in this Sliding Menu calls a fragment, i want to make one of the fragments calls this listview feed.
    Can i have a clear code of how to convert this to fragment, not fragment activity.

    Thanks in advance 😀

    • Alan Lee

      I trying do this combination, and also get error, maybe @ravi8x:disqus can give a hint to us 🙂

      • uno_xx

        I am using it inside a fragment without any problem. May be you missed something.

        • Alan Lee

          Yeap, I already found the problem and fixed it, thx 🙂

          • nishant

            Could u plz tell me?

          • uno_xx

            Code is almost same, except for using getActivity() as context.

          • nishant

            Thanks.
            I’ve fragment class (as in case of navigation drawer ) that calls my simple layout .
            Do I need to create new activity for placing above given MainActivity code or I can place it into
            Existing fragment class. Wht changes I’ve to make?

            I’m kind of new here ….plz help. here is my mail id : nishant2740@gmail.com

          • uno_xx

            I tried it in same fragment but there are many possibilities.

          • nishant

            Thanks again.
            Can u send me that fragment class coding which u have done for ?if possible.

          • uno_xx
          • nishant

            I’ve implemented the given code But I’m getting unfortunately app_name has stopped.l
            Any correction…..!

          • uno_xx

            You have to find the problem yourself, you have logs, you have code. Take help from logs and try to solve it…

        • nishant

          Can u share ur idea!!.?? Please.

  • Tanmay

    how to fetch data from the website(which do not have rss feed or json feed in their website) in the same example u mention above ?
    and news feed should update automatically with the website posts and data with time to time

  • Charbel Hassrouny

    how can i get the FeedItem id at a specific position in the list?

    • Lewis Munene

      i used the name textview to get a specific position .in the FeedlistAdapter under the get view method i added this …
      final FeedItem item = feedItems.get(position);

      name.setText(item.getName());

      name.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
      info =item.getName();
      Bundle extras = new Bundle();
      Intent i1 = new Intent (context, Begin.class);
      extras.putString(“val”, info);
      //pasing info to new activity
      i1.putExtras(extras);
      context.startActivity(i1);

      //Intent callIntent = new Intent();
      Log.d(“Clicked”,”textview clicked “

  • jeeva

    Whenever i update the json file in my server,application not showing the updated data,

    it shows the updated data only if i reinstall the application ,Kindly share the code for this issue and also include loading alert dialog box

    • Mehmet Can Taş

      I need that too

  • Kelvin

    I am trying to redo the whole project using fragments instead of activity but there is an error at feedlistadapter.java trying to get the layout inflater for fragments

  • max

    how to make infinity scroll ?

  • Guest

    It is very good indeed but how do you parse JSON in UTF-8 ? In order to display Hindi 🙂 I am making an app which is Hindi related.
    Thank you very much if you have time to explain or add the few line of code which would make it possible to display it properly.

  • Tonyoh87

    Great Tutorial 🙂

  • TonyAndroid

    I can’t download the code (keep getting timeout). Does anyone mind send me the code, please?
    my mail: raffproject@gmail.com

    • Please check your SPAM folder for activation email.

      • wellington

        Also I can not download

  • Nef

    Excellent tutorial congratulations. I have a question. How can I show
    the content within a fragment?. I hope to have your help. Thank you

  • JustHit Play

    Hi I try this onw but my app says unfortunately stop… Can you please help me..

    • Bas Wilson

      Anyone Found a fix yet?

  • JustHit Play

    Hi Ravi.. I wonder if I can use my own facebook URL in the json? and how?

    • I haven’t tried. But look for graph api in facebook docs.

      • JustHit Play

        Hi Ravi… This is what I found and Tried. But, the app loads a blank feed. What Am I doing wrong?

        ———–

        “How to obtain JSON/RSS feed for Facebook Pages without OAuth/GraphAPI

        Facebook killed their publicly available RSS feed for Facebook Pages couple of years back in favor of their walled garden approach (GraphAPI). For example, if you go to http://graph.facebook.com/Nike/feed it will ask you for a valid access token which you can get obtain via OAuth Authorization which entails quite a few steps. If you just wanted to display/parse any Facebook Page feed without going through those hoops you are out of luck!

        I found myself in a similar situation recently and after some Googling I was able to figure out a workaround. Here’s how it goes:

        1) Go to https://developers.facebook.com/tools/explorer

        2) Put the username/vanity url of the Facebook Page in question in the request bar and hit Submit. For example, if you wanted to get a feed for:https://www.facebook.com/nike you would put “nike” without quotes in the request bar and click on Submit. (Make sure GET request is selected in the drop-down)

        3) Grab the id from the results below and paste it in this URL: https://www.facebook.com/feeds/page.php?id=%5BFACEBOOK-ID-GOES-HERE%5D&format=%5Brss20|json]
        So for example, if we wanted JSON feed for Nike’s Facebook page, we’d go to:https://www.facebook.com/feeds/page.php?id=15087023444&format=json

        ————–

        Here is my code:

        e String URL_FEED = “https://www.facebook.com/feeds/page.php?id=15087023444&format=json”;

        and here is my error:

        [2014-07-30 21:06:07 – Facebook Like FeedView] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=info.androidhive.listviewfeed/.MainActivity }

        [2014-07-30 21:06:07 – Facebook Like FeedView] ActivityManager: Warning: Activity not started, its current task has been brought to the front

        • Bas Wilson

          I also have this problem blank feed, can anyone help?

          • JustHit Play

            yeah same problem ! I hope @ravi8x:disqus help us..

          • Please try to write the response to LogCat and verify whether you guys are getting something in the response or not. This happened to me when my phone doesn’t have internet connection.

          • JustHit Play

            Im using Emulator..

          • Did you printed the response to logcat? I already printed in log. Check for “Response: ” or “Error: ”

            VolleyLog.d(TAG, “Response: ” + response.toString()); will print the json added in MainActivity.java

          • JustHit Play

            the error: Error Opening trace file: No such file or directory (2)

          • Its not the error. Paste the complete log if you see it in red color font.

          • JustHit Play

            what i did is i change your json link

            http://api.androidhive.info/feed/feed.json to

            “https://www.facebook.com/feeds/page.php?id=196934133652011&format=json”

          • It won’t work that way for every json url. You need to make the changes in the code according to the json response.

          • JustHit Play

            Can you help me to figure this out ?

  • Guest

    Hi Ravi, I have succesfully build the app and done everything without errors and stuff but now on my phone on start up of the app it says: Unfortunately, “My App” Has Stopped. Can you suggest anything to fix this?

    • Pls check your Logcat for errors.

      • Guest

        The red lines in the logcat starts with FATAL EXCEPTION: main, Hope you can help me, and maybe a crucial one is: Process”” com.example.listviewfeed, PID: 32486

        • Guest

          I Have fixed thanks anyway

      • Bas Wilson

        Hi Ravi, How can i use a custom json file I have uploaded it to my website and when i go to the link its the same as how yours would preview but when i put the link in MainActivity.java and if i then start the app nothing shows up.. Can you help please

  • I Have updated the project to download new information everytime the activity is loaded and internet connection is available.
    When internet connection is not available it fetches the cache and uses it.
    You can also combine this with refresh options like SwipeRefreshLayout or the ActionBar Refresh Button [Not Included in this project]. whenever you want to refresh just call getFeed();
    Download: http://go.adm.bugs3.com/1

    • Faiz

      Thanks a lot for your valuable contribution…. need a solution for xml request instead of json

      • final String URL = “/volley/resource/recent.xml”;
        StringRequest req = new StringRequest(URL, new Response.Listener() {
        @Override
        public void onResponse(String response) {
        VolleyLog.v(“Response:%n %s”, response);
        }
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        VolleyLog.e(“Error: “, error.getMessage());
        }
        });

        // add the request object to the queue to be executed
        ApplicationController.getInstance().addToRequestQueue(req);

        parse XML in onResponse.You can find tutorial for it in this blog itself

        • Jeeva

          Hi , i have used your updated code from your download path, but the application is not refresing everytime when i update the json file in the server, kindly help me. you can also reach me at jeevap14@gmail.com

          • What do you mean?
            Does it not load new data instantly the server was updated or it doesn’t update itself even during activity launch?
            Keep in mind that for information to be updated instantly you need to use GCM

          • Jeeva

            Hi Idragon81, it doesn’t update itself even during activity launch, it only refresh only when i clear the cache.Kindly check and provide me the solution

    • Indra

      Link is not working Pls update

    • Levi Costa

      Link not work.. 🙁

  • hatim

    bonjour Ravi ,
    merci bcq pour votre tuto de “Android Facebook like Custom ListView Feed using Volley” , j’ai des questions si c possible je veux utiliser votre exemple avec un flux rss des site des journaux electronique et je veux ajouter une zone de commentaire pour chaque article afficher .
    si vous pouvez m’aider
    merci d’avance

  • silentmind

    i have bought from godaddy and cpanel also .

  • Joe Jo

    How do i make the List item Clickable ?

  • Hi, Ravi. I’am a new for developing Android App.

    Btw, thanks for the best tutorial. I have a problem with my “own experience”. Can you tell me what its wrong with my code below:

    TextView title = (TextView) concertView.findViewById(R.id.title);
    TextView typeFood = (TextView) concertView.findViewById(R.id.typefood);
    TextView restaurantLocation = (TextView) concertView.findViewById(R.id.restaurant_location);
    ImageButton phone = (ImageButton) concertView.findViewById(R.id.action_call);

    // getting restaurant data for the row
    Restaurant r = restaurantItems.get(position);

    // thumbnail image
    thumbNail.setImageUrl(r.getThumbnailUrl(), imageLoader);

    // title
    title.setText(r.getTitle());

    // type of food
    typeFood.setText(r.getTypeFood());

    // location of restaurant
    restaurantLocation.setText(r.getLocationRestaurant());

    // I GOT STUCK IN HERE
    // phone
    phone.setOnClickListener(new OnClickListener() {

    @Override
    public void onGetCall(View v) {
    // TODO Auto-generated method stub

    }
    });

    thank you 🙂

  • nasznjoka

    Hi @ravi8x:disqus you have never covered about multiple rows listview onitemclick implementation. Suppose I only want to take action when the image is clicked what the best way of doing that? What if I want the user to view the whole content from the link given i only show him/her the excerpt on the status place. how to go about that too on the same application not a browser

  • Joe Jo

    hello, could you please show me where you order the items ?

    like order by ASC or DESC.
    and the limitation or the items how do i set limit to something like only 5 items ?
    Thank You

    • silentmind

      no you can have as many as you want but make sure you do respective changes also in java files

  • silentmind

    Is it possible to make multiple jsonparser from multiple url in 1 android project?

    • Kaushal Saraf

      Yeah it is possible. You need separate Java Files for parsing diferent JSONObbjects and different URLs . If the JSON format is the same then one Java File will be enough.

      • silentmind

        can you provide me any working code for this. it would be helpful for me. if you can do this

  • rahul.khakse

    it’s amazing 🙂 it is possible to “Facebook Feed Like” into AndroidTab Fragment i try lot but i cant do please help me it that possible like Android Facebook App

    and
    Thank You Sharing Nice Android Tutorial

    • silentmind

      Ravi Sir is awesome ,teaching and helping many android developer for free.

    • EmileH2000

      This is exactly what i want to do

    • Noah

      Yes, please convert this to a Fragment!

  • silentmind

    hi ,ravi sir
    need your help

    how can we add refresh button to it. please help .

    you have always been our saviour . reply awaited

    thank you .

    • For that follow below steps.
      1. Have a refresh button with click event
      2. In the click event function make a call to server and get latest data and add it to listview source array list.
      3. Then call notify data set changed on adapter to update the list view recent data.

      • silentmind

        sir in your code i deleted following lines of code from main activity, so that i can make a fresh json request
        >>if (entry != null) {
        // fetch the data from cache
        try {
        String data = new String(entry.data, “UTF-8”);
        try {
        parseJsonFeed(new JSONObject(data));
        } catch (JSONException e) {
        e.printStackTrace();
        }
        } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        }

        } else {

        <<
        and rest of the main activity code i wrote in onclicklistener
        so when i am pressing it is calling fresh json again and again but its filing the refreshed list above old list.

        sir ,i got your point i tried using notifydatasetchanged but its not helping.

        • silentmind

          sir i don’t know how to delete the old item from the list view and add refreshed item in listview on onclickevent

          • Indra

            Add the following line in MainActivity-> parseJsonFeed->Just above the for loop…

            feedItems.clear();

            it should work fine

          • W Fabiian Rojas

            Amigo, pudiste agregar el boton?, Me Regalas el codigo?

  • Sudarshan Vidhate

    Hi Ravi, StringRequest doesnt run on 2.3.3 Gingerbread. Giving Error As :

    BasicNetwork.performRequest: Unexpected response code 411

    But it works on 4.0 & above.

  • silentmind

    ravi sir please tell me can we create multiple facebook like feeds , in a way you did it above. you have only one activity , i want to have 3 activities and each parsing json and with the help of button i’ll navigate through each one of them

    • EmileH2000

      This is exactly what i’m trying to do, but with fragments and I don’t know how to do it with fragments because in this tutorial it’s done in an Activity

      • silentmind

        are you able to do that now… ?
        mail me in this 040found@gmail.com
        if u have the code.

        • EmileH2000

          Yeah I now know how to do this, I’ll email you the code

          • Abyss

            Hi EmileH2000,

            Can u mail the code to me too? coz im doing it in fragment too. but tats some problem in FeedListAdapter.
            thank you.
            mail me at thegemini888@gmail.com

  • Raveen

    Hi,

    Your article is great, however there is one major mistake in listview usage. By right you should not set height of the listview is wrap_content, it is call onMeasure method every child is created. Hence, make it is 0dp and weight is 1.
    it will give best listview.

  • Cecile

    Hi there i like your tutorials but im having struggle to add the following.
    Can you tell me how to add extra options to this beautiful code?
    On the top right where u have added settings button i want it to look like this.
    -How to add a search filter for the json loaded data.

    For example if your json contains food, and if there where a search baar when pressed on menu.
    You would search for (Chicken) it will only load all posts with chicken.

    Can you show us how to?

    Thanks in advance

  • prakash

    How to use this tutorial to fetch any blogs data(xml) ? Which generate automatically along with any new post…. Here you are using predefine json file
    I want this app to load data dynamically … Can u help ?

    • Kaushal Saraf

      The JSON file can be made dynamic using PHP and Database to generate JSON and add to the database. And then you can parse JSON into the Application.

  • Michael

    anyone can help me with implement infinite scrollview to facebook like custom listview ;>

  • Guest

    Hi,
    I have been trying to implement the code you have put up for download. When i run it individually as a project it runs perfect. But when i am implementing it in another project it shows NullPointerException in FeedAdapter on the line where we are getting the ImageLoader from the instance in the AppController Class. Line 30 of FeedAdapter. Please help sir.

  • derulofm

    Hi Sir @ravi8x:disqus , i’ve

    been trying this codes with emulator and also physical tablet. Both are running in Honeycomb 3.2. Unfortunately the apps couldn’t run at all (force close at the starting). Has you or anyone else facing the same problem with me?

    I’ve been tried to run the this code using emulator targeted for ICS 4.0 and above, the apps is running perfectly.

    Thanks in advance for any guide and solutions

  • App Guru

    Could you do this with VideoView instead of ImageView?

  • Nikhil Tyagi

    I am using this feed with using fragment when i place api link of json file on my server it doesn’t showing data in app,,and if i place ur api link it is showing normally ,,help any suggestions??????

  • Asd

    Download link isn’t working.. could somebody please upload it somewhere and share the link? Thanks!

  • silentmind

    how to parse multiple facebook like feed in different activity in the same app.
    i tried doing that but app crashes due to some reason …log cat says .. null pointer exception i tried resolving this problem, but nothing helped

    sir ji , help me no?? give some time to your followers also no??

  • Tindi_

    HI Ravi. Great tutorial. I have replicated your code except from the ImageLoader. I’m getting a nullpointer exception on this line:

    // We first check for cached request
    Cache cache = AppController.getInstance().getRequestQueue().getCache();

    Error is 09-23 16:51:05.319: E/AndroidRuntime(15722): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.avanaya.volleycacheexample/com.avanaya.volleycacheexample.VolleyActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘com.android.volley.RequestQueue com.avanaya.volleycacheexample.AppController.getRequestQueue()’ on a null object reference

    What could be the issue?

  • I am getting a NullPointerException at this line: ImageLoader imageLoader = AppController.getInstance().getImageLoader(); .

    How to solve it?

    • Make sure that you added AppController in AndroidManifest.xml file to application tag.

    • silentmind

      even i was getting same error when i tried parsing 2 json that are identical to facebook like feed’s json

    • if you’re copying the project to your project.

      in the manifest file add this ..

      android:name=”com.blah.blah.listviewfeed.app.AppController”

      inside the application tag..

  • silentmind

    how to parse multiple facebook like feed in different activity in the same app.
    i
    tried doing that but app crashes due to some reason …log cat says ..
    null pointer exception i tried resolving this problem, but nothing
    helped

  • abhi

    How to get data in json dynamically? Can you please send the modified code?
    And also when i try to excess json from local host it doesnt display anything.. Please help me with this

  • utsav

    how can i setup onItemClickListner for this?

  • Joel || GetAvenue

    Thanks Ravi for all this great tutorials,

    I want to make the List Items Clickable to a WebView in another Activity.

    I added this to this Code on the MainActivity.java, but it is not working.

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
    try {
    JSONArray jsonPosts = response.getJSONArray(“feed”);
    JSONObject jsonPost = jsonPosts.getJSONObject(position);
    String bUrl = jsonPost.getString(“url”);
    Intent intent = new Intent(MainActivity.this, FacebookWebView.class);
    intent.setData(Uri.parse(bUrl));
    startActivity(intent);
    } catch (JSONException e) {
    Log.e(TAG, “Caught”, e);
    }
    }
    });

    another Activity or class
    FacebookWebView.java

    protected String mUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    Intent intent = getIntent();
    Uri bUri = intent.getData();
    mUri = bUri.toString();
    WebView web = (WebView)findViewById(R.id.webView1);
    web.loadUrl(mUri);

    I only noticed that the App crashes on the url with JSONObject value of “null” and LogCat is saying NullPointer Error which I understand, but Other List Item is not showing any sign of it being click-able.
    Sir, I want to know if I can change anything in any other class to make this work.

    Thanks alot, will be waiting for your reply

  • Denilson Marcelino

    Hi, I’m a developer from Brazil, I used your tutorial to made a feed in my app, that can show photos, videos, questions, or some text. I add to json a field called “type”, to identify the type of this item, if (item.getType() == “image”) it show FeedImageView, if == “text”, the imageview set visibility to View.GONE, but, when I scroll down or up, the imageview is created again in the item, appers blank and I haven’t any idea how to drop this error… Can you give me a help to make this 4 types of itens (image, text, video, question) ? Thanks, and sorry for my english, I have a very bad english 😀

  • Sanjay M

    Can anyone tel me how to use onResume method in fragment. I am using navigation drawer, in that while I am moving from one fragment to another and if I again come back to the same. The app is unfortunately getting closed. The onResume method is not working properly in android fragment. But this same method working fine in android activity. How to add life cycle methods properly???

    • Edwin

      I think your very limited with fragments, use activities instead of fragments for the nav drawer … You can use open source examples like the Google IO 2014 app to see how to use activities instead of fragments, heres the link to the google io 2014 app: https://github.com/google/iosched

  • Nihar Ranjan

    @Denilson Marcelino

    Hi,
    The basic concept of list view says it reuses views, thats why you are facing the problem.Instead of checking just one view to VISIBLE or GONE. Do it for both.
    ex- if (item.getType() == “image”)
    {
    imageView.setVisibility(View.VISIBLE);
    textView.setVisibility(View.GONE);
    }
    else if(item.getType() == “text”)
    {
    imageView.setVisibility(View.GONE);
    textView.setVisibility(View.VISIBLE);
    }

    • Denilson Marcelino

      No, if I scroll the list, imageview show again, in blank

  • waseem ahmad

    in this How to Use Post Method to fetch json

  • Trey Rosius

    One more useful tutorial which made me beat the last Huddle. Mr. Ravi, U R A VISSIONARY

    • Thanks Trey 🙂

      • Trey Rosius

        Hi Ravi can u please give me clue on how to convert the rectangular images to rounded cornered images.I had a look at this document on stackoverflow http://stackoverflow.com/questions/2459916/how-to-make-an-imageview-with-rounded-corners, but i don’t know how to apply it to ur custom listview with images and text using volley tutorial.It talks about Bitmaps, but i find imageLoader in customAdapter….I’ll appreciate any help.Thanks

        • Trey Rosius

          solved

      • Alplesh

        Ravi , In which format your date is stored?? i am having trouble understanding that. could you please help me here ?

  • Spark

    Thanks Ravi. How to use pagination by using volley if we have in url with more than 1 page?

  • Michael

    Hi there,

    I downloaded the code, and I just wanted to run it and check the feed out. However, when I download it straight off the zip file, I get several errors in the LruBitmapCache.java under the volley file. Is there a solution to this?

  • Görkem Karadoğan

    I have base64 or binary image string. How can i feed like that ? If String is big size, application can be frozen. How can i improve that stuation

  • Sanny Singhs

    Hi Ravi , is there a way to change the shape of square profile pic to rounded ?

  • gonza28

    I would create a second listview activity second. closes the app

  • Sugnesh

    Hi Ravi nice tutorial. I have implemented the code and its work perfect but feedImageView not set the height proper. It occupies the pervious views height and also not occupies proper image sizes.

  • Rodrigo Gonçalves

    Ravi, I don’t understand… I tried to mix this code to your Navigation Drawer code and I still can’t do it. Why is this happening? When we use Navigation drawer, are we supposed to create only fragments? If so, how can we “convert” this Volley class into a fragment? Why can’t we open Activities and still maintain the Navigation Drawer menu?

    Thanks in advance

    • Andrew

      I made some changes to my project, and it works for me in fragment with pull to refresh, maybe it can help.

      http://pastebin.com/5GtuSCvi

    • Didin

      i have same question, how to mix this code in navigation drawer code, Rodrigo did you was fix it now ?.

  • Salman

    Hey Ravi nice tutorial. I just implemented facebook feed with custom layout of yours but image quality is to too low. Please suggest how tom improve quality of image

  • Shin

    Hi, nice tutorial this helped to me a lot!!. with the json example this work but i try do with other json and i get null in “Entry entry = cache.get(URL_FEED);” where URL_FEED=”http://api.androidhive.info/contacts/” and i don’t know why (this is my first time with json)

  • mohamad hamieh

    hello everybody how i can encode from php mysql to json to obtain like this

    api.androidhive.info/feed/feed.json

    any help!!

    • Stefan

      Any luck with this issue?

    • Mehmetcan Tas

      your php code should be like this.
      This will be print your json feed according to your query

      $sql = “select * from “; // This is your sql
      $result = mysql_query($sql);
      $json = array();

      if(mysql_num_rows($result)>0){
      while($row=mysql_fetch_assoc($result)){
      $json[“feed”][]=$row;

      }

      print json_encode($json);
      }

  • George

    What I need to copy to make just the layout ???

    • George

      Got it .

  • Keshav

    How to dynamically add statuses/content to the newsfeed?

    • Stefan

      Any luck with this?

    • Mehmetcan Tas

      You need a database and bridge to communicate with it like mysq and php.
      For example, Create a db schema in mysql and php file.
      Sample php code is here, This will return a string in json object type.
      $sql = “select * from “; // This is your sql, you have to design it according to json object //elements.
      $result = mysql_query($sql);
      $json = array();

      if(mysql_num_rows($result)>0){
      while($row=mysql_fetch_assoc($result)){
      $json[“feed”][]=$row;

      }

      print json_encode($json);
      }

      In your MainActivity, In tutorial, it makes json request, you need to convert it StringRequest,(check it from Volley tutorial) that’s it.

      • Anas Kambali

        can you show the code on how to convert the json request to string request?

  • omid

    Hi I have a problem with this source Persian text I received from the server problem is when I was first loaded completely Persian Persian text displays, but the second time ??? Show me the utf-8 activity was defined as the main problem is what to do with my issue is resolved volley cach Persian text display Radrst
    help!!!!!

  • Stefan

    I’m not sure what the issue is, but when I amend my JSON file or add to it it does not update on teh app itself…… any help is very much appreciated. Thanks

    • Ahmet Talut Taşgıran

      I need also to this answer

  • aert

    when i try my own json i get a black screen everytime?

    • aqrty

      even if i don’t change anything in it still black screen but when i switch to default url you gave me it works fine? help?

  • Mehmetcan Tas

    ?

  • Guest

    First of all, thanks a lot for the awesome tutorials. My problem is when I run my project, I get a nullpointer exception error in the main activity. Has anyone else experienced this? And does anyone know how to solve the issue?

    • Mehmetcan Tas

      Check your json address and internet access of your device or emulator

      • Guest

        Was able to correct the problem, just started building the app again from scratch and I found so many errors I had made. Might you know how I can connect this app to localhost, I’ve created the necessary php scripts and database and I’m able to get the json on my localhost url but sadly I’m getting a blank screen when I try this on the app

        • Mehmetcan Tas

          I think, you reach the json via localhost/abc.php. In that case ,you dont reach json file, you reach json array as a String format. Therefore, you must do StringRequest instead of jsonObjectRequest. There are tutorial how to use StringRequest, after you get string, you can parse it.

          • Guest

            Thanks, I’ll try this and see if it works

  • wilson moraes dos santos

    Link of source is broken.. you can send me in : wilsontads@gmail.com or change and notify?

  • http://stackoverflow.com/questions/28756434/how-to-make-a-custom-clickable-by-index-sounds-easy-huh

    I’m trying this clickable

    according to item.getId()’s value.

    Can someone help me?

  • Sanjay Mewada

    nic article

  • Ravi you’re a beast!!! Check this out.

    http://stackoverflow.com/questions/28785284/how-to-avoid-this-pesky-indexoutofboundsexception-adding-items-to-json-array

    I’ve combines the Facebook and the Group Chat tutorials together. The issue is, item = feedItems.get(position); will throw the indexoutofboundsexceptions when you change the statusmessage textview to display the text of

    m.getMessage()

    from

    txtMsg.setText(m.getMessage());

    I’ve had the take the JSON variables from the POJO class from the FB tutorial and added the to the chat app POJO class, and manipulated the constructor.

    I’ve learned so much from these two tutorials!!! THANK YOU SO MUCH,

    should I add and append items to the JSON file, create a dynamic JSOn file inside the app, or use MYSQL (Which I don’t know how to do)?

  • GW

    Hi, I used your feed image view in a grid layout which I use to display an image gallery. When I scroll down the gallery and scroll back up images in the top of the grid layout are gone and it will not come back for a long time some times It wont. I saw you remove and cancel the request when the image detach from the window. Is there any way I can get the image back as quickly as possible.
    Thanks in advance.

  • John

    Hi, I am using the example but as fragment but does not work and i do not know how to change help me?

  • Guest

    Hello everybody, i am doing my dissertation for my final year. your tutorial is really great but when i am using it through the localhost a blank page is displayed in my emulator. someone can plzzz help me?

  • xalid

    Hello everybody, I’m using this tutorial for showing Persian or Kurdish language texts and for the first time when the app load texts, it’s shows in non define format but when I close the app and run it again it work well in correct format.
    In MainActivity when data get form cache it use UTF-8 but for new request not.
    how set UTF-8 encoding for new request?

    • xalid

      I solved my problem by changing below code in parseJsoneFeed():

      try {

      String txt =new String(feedObj.getString(“name”).getBytes(“ISO-8859-1”), “UTF-8”);

      item.setName(txt);

      } catch (UnsupportedEncodingException e) {

      // TODO Auto-generated catch block

      e.printStackTrace();

      }

      try {

      String txt =new String(feedObj.getString(“status”).getBytes(“ISO-8859-1”), “UTF-8”);

      item.setStatus(txt);

      } catch (UnsupportedEncodingException e) {

      // TODO Auto-generated catch block

      e.printStackTrace();

      }

      with this change texts shows in proper format.

  • Jack

    Hi, Thanks so much for this information. How do you use a username in shared preferences and select only post from that user. Please help or direct me to additional information.. Thanks in advance!

  • Ranjeet

    Hi,Thanks so much for this info.
    I want to know how can i set Tag to view(attach a post id) for performing further actions such as Like a post,comment on a post,delete and edit etc ?

  • Ardi Esta

    Amazing tutorial.. Thanks..

  • Ardi Esta

    How to adding command and like to list..

  • Sohil Dedhia

    Hey Ravi, This is a Fantastic Tutorial and I really love all the tutorials you have written. I want to show multiple images in every news feed post. How do I do that? Should I try GridView inside ListView. I am confused. Can you please help me out?

    • Sepaka Hlongwane

      I would recommend using viewpager with imageview if image slider is what you are looking for.

  • WaWaToR

    Hello everybody, Could someone please help me integreat Facebook Like Json Feed in the different tabs ? Thanks you
    Please help

  • Ed

    Hello everybody, Could somone please help me in this instruction:

    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    This returns me an error, I dont kno

    • Ed

      This returns me and error, I dont know what error is, the image is not downloaded or I have to setup a directory for cache image, because in the code not mentioned something about that.

      Please help

  • aris budiharto

    Hello.. when i change this “http://api.androidhive.info/feed/feed.json” to “http://mysite.com/index.php” i got error, but “http://mysite.com/feed.php” is OK. How chould this happen? Should i use “feed.???” or what..? Please Help..

    • Thomian ITClub

      don’t use php use json then it will work because this project only receive json script

  • karampal

    hello.. Ravi can you please give same tutorial using parse.com libs using cloud database …..

    • I’ll will be posted in 10days of time.

      • karampal

        thanks, yaar for reply……. and I am waiting ………

      • karampal

        10 days time completed. will you reply…..? please………!

  • Thomian ITClub

    hey my images not working on the app

  • Vanraj Vyas

    Where is R.layout.feed_item ???

  • Steve Curtis

    Your feed (feed.json) works perfectly but my json feed here won’t load. I don’t have any errors though. Any ideas?

    • Georgekutty George

      i check out ur url..its working fine…
      i am at the same problem..
      plz help me..

      • Steve Curtis

        Check your json file here: http://jsoneditoronline.org/ It will show you if there are any errors.

        • Georgekutty George

          kk…thsnks.error free now..

      • Steve Curtis

        See my reply to another comment above

        • Georgekutty George

          thanks..i got it…i use editors..

  • Shafil

    Hi Ravi,

    My list is displayed blank, when I use my own JSON file. It displays onErrorResponse in my logcat. I tried accessing the JSON file via browser and it return data as expected.

    Kindly help me on this.

    Regards,
    Shafil

    • Era Dwivedi

      Could you share the errorlog sentence. I could help if I know the error code. For starters if it is 500 then the url you are sending is wrong and it happens mostly when sending params in get or post request and I have a way to solve that

      • Georgekutty George

        i have the same problem..
        my json file not working..sme log
        r string cannot conveted to json object

    • Steve Curtis

      Try confirming your JSON file using this link: http://jsoneditoronline.org/ I had to view my json file there and only there did I find where the errors were.

  • Sam

    Are the best works fine for me

  • karampal

    can any one please tell how i add a progress bar before load whole page and also before image loading …….

    • Era Dwivedi

      progressDialog = new ProgressDialog(this);

      progressDialog.setMessage(“Loading…”);

      progressDialog.setCancelable(false);

      progressDialog.setCanceledOnTouchOutside(false);

      progressDialog.show();

      Something like this before your code for fecthing or displaying things and progressDialog.hide() after it

      • karampal

        Thanks…….!

  • android akt

    hello, can any one please tell if i can run Facebook Like FeedView on android 2.3.3 Gingerbread? if i simple change android:minSdkVersion=”11″ to “10” the app stops unexpectedly

  • Sam

    Hi all, can someone please show me how to add OnClickListener to the JSON item so i could pass the image and status through intent to another activity, Thanks in advance

    • I dont think we can implement onClickListener to JSON, instead you can implement for list view like this :

      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView arg0, View arg1, int arg2,
      long arg3) {

      // code

      }
      });

      • jaipal

        I Apply This Code But It was Not Working For All List onliy One Item Is Clickable

        • Andries Van Piitso

          I also had the same problem!

  • Neelam Hema

    why one one record is display in the list view??

  • Sepaka Hlongwane

    Hi Ravi,

    How do you covert mySQL timeStamp to “x hours Ago” ?

    • Sepaka Hlongwane

      İncase someone struggle with this. You will need to convert mysql timestamp to unix TimeStamp then use Ravi’s code as is to display x time ago.

  • Yogi Putra

    hy dude i have a problem converting datetime to unix timestamps , can you show me how to script conversion??

  • Why not take a look at my blog about how to create an Android app that displays an Image in an ImageView control of the main Activity at the full width of the screen.

    The app uses the following Android SDK objects:

    . LinearLayout
    . Bitmap
    . Activity
    . XML layout
    . ImageView
    . LayoutParams
    . Display

    Also:
    . layout_width
    . layout_height
    . orientation
    . id
    . vertical
    . match_parent

    XML attributes and values are covered.

    Click the link BELOW! to see

    http://androidprogrammeringcorner.blogspot.com/2015/06/pak-longs-android-programming-corner.html

  • Utkersh Reuben Khanna

    Awesome Tutorial Ravi but can you also guide me on how can i add a comment section below it That would be of great Help 😀

  • Nirmal Chaulagain

    Hey you did the great job and thanx alot for the great tutorial …. I have one question..After i run the app in online mode i could load the text even in offline mode but when i cleaned the cache memory through external app like “ES Task manager” the text will be cleared…is there a tricky code in android that helps me to clear cache only through mu own app setting or not to allow external app to clear my cache. Thanx in advance

  • Mwebembezi Dennis

    Does Putting a splash screen affect the application??

    • Peter Muchiri

      No it does not.

  • Brian

    hey guys. if i want to fetch the data using php & mysql

  • Mwebembezi Dennis

    07-10 09:59:24.495: E/AndroidRuntime(631): FATAL EXCEPTION: main

    07-10 09:59:24.495: E/AndroidRuntime(631): java.lang.NoClassDefFoundError: com.android.volley.toolbox.Volley

    07-10 09:59:24.495: E/AndroidRuntime(631): at com.fightcancer.AppController.getRequestQueue(AppController.java:33)

    07-10 09:59:24.495: E/AndroidRuntime(631): at com.fightcancer.AppController.getImageLoader(AppController.java:40)

    07-10 09:59:24.495: E/AndroidRuntime(631): at com.fightcancer.FeedListAdapter.(FeedListAdapter.java:24)

    07-10 09:59:24.495: E/AndroidRuntime(631): at com.fightcancer.MainActivity.onCreate(MainActivity.java:44)

    07-10 09:59:24.495: E/AndroidRuntime(631): at android.app.Activity.performCreate(Activity.java:4465)

    07-10 09:59:24.495: E/AndroidRuntime(631): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)

    07-10 09:59:24.495: E/AndroidRuntime(631): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)

    07-10 09:59:24.495: E/AndroidRuntime(631): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)

    07-10 09:59:24.495: E/AndroidRuntime(631): at android.app.ActivityThread.access$600(ActivityThread.java:122)

    07-10 09:59:24.495: E/AndroidRuntime(631): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)

    07-10 09:59:24.495: E/AndroidRuntime(631): at android.os.Handler.dispatchMessage(Handler.java:99)

    07-10 09:59:24.495: E/AndroidRuntime(631): at android.os.Looper.loop(Looper.java:137)

    07-10 09:59:24.495: E/AndroidRuntime(631): at android.app.ActivityThread.main(ActivityThread.java:4340)

    07-10 09:59:24.495: E/AndroidRuntime(631): at java.lang.reflect.Method.invokeNative(Native Method)

    07-10 09:59:24.495: E/AndroidRuntime(631): at java.lang.reflect.Method.invoke(Method.java:511)

    07-10 09:59:24.495: E/AndroidRuntime(631): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)

  • Ansari Sufiyan

    android framework is detected… whenever i open project i get this error… please help me

  • Mwas

    Thanks for this tutorial. Kindly email me the php code for the server side(http://api.androidhive.info/feed/feed.json) at simonmwangiwanjau@gmail.com

  • Gustav Lund

    Hi – um im having some difficulties adding this into a sliding menu – the other elements in the sliding menu arent clickable anymore (ergo this is overriding the sliding menu) – any tips? Cheers!

    • Give me your navigation drawer layout xml

      • Rahul kishan

        Ravi plz help me to do a server side program for this feed json

    • Meyka Jograt

      did you fix your problem? can you share it to me ? XD

      • Gustav Lund

        Ah sorry sorry for the late reply – vacation … But yeah no I haven’t been working on that yet but I’m interested in a solution haha

      • Meyka Jograt

        i fixed it :3

        • Gustav Lund

          Ahh could you post your solution pls?:)

  • Shane Okukenu

    Hey great but how do you connect your json to the real world so that when i give like a list of urls it gives back on the feed the latest from that site just like facebook??

  • Meyka Jograt

    Cool Tutorial! but i have a problem I implement this on Fragment Sliding Tab but its overriding the other Tab what i need to do to fix this?

  • Sandeep Gahlawat

    JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,URL_FEED,
    new Response.Listener()

    Here, it gives me an error saying error: incompatible types: int cannot be converted to String

    Thanks in advance.

  • Thanks. Cache method doesnt work. after downloading sample and run on phone. images can download and show on imageViews. but after disconnect from wifi and restart application all of images dont show. 😐 this cache mechanism how to work? i’m try to underestand it

  • Niyati Sharma

    Awesome Tutorial
    but
    New updates in db are not reflected in the app…what should i do to make that happen ?

  • vikranth kumar

    i am getting a blank feed after running the app..can anyone guess what might be the problem

  • Patricia Mai Yuki Pedro

    Ravi please help me how to use this with database?? :((

  • Meyka Jograt

    Ravi need some help here, how to make this real time?

  • Kunal Agrawal

    anyone pls help me to interate it with home fragment

  • Zlanfa Adulrafa

    awesome guy : i find about this article for long time . thk you so much

  • kashif

    hello first of all thanks 4 this buityfull post and i m new in developing android application my problem is that when i change your url(“http://api.androidhive.info/feed/feed.json”) to my server address(“http://kashifandroid.comyr.com/json/feed.json”) there is no feed is shown when app is launched…plz solve this prob i m very worried about that..thanks in advanced

  • kashif

    hello ravi sir i m new in developing android apps your post is very helpful to me and my prob is that ur entire code is work in my phone bt when i exchange your url to my server url in which your json file is uploaded is not show in my phone plz help me for sorting out this problem.thanks in advanced and sorry 4 my English.

  • Pratik Gondil

    App is not working…..

    10-31 12:12:31.031 6898-6898/com.example.dipali.facebooklikefeedview E/AndroidRuntime﹕ FATAL EXCEPTION: main

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dipali.facebooklikefeedview/com.example.dipali.facebooklikefeedview.MainActivity}: java.lang.NullPointerException

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)

    at android.app.ActivityThread.access$600(ActivityThread.java:130)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)

    at android.os.Handler.dispatchMessage(Handler.java:99)

    at android.os.Looper.loop(Looper.java:137)

    at android.app.ActivityThread.main(ActivityThread.java:4745)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:511)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

    at dalvik.system.NativeStart.main(Native Method)

    Caused by: java.lang.NullPointerException

    at com.example.dipali.facebooklikefeedview.MainActivity.onCreate(MainActivity.java:53)

    at android.app.Activity.performCreate(Activity.java:5008)

    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)

    at android.app.ActivityThread.access$600(ActivityThread.java:130)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)

    at android.os.Handler.dispatchMessage(Handler.java:99)

    at android.os.Looper.loop(Looper.java:137)

    at android.app.ActivityThread.main(ActivityThread.java:4745)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:511)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

    at dalvik.system.NativeStart.main(Native Method)

  • Fabi

    Why is “item.getId();” a Nullpointer?
    In my case i set the id from the full card layout to “fullCardItem” and then in the Adapter:
    fullCardItem.setId(item.getId()); but it is a Nullpointer

  • Bogdan Tudorascu

    Hello. I love your tutorial. How can I keep the feed after the app is destroyed and entered again ? Like instagram/facebook, they still have data even after you close the app and enter again. Could you take a look here http://stackoverflow.com/questions/33631429/instagram-like-app-realm-vs-cursorloader ?

  • Saunak Paul Choudhury

    Hello,

    The tutorials are really nice, they are really great.
    I have been trying to connect three of your tutorials together,
    1. Login using php
    2. Navigation drawer.
    3. Facebook like feed
    However when i open the drawer and click on the tab which has the FB like feed, it again takes me to the login screen.
    Can you please help me understand this.

  • Raza Akhter

    Very helpful tutorials ravi. can you please share a tutorial on listview with different row layouts(different list rows)

  • dsrtradefx

    Hello Ravi. This is a great tutorial. I am getting the null point exception error and I think it is because I have not added the AppController to application in the Manifest. I already have Facebook SDK there, so I cannot add a second instance. (Handles login to the application). I tried removing the Facebook SDK and replacing it with AppController in the manifest, but the app crashed on start. How would I add both Facebook SDK and AppController to the manifest?

    • dsrtradefx

      **Fixed. I extended the first application thru AppController and added AppController to the manifest.

  • Natiq Mustafa

    FATAL EXCEPTION: main

    Process: test.nato.fasebookfeed, PID: 6702

    java.lang.RuntimeException: Unable to start activity ComponentInfo{test.nato.fasebookfeed/test.nato.fasebookfeed.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)’ on a null object reference

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)

    at android.app.ActivityThread.-wrap11(ActivityThread.java)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:148)

    at android.app.ActivityThread.main(ActivityThread.java:5417)

    at java.lang.reflect.Method.invoke(Native Method)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)’ on a null object reference

    at test.nato.fasebookfeed.MainActivity.onCreate(MainActivity.java:53)

    at android.app.Activity.performCreate(Activity.java:6251)

    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)

    at android.app.ActivityThread.-wrap11(ActivityThread.java)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:148)

    at android.app.ActivityThread.main(ActivityThread.java:5417)

    at java.lang.reflect.Method.invoke(Native Method)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

  • Ashish Singh

    how did you generate the timestamp according to India’s GMT ?

  • Sam John

    HI, Great tutorial!
    I followed all the instruction on the page and have recreated the app on Andriod Studio. But when i run it i’m getting this error!

    Plz help..thx in advance!

    01-08 00:45:18.476 28023-28023/com.mysite.facebooklikefeed E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.mysite.facebooklikefeed, PID: 28023
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mysite.facebooklikefeed/com.mysite.facebooklikefeed.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)’ on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2477)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1345)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5415)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:725)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:615)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)’ on a null object reference
    at com.mysite.facebooklikefeed.MainActivity.onCreate(MainActivity.java:53)
    at android.app.Activity.performCreate(Activity.java:6162)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2370)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2477)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1345)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5415)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:725)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:615)

  • Sam John

    Hi, i’m getting this error when i run your code.
    Plz help…thank you in advance!

    01-08 00:45:18.476 28023-28023/com.mysite.facebooklikefeed E/AndroidRuntime: FATAL EXCEPTION: main

    Process: com.mysite.facebooklikefeed, PID: 28023

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mysite.facebooklikefeed/com.mysite.facebooklikefeed.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)’ on a null object reference

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2477)

    at android.app.ActivityThread.-wrap11(ActivityThread.java)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1345)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:148)

    at android.app.ActivityThread.main(ActivityThread.java:5415)

    at java.lang.reflect.Method.invoke(Native Method)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:725)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:615)

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)’ on a null object reference

    at com.mysite.facebooklikefeed.MainActivity.onCreate(MainActivity.java:53)

    at android.app.Activity.performCreate(Activity.java:6162)

    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2370)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2477)

    at android.app.ActivityThread.-wrap11(ActivityThread.java)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1345)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:148)

    at android.app.ActivityThread.main(ActivityThread.java:5415)

    at java.lang.reflect.Method.invoke(Native Method)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:725)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:615)

    • ashwani Janu

      try to remove the code which is used to change action bar color.

    • rafael rocha

      you need to add AppController in your manifest

  • Andries Van Piitso

    I tried to do onItemClick for the feeds buts i can only click first and second item only! my code looks like this:

    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView parent, View view, int position, long id) {
    Toast.makeText(getContext(), “aaaaa ” + position, Toast.LENGTH_SHORT).show();
    // FeedItem feedItem = feedItems.get(position);

    // Toast.makeText(rootView.getContext(), feedItem.getName(), Toast.LENGTH_SHORT).show();
    }
    });

    • Andries Van Piitso

      I got it 🙂

      You need to add : android:descendantFocusability=”blocksDescendants”

      in feed_list.xml

      • W Fabiian Rojas

        Amigo, Como Hiciste Pa Hacer “OnItemClickListener” ????

  • Prabhakar Purplepro Infotech

    in android studio i got an error like cannot resolve method ‘parseJsonFeed(org.json.JSONObject)

    • rafael rocha

      thats is because you need to add the method parseJsonFeed it is in the main activity outside of the oncreate.

  • rafael rocha

    someone knows how to save the timestamp in this format(13 digits ) like ravi? im tryin to load the feed from my database but the timestamp is in the wrong format thanks in advance!!

    • You can leave mysql timestamp as it is. Use the below function to achieve desired time format on Android.

      public static String getTimeStampMonthYear(String dateStr) {
      SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
      String timestamp = “”;
      try {
      Date date = format.parse(dateStr);

      format = new SimpleDateFormat(“MMMM, yyyy”);
      String date1 = format.format(date);

      timestamp = date1.toString();
      } catch (ParseException e) {
      e.printStackTrace();
      }

      return timestamp;
      }

      public static String getTimeStampOnWithoutTime(String dateStr) {
      SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
      String timestamp = “”;
      try {
      Date date = format.parse(dateStr);

      format = new SimpleDateFormat(“LLL dd, yyyy”);
      String date1 = format.format(date);

      timestamp = date1.toString();
      } catch (ParseException e) {
      e.printStackTrace();
      }

      return timestamp;
      }

      • rafael rocha

        ravi too much thanks, i´m almost done, but just one more question, if I modify my database, my feed, don´t update,could you guide me, to make the feed updateable?

        • Are you storing the feed in sqlite Database ?

          • rafael rocha

            no, I store the feed in mysql database and create the json with querys php

          • Then when there is a change in database, the json also changes right as you directly reading the data from db and printing in json.

          • rafael rocha

            thats right ravi, but i dont know why I need uninstall the app and run again to see those changes of database

          • Prem

            Hi Rafael Rocha,

            The data is stored in catch so you are not able to see those changes which is done in db, to achieve that you have use refresh layout and call your json method again.

          • rafael rocha

            ravi i’ll will try to do with you toturial of swipe down, i’ll hope can achieve!!! thaks for your greats toturials.

      • Michael Julyus Christopher M.

        My timestamp data is like this: 2017-05-23 19:13:37
        And I get error like this:
        java.lang.NumberFormatException: Invalid long: “2017-05-23 19:13:37”

        Is there solution to fix it? Or maybe someone know how can I covert my timestamp data into 13 digits like the example above?
        Thanks in advanvce.

  • Kwan_Gfriend

    I got a problem after i bring a listview to use in fragment( I try 3 hours but i cant fix please help me i am a beginning )
    Error
    Error:(63, 43) error: incompatible types: OneFragment cannot be converted to Activity
    Error:(74, 9) error: cannot find symbol class Entry
    Error:(90, 69) error: cannot find symbol variable GET

    Code OneFragment

    package com.kwan0563.myapplication;

    import android.annotation.SuppressLint;

    import android.graphics.Color;

    import android.graphics.drawable.ColorDrawable;

    import android.os.Bundle;

    import android.support.v4.app.Fragment;

    import android.view.LayoutInflater;

    import android.view.Menu;

    import android.view.View;

    import android.view.ViewGroup;

    import android.widget.ListView;

    import com.android.volley.Cache;

    import com.android.volley.Response;

    import com.android.volley.VolleyError;

    import com.android.volley.VolleyLog;

    import com.android.volley.toolbox.JsonObjectRequest;

    import com.kwan0563.myapplication.adapter.FeedListAdapter;

    import com.kwan0563.myapplication.app.AppController;

    import com.kwan0563.myapplication.data.FeedItem;

    import org.json.JSONArray;

    import org.json.JSONException;

    import org.json.JSONObject;

    import java.io.UnsupportedEncodingException;

    import java.lang.reflect.Method;

    import java.util.ArrayList;

    import java.util.List;

    /**

    * A simple {@link Fragment} subclass.

    */

    public class OneFragment extends Fragment {

    public OneFragment() {

    // Required empty public constructor

    }

    private static final String TAG = MainActivity.class.getSimpleName();

    private ListView listView;

    private FeedListAdapter listAdapter;

    private List feedItems;

    private String URL_FEED = “http://api.androidhive.info/feed/feed.json”;

    @SuppressLint(“NewApi”)

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

    Bundle savedInstanceState) {

    // Inflate the layout for this fragment

    return inflater.inflate(R.layout.fragment_one, container, false);

    listView = (ListView) getView().findViewById(R.id.list);

    feedItems = new ArrayList();

    listAdapter = new FeedListAdapter(this, feedItems);

    listView.setAdapter(listAdapter);

    // These two lines not needed,

    // just to get the look of facebook (changing background color & hiding the icon)

    //getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(“#3b5998”)));

    //getActionBar().setIcon(

    // new ColorDrawable(getResources().getColor(android.R.color.transparent)));

    // We first check for cached request

    Cache cache = AppController.getInstance().getRequestQueue().getCache();

    Entry entry = cache.get(URL_FEED);

    if (entry != null) {

    // fetch the data from cache

    try {

    String data = new String(entry.data, “UTF-8”);

    try {

    parseJsonFeed(new JSONObject(data));

    } catch (JSONException e) {

    e.printStackTrace();

    }

    } catch (UnsupportedEncodingException e) {

    e.printStackTrace();

    }

    } else {

    // making fresh volley request and getting json

    JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,

    URL_FEED, null, new Response.Listener() {

    @Override

    public void onResponse(JSONObject response) {

    VolleyLog.d(TAG, “Response: ” + response.toString());

    if (response != null) {

    parseJsonFeed(response);

    }

    }

    }, new Response.ErrorListener() {

    @Override

    public void onErrorResponse(VolleyError error) {

    VolleyLog.d(TAG, “Error: ” + error.getMessage());

    }

    });

    // Adding request to volley request queue

    AppController.getInstance().addToRequestQueue(jsonReq);

    }

    }

    /**

    * Parsing json reponse and passing the data to feed view list adapter

    * */

    private void parseJsonFeed(JSONObject response) {

    try {

    JSONArray feedArray = response.getJSONArray(“feed”);

    for (int i = 0; i < feedArray.length(); i++) {

    JSONObject feedObj = (JSONObject) feedArray.get(i);

    FeedItem item = new FeedItem();

    item.setId(feedObj.getInt("id"));

    item.setName(feedObj.getString("name"));

    // Image might be null sometimes

    String image = feedObj.isNull("image") ? null : feedObj

    .getString("image");

    item.setImge(image);

    item.setStatus(feedObj.getString("status"));

    item.setProfilePic(feedObj.getString("profilePic"));

    item.setTimeStamp(feedObj.getString("timeStamp"));

    // url might be null sometimes

    String feedUrl = feedObj.isNull("url") ? null : feedObj

    .getString("url");

    item.setUrl(feedUrl);

    feedItems.add(item);

    }

    // notify data changes to list adapater

    listAdapter.notifyDataSetChanged();

    } catch (JSONException e) {

    e.printStackTrace();

    }

    }

    // @Override

    // public boolean onCreateOptionsMenu(Menu menu) {

    // getMenuInflater().inflate(R.menu.main, menu);

    // return true;

    //}

    }

  • Kwan_Gfriend

    now i still cannot fix.. please help me.. i wanna use this pattern to many app in future i like design ..

  • sanajay

    how to load multipale image in feed? i added multipal image link like this

    “image”: “http://mysite.com/img1.jpg,http://mysite.com/img2.jpg” and i split in array and how to display now?

  • Jose Vicente Lucas Poveda

    Hi,

    Could you help me? How can i use a php script to obtain the Json data?

    I try with

    $row[‘field1’],
    “field2″=>$row[‘field2’],
    “field3″=>$row[‘field3’])
    );
    }
    //Displaying the array in json format
    echo json_encode($res);

    ?>

    But in the debugging , in the “Entry entry = cache.get(URL_FEED);” line, “entry” is allways null.

    Thanks in advance

  • Prem

    Hi Ravi,

    Grate tutorial thanks for it, i wanted to know whether we can add video play in volley as same as present Facebook play the videos ?

    • Hahaha I think he could not have done everything here… if you have learnt how to play videos in android then you can create your own json feed containing video.. for this you can use Glide library to cache video

  • Nystrom

    Hi, thanks alot. But i’ve a question, how to make rounded image for profilePic?

    • Use the below functions

      profilePic.setImageBitmap(getRoundedCornerBitmap(response.getBitmap(), dpToPx(response.getBitmap().getWidth())));

      public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
      Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
      .getHeight(), Bitmap.Config.ARGB_8888);
      Canvas canvas = new Canvas(output);

      final int color = 0xff424242;
      final Paint paint = new Paint();
      final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
      final RectF rectF = new RectF(rect);
      final float roundPx = pixels;

      paint.setAntiAlias(true);
      canvas.drawARGB(0, 0, 0, 0);
      paint.setColor(color);
      canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

      paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
      canvas.drawBitmap(bitmap, rect, rect, paint);

      return output;
      }

      public static int dpToPx(int dp) {
      DisplayMetrics displayMetrics = MyApplication.getInstance().getApplicationContext().getResources().getDisplayMetrics();
      int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
      return px;
      }

      • There are also libraries from github to make image round;

  • AVINASH KUMAR

    Hey, its the best blog for beginners like me. i wanna ask why don’t you post in Android Studio Platform??

    • These articles are written before Android Studio is in usage. All the recent articles are written using AS only.

      • AVINASH KUMAR

        Sir, can u please upload the same tutorial in AS ?? I’m having so much problem running in AS. I’m a beginner and i’m making a news feed app for college project. So need your help.

        • You need to first learn RecyclerView… The concept is simple if you give it time

  • AVINASH KUMAR

    package info.avinashke1.listview.volley;
    import com.android.volley.toolbox.ImageLoader.ImageCache;

    I’m getting error while importing above. Android Studio says cannot resolve “ImageLoader”. Help me out.

  • Amany Yehya

    please sir it is very good tutorial but I want to save data loaded in activity after close it when I resume it and there is no internet connection

  • Lakna

    It is indeed a great tutorial. Can you assist me on loading the newsfeed from another activity? Since there is an application class, I cannot figure how to do it

  • Capkin

    Hi, thanks for the tutorial. But i have a question, how can I covert the code till i show only my own facebook fanpage?

  • Kepi Agrawal

    Again thanx for tutorial. Its working fine.. but i think its not storing the images. as if i am scrolling down it will load the lower news feeds. but when i am going upward it will aain loadng the upper images.. why it is happening..? please help

  • Mahmoud Alsharif

    Ravi, Feed is ordered according to what ? Please reply.

  • Sharoon Amjid

    Yeeahh 😀 I did this with recyclerview which I had learned from your “working with recylcerview” blog and got success 😀 and the trick you mentioned to get the visibility gone for unavailable data is very good, overall it was very good for my knowledge Thanks buddy 🙂

    • I am glad you enjoyed the tutorial a lot.

    • Abhinav Soni

      can you share your recycler view code

  • Sridharan Natarajan

    How to make List view Bottom loading like facebook?

  • Yash Verma

    Hello sir, Thanks for his tutorial it is very useful for me.
    I’m a beginner for android development.
    My php code is not parsing
    so can you mail me your php code of this tutorial
    yash.verma1200@gmail.com

    • Joy

      hello Yash did he respond to you?

      • Yash Verma

        No

  • Joywin Missier

    Hello Ravi,When i change the feed url like this http://moviesglitz.in/PhotoUpload/getImg.php it does not load the feed plz help me

  • karampal

    when i use it in a fragment not in main activity. in the feedlistAdapter it show Cannot resolve method ‘getSystemService(java.lang.String)’

  • You have been ignoring downloading data and saving it to sqlite database to access last feed if network fails…. Aslo teach on how to use JobScheduler to create realtime json requests…

  • imran

    bro how did you get this kind of domain…please tell me…”http://api.androidhive.info/”…
    by the way thanks for helping me out great tutorial…
    and a small request how can we replace the
    ” private String URL_FEED = “http://api.androidhive.info/feed/feed.json”;”
    using json created using php and mysql..using our own server…..

    you had a tutorial on gcm chat application,where we can send push notification from wamp server….just like can we use the same in feed??

    help me out…

  • Dilip Poudel

    Can I get help plz . I am getting error while building gradle it says unable to delete directory and then it says cannot resolve symbol R, Appcompatactiviy, oncreate etc

    • public class “MainActivity” extends AppCompatActivity, problem solved.. 😉

  • imran

    how to create a json using php and mysql.the same feed which you have created…help me out..facing problems…can you please send me the code of that sql,php file..

  • imran

    http://www.immu.pe.hu/feed.json
    error in this json file help me out bro..plz help me in sending the code for generating json from phpmyadmin

  • Engin

    May I use Picasso instead of FeedImageView or NetworkImageLoader?

  • Sohan Kumar

    Hi Ravi & Eveyrone,

    How do I handle the click event of any object like Textview which is inside the list view ?

  • Ishu Mishra

    I wanna import my sliding menu code in this application how to do this i m confused please help

  • Sohan Kumar

    Hi,

    Using the above code from Ravi, I tried it … it works great !!! now how to get an bitmap image from the the loaded feedimageview .
    feedimageview return null.
    I want to use that image in other activity.
    can anyone help …
    thanks

  • Somanna

    Sir, I’m getting the following error when I try to build the App –

    Error:Execution failed for task ‘:app:transformClassesWithDexForDebug’.
    > com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process ‘command ‘C:Program FilesJavajdk1.8.0_65binjava.exe” finished with non-zero exit value 2

  • Samuel Guláš

    How can I change when app actuallizate the news

  • Deepak Rao

    Awesome example. How to combine this with pull to refresh list view?

  • Adnan Ahmed Khan

    I have updated this tutorial with RecyclerView, CardView, Retrofit 2.0 and Picasso 🙂
    you people might like it 🙂

    https://github.com/iamkhanshaheb/updateToAndroidHiveExample

    • $|R_MYK3

      i have download the app its nice and great but downgrade it to use api 23 and Libraries instead of 24 . which i do not have. welsha i really need your help, how can i implement drop-down refresh on the above am not a fan of android studio i prefer eclipse to it even due android studio fix error more than eclipse but my eclipse consumes less memory and builds app faster to android

    • $|R_MYK3

      the link is not click-able why i mean the like is visible but cant be clicked

  • $|R_MYK3

    THanks Nice

    • Edgar Tu

      If you were able to get this to work, could you share your solution? I am trying to do the same thing. Thank you.

  • $|R_MYK3

    I really need help please welsha since no one want to help me arrange the above code i used t separately and added if login-ed move to the other page if clicked am not good at coding but am trying and working hard in modifying thanks for all your tutorial

  • $|R_MYK3

    i have a problem while trying to combine the two program(One activity
    and One Fragment). I want to combine them in order to display in Tab(s).

    I want combine this two programs into one. the first one its a fragment with this example

    index.java

    public class Index extends Fragment implements OnClickListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View view = inflater
    .inflate(R.layout.blocks_fragment, container, false);
    return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
    Button newBlockButton = (Button) getActivity().findViewById(
    R.id.new_block_button);
    newBlockButton.setOnClickListener((OnClickListener) this);
    }

    @Override
    public void onClick(View v) {
    Intent intent = new Intent(getActivity(), LoginActivity.class);
    startActivity(intent);
    }
    }

    and this

    package info.androidhive.listviewfeed;

    public class feed extends Activity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List feedItems;
    private String URL_FEED = “http://crc.jsoncms.io/v2/objengine/ajax.php?objectname=feed”;

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

    listView = (ListView) findViewById(R.id.list);

    feedItems = new ArrayList();

    listAdapter = new FeedListAdapter(this, feedItems);
    listView.setAdapter(listAdapter);

    // These two lines not needed,
    // just to get the look of facebook (changing background color & hiding the icon)
    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(“#3b5998”)));
    getActionBar().setIcon(
    new ColorDrawable(getResources().getColor(android.R.color.transparent)));

    // We first check for cached request
    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Entry entry = cache.get(URL_FEED);
    if (entry != null) {
    // fetch the data from cache
    try {
    String data = new String(entry.data, “UTF-8”);
    try {
    parseJsonFeed(new JSONObject(data));
    } catch (JSONException e) {
    e.printStackTrace();
    }
    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    }

    } else {
    // making fresh volley request and getting json
    JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
    URL_FEED, null, new Response.Listener() {

    @Override
    public void onResponse(JSONObject response) {
    VolleyLog.d(TAG, “Response: ” + response.toString());
    if (response != null) {
    parseJsonFeed(response);
    }
    }
    }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
    VolleyLog.d(TAG, “Error: ” + error.getMessage());
    }
    });

    // Adding request to volley request queue
    AppController.getInstance().addToRequestQueue(jsonReq);
    }

    }

    /**
    * Parsing json reponse and passing the data to feed view list adapter
    * */
    private void parseJsonFeed(JSONObject response) {
    try {
    JSONArray feedArray = response.getJSONArray(“rows”);

    for (int i = 0; i < feedArray.length(); i++) {
    JSONObject feedObj = (JSONObject) feedArray.get(i);

    FeedItem item = new FeedItem();
    item.setId(feedObj.getInt("id"));
    item.setName(feedObj.getString("name"));

    // Image might be null sometimes
    String image = feedObj.isNull("image") ? null : feedObj
    .getString("image");
    item.setImge(image);
    item.setStatus(feedObj.getString("status"));
    item.setProfilePic(feedObj.getString("profilePic"));
    item.setTimeStamp(feedObj.getString("timeStamp"));

    // url might be null sometimes
    String feedUrl = feedObj.isNull("url") ? null : feedObj
    .getString("url");
    item.setUrl(feedUrl);

    feedItems.add(item);
    }

    // notify data changes to list adapater
    listAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
    e.printStackTrace();
    }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }
    }

    into one .java in terms if i open the app it will be inside a fragment

    thanks

  • hafizh

    i just following all of this tutorial and got error like this…
    Caused by: java.lang.NullPointerException
    at (My package name….).FeedListAdapter.(FeedListAdapter.java:29)
    at (My package name….).MainActivity.onCreate(MainActivity.java:46)

    where FeedListAdapter.java line 29 is

    ImageLoader imageLoader = AppController.getInstance().getImageLoader();
    and MainActivity.java line 46 is

    listAdapter = new FeedListAdapter(this, feedItems);
    hope u can help me fix this..thanks

    • Have you added AppController to AndroidManifest.xml ?

      • hafizh

        aw…forget that….thanks for answering

  • Rahul Jain

    how can i change time and date in the timestamp

  • iefans_saydie

    how to implemennt this directly to .php, not from .json??

    or I mean implement with .php parsing process?
    thank you so much for attention and guiden. 😀

  • Karim Dabour

    how i pass values to details activity ,Please

  • Kalpesh Kotadiya

    Very nice ..but whatsapp messaging page is used custom recycle ? ya Programmatically create view ?

    • You can keep multiple layouts xml files and inflate appropriate xml in recyclerview createView method.

  • Kemal Dara

    how to change json data model? My json file format is :
    {
    “data”: [
    {
    “id”: “117143901814932_543610879168230”,
    “name”: “Mynames”,
    “full_picture”: “picture”,
    “picture”: “profil_pic”,
    “created_time”: “(timeStamp) 2016-09-22T11:31:39+0000”,
    “link”: “url to the page”
    }
    }

    Use this json model on the apps

  • Subhash

    Hi Ravi can you please implement native LiveView tutorial for facebook in Android.

  • joshua mugisha

    great tutorial mate…..but i was wondering if you cud help and point me in the right direction in case i have a .php file instead of a .json thanks in advance.

  • Pavan

    Hi Ravi,
    Can you plz help me with onItemClickListener,as i can click on only 1st listitem,rest items are not getting data for click.
    Thanks
    in advance bro

  • Edgar Tu

    Ravi- Thank you for this tutorial. It’s helped me a lot to learn how to program Android. I’m making an attempt to convert this to RecyclerView. I’ve run into a sequencing problem. In your example, you Inflate the Layout, change the height all in getView. In your RecyclerView tutorial, you explain that you inflate the layout in onCreateViewHolder and set the data in onBindViewHolder. Since your custom FeedImageView (which changes the height with setLayoutParams) doesn’t get called until after onBindViewHolder, there is no height set during onCreateViewHolder, making the height -1. I think this is an unusual situation since FeedImageView is returning onSuccess much later. End result is the height of the items all stay the same. Please advise. Thank you

  • Kunal Agrawal

    Ravi thanks for this tutorial really help me a lot i was getting problem in converting sql time
    guys here i m posting solution that u can easily convert sql timestamp in feedlistadapter.java

    try {
    DateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
    Date d = dateFormat.parse(item.getTimeStamp());
    long millisec = d.getTime();
    CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
    millisec,System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS,DateUtils.FORMAT_ABBREV_RELATIVE);
    timestamp.setText(timeAgo);

    }catch (java.text.ParseException e) {
    e.printStackTrace();
    }

    • Sherwyn Cardozo

      thanx for the help but can u tell me how to dispplay the time in seconds cause when i just post it the time shows In 5 hr.

  • sharad lamba

    Thanks Ravi for such a great tutorial.
    I have one question will this listview refresh automatically if we add new data to mysql serve database. Or do we have to add something else.

  • donezio

    Thank you you this tutorial but I have a question.
    I try to request to volley in a fragment following this tutorial but somehow the request never get any response. Then the empty list that should be populated by the volley is passed to the adapter then my app crash. Any idea why this will happen?

  • Niranjan Reddy

    Thanks Ravi for a great tutorial.

    I want to set network image view as circle type … from server I getting images after , i want to set as circle type to network image view. How we can add to network image view … ?

    • Reinhard Jonathan

      you can create your own CustomCircleImageview, copy full java code from circleimageview library, and then put it in your java class named CustomCircleImageview, that extend NetworkImageView, and then, use your customcircleimageview in xml.

      You can call setImageUrl() from CustomCircleImageView object.

      sorry for my bad english…

    • Jamim Mehdi

      You can use this too. By placing the ImageView inside a CardView.
      Here’s the Code

  • MOHAMMAD MISBAH

    Hi Ravi- First of all I would like to thanks. I have implemented this for Feed Listing, all working fine but once issue is there i.e. some time image is rotating 90 degree. Whenever we view image directly from browser is it display in right rotation but in feed it rotating 90 degree. Can you please help for the same.

    • MOHAMMAD MISBAH

      Hello @Ravi & All, can anyone help me for the problem which I have described above, Please. I am unable to debug it and the issue is very critical.

        • MOHAMMAD MISBAH

          Thank you so much @ravi8x:disqus for your response. My issue is still not resolve, some observation I would like to share i.e. Image is uploaded by iPhone camera then same image is rotating in android but not in iOS feed and image which android camera is working fine without any issue. So problem is only when image we upload by iPhone camera.
          In pro-grammatically, I am getting orientation 0 i.e. ” ExifInterface.ORIENTATION_UNDEFINED” always.

          ExifInterface ei = new ExifInterface(photoPath);
          int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
          ExifInterface.ORIENTATION_UNDEFINED);

          and one problem if I am doing this I need image path which is not good for app.

          Please guide!

          • Then you have to fix the problem in iOS side. Also when the image is uploaded to server from iphone, how it’s visible in web browser when you open the image url?

          • MOHAMMAD MISBAH

            iOS guys denied that the problem is there end because when we open image url in browser, image is showing correct rotation as well same image in iOS app showing correct, but in android its rotation/tilt and when we capture image front camera of the iPhone, image rotate 180 degree. But I just came to a solution via using Glide Library with your FeedImageView’s code snippet. Thank you so much @ravi8x:disqus for your consideration and quick responses.

          • MOHAMMAD MISBAH

            Okay, Thank you once again for your consideration!!!

  • Arul Srinivaasan

    please help me sir,
    Error:(88, 41) error: reference to JsonObjectRequest is ambiguous
    both constructor JsonObjectRequest(int,String,String,Listener,ErrorListener) in JsonObjectRequest and constructor JsonObjectRequest(int,String,JSONObject,Listener,ErrorListener) in JsonObjectRequest match

  • Shalini Malviya

    Trying to create a custom list view in android of FB friends where user can select friends, but am not able to do so. Can you help?

    Can share the image in a mail.

    • Reinhard Jonathan

      you can create your own CustomCircleImageview, copy full java code from circleimageview library, and then put it in your java class named CustomCircleImageview, that extend NetworkImageView, and then, use your customcircleimageview in xml.

      You can call setImageUrl() from CustomCircleImageView object.

      sorry for my bad english.

  • Sourav Roy

    Works like charm but can’t set src or setImageBitmap, it seems as it is invisible… please help… I really need that… or I have to use ImageView instead of FeedImageView

  • dsrtradefx

    Hey Ravi. I built this tutorial end of 2015 and it worked great! I have been trying to modify it to utilize Firebase database with no luck so far. I need to be able to map the json file from firebase into this style feed. Can you show how that could be done?

  • Aishi

    how to make query dynamically for the newsfeed? can somebody help me with this? Thanks! 🙂

  • Miłosz Kramek

    Hi,
    I’ve got NullPointerException too. I want to make it a part of app – not whole app, so this MainActivity is “NewsFeedActivity”. Is there any method to avoid it?
    (same lines and same content as in previous comment):
    at FeedListAdapter.(FeedListAdapter.java:27)
    at onCreate(GalleryActivity.java:48)

    • Sherwyn Cardozo

      even i am getting same issue did u get a fix ?

      • Miłosz Kramek

        Nah, still looking. I think the problem is in Manifest, something like change intent category of (in my case) NewsFeedActivity to MAIN, but set MainActivity still as LAUNCHER.
        I’ll check it later, because I’ve got looots of work at school.

  • Aqsa

    avoid passing null as the view root.. how can i get rid of this..??

  • LDJStudios

    How can you add this to a Navigation Drawer… I got this code and the navigation to work. But my question is how can you make this Page show up with content from the .json file when you click on one of the menu items… I can get it to show the picture and text but not the content that I have setup with this code above… PLEASE HELP!

  • Abhinav Shukla

    hey the app bar is disabled??

  • Ken Choong

    This is such a great work…I learn a lot from you.

  • Ken Choong

    Sir just wanna ask,can i implement it in Recycle view?

  • Márcio Fornari

    Hello, Can i have to implement Swipe to Refresh too in this Example?

    • Ken Choong

      I just test it..is possible bro

  • Sagar Deshpande

    How do we handle pagination here? For example when requesting a facebook feed i get a next and a previous link.

    • Vince Urag

      That’s my problem too. 🙁

      Maybe we can store the ‘next’ link to a variable then use it to call the API on our onScrollListener?

  • Love Songs

    How to set up swiperefreshlayout to refresh the json feeds? Now it is just stay the same although you update feed.json. It is not getting updates from json. so help me please

  • Raj Roshan Singh

    Hi,
    Can you please help, how we can make each individual item that appears in feed clickable, so that when user clicks on any one, a new activity opens showing further more details about that item.
    Please respond soon. 🙂

  • Love Songs

    Ravi, really thanks for this tutorial. You are great. But I want to know how to use bufferreader to do like this.I meant loading .txt extension, not .json

  • NH channel

    Hi Ravi, thats good application.
    I just want to ask you, if I want to create same application but the image I want to display is 2 or more with the image slider. What solution you can give to me? The image is nested array. it maybe have no image, 1 image, 2 images,…

  • Anas Kambali

    Hi sir,
    i want to make like facebook status which means i can update my status and it will be listed in the json feed. How?

  • Nidhin

    Thanks for the wonderful tutorial, I have implemented this successfully but I need to implement onitemclicklistner I’ve tried the below one but now working. Can you help me to implement the onitemclicklistner in this application.

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_event, container, false);
    listView = (ListView) v.findViewById(R.id.list);
    listAdapter = new FeedListAdapterAll(getActivity(), feedItems);
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
    @Override
    public void onItemClick(AdapterView parent, View view,
    int position, long id) {
    // TODO Auto-generated method stub
    Toast.makeText(getContext(), “helo”, Toast.LENGTH_SHORT).show();
    }
    });
    return v;
    }

    Regards

  • ibrahim sh

    Hi thanks for the wonderful tutorial
    In this application images are not kept when you disconnect from the Internet as in the Facebook application, how it can be done

    • The image header should have expiry date. This can be done from the server.

      • ibrahim sh

        thank you very much ,but Do I need to use Disk Cache instead of Memory Cache as described in the Android manual (Caching Bitmaps )

  • ShadowDawn

    Hi thanks for the Tutorial

    But I have problem in loading images in offline using cache.Expect images all contents loading properly.

    Anyone Has suggestion on my problem please let me know.

    Thanks in advance

  • Susi krbs

    Hai,.. i am using sql server as backend, news contains images and youtube link in sql data, send code for sql server. thank u.

  • Nikhil Tulseja

    hi ravi,
    I have bottom navigation in my app. inside bottom navigation i am rendering a fragment for news feed. should i use recycler view or listview ? please suggest something.My news feed just looks like above mentioned feed in the tutorial.

  • ilya

    I dont understand how convert this into fragment.. I’ve read all answers but didn’t find a decision..
    Please Help!!

    I’ve got fatal exeption like this:

    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ilyab.section_4_my_profie_main_menu, PID: 7599
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ilyab.section_4_my_profie_main_menu/com.example.ilyab.section_4_my_profie_main_menu.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘com.android.volley.toolbox.ImageLoader com.example.ilyab.section_4_my_profie_main_menu.Motivation_feed_pckg.motivation_feed_appcontroller.AppController.getImageLoader()’ on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘com.android.volley.toolbox.ImageLoader com.example.ilyab.section_4_my_profie_main_menu.Motivation_feed_pckg.motivation_feed_appcontroller.AppController.getImageLoader()’ on a null object reference
    at com.example.ilyab.section_4_my_profie_main_menu.Motivation_feed_pckg.feed_adapter.FeedListAdapter.(FeedListAdapter.java:34)
    at com.example.ilyab.section_4_my_profie_main_menu.Motivation_feed_pckg.FeedActivity.initControls(FeedActivity.java:69)
    at com.example.ilyab.section_4_my_profie_main_menu.Motivation_feed_pckg.FeedActivity.onActivityCreated(FeedActivity.java:57)

    • Baronarama

      You seem to be having same problem as me, I fixed it with adding android:name=”.app.AppController” in my AndroidManifest.xml

  • Spartacus Gupta

    Hi Ravi, its a great tutorial.. successfully integrated in my app, had one problem – much higher resolution images not loaded into FeedImageView, got exception “Bitmap too large to be uploaded into a texture”. i had images with resolution 2437 x 3258.
    if i used android:largeHeap=”true” & android:hardwareAccelerated=”false” then it loaded successfully on custom view. but the problem is…. I also used custom textureview class for auto playing video So i changed it to android:hardwareAccelerated=”true”. i got stuck over there.Please suggest me…..
    Thankyou

  • Bill Mike

    Hi there Ravi. Is it possible to make this kind view with a Navigation Drawer on the side? Been trying to implement it, but it isn’t coming out as desired. Any help there? Thanks!

  • Baronarama

    Hm, since I’m using official volley from github I guess something has changed and this might be a bit outdated. Anyway I’m getting an error, can you see anything from it?

    FATAL EXCEPTION: main
    Process: testing.events.myapplication, PID: 9539
    java.lang.RuntimeException: Unable to start activity ComponentInfo{testing.events.myapplication/testing.events.myapplication.FeedActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘com.android.volley.toolbox.ImageLoader testing.events.myapplication.app.AppController.getImageLoader()’ on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘com.android.volley.toolbox.ImageLoader testing.events.myapplication.app.AppController.getImageLoader()’ on a null object reference
    at testing.events.myapplication.FeedListAdapter.(FeedListAdapter.java:33)
    at testing.events.myapplication.FeedActivity.onCreate(FeedActivity.java:52)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

    • Baronarama

      Found out my problem, I was missing android:name=”.app.AppController” in my AndroidManifest.xml

  • Siddhant Dube

    how to add a like button ??

  • MK

    Hi, thanks for the wonderful tutorial. I wanna ask how to add a view b/w these list items (posts) like facebook shows friend suggestion and ads b/w posts.

  • sathis

    sir.. How to do this example using server like display all of it in fetch from server….pls give the solution to reteive this all in server

  • Chìthläl KrísHná

    sir.. can i use a videoView and imageView simultaneously in ths example..?

  • yamini

    unfortunately,app has stopped.

  • Farouk Mohammad

    “Download Code” link doesn’t work!

  • prakash sarki

    profile pic and image is not shown.
    i am waiting for your reply

  • prakash sarki

    profile pic and image is not shown.
    i am waiting for your reply
    And its showing this error

    https://uploads.disquscdn.com/images/0a3542c78d64ad8e05139d3108085ff805b3820ffcd2722931072171937d7e26.png

  • Priyanka Patel

    sir.. can i use a videoView and imageView simultaneously in ths example..?

    Please reply me sir..

    • Yes, but you need to render Video View in adapter class.

  • prakash sarki

    hello Sir if we want to add like , comment and share like facebook how to do that

  • Abdelaziz Waheed Lasheen

    Hello Sir this code doesn’t work fine with me ,both profile pic and post pic failed to load https://uploads.disquscdn.com/images/2fde015a6377edc6ee3d42144ed91526c37e93c61834a2586088c1cf63557ca2.png

    • prakash sarki

      i also have the same problem

    • It’s may be https issue. I’ll check.