ListView Empty Message

When I first needed to set a message on a ListView that was empty, I tried different methods, but none of them worked, except the one that I will describe in this tutorial. So let’s start.

1.  Create an xml which will hold the ListView and name it “my_activity” and an activity called “MyActivity”.

2. Now, in the just created xml “my_activity”, you will have to set the ListView.  And right below the ListView, you will have to add a TextView. This will be used to display the empty message.

Important: The TextView must have as id the following name: “emptyElement”. This name is mandatory. The message won’t be displayed if you use another name.

This is how “my_activity” xml should look like:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"/>

    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/emptyElement"
        android:text="The list is empty"
        android:textStyle="bold"
        android:textSize="15sp"
        android:visibility="gone"
        android:layout_centerInParent="true"
          android:textColor="@android:color/darker_gray"/>

</RelativeLayout>

3. Create an xml for displaying items (when the list is not empty), and name it “list_item”.

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

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/list_item"
    android:gravity="center_vertical">


    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/list_item_text_view"
        android:textSize="20sp"
        android:padding="10dp"
        android:layout_marginLeft="5dp"/>

</LinearLayout>

4. Create a new Java class for the custom adapter which will be used by the ListView and name “MyCustomAdapter”. The code for the adapter is written below:

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;


public class MyCustomAdapter extends BaseAdapter {
    private ArrayList<String> mListItems;
    private LayoutInflater mLayoutInflater;

    public MyCustomAdapter(Context context, ArrayList<String> arrayList){

        mListItems = arrayList;

        //get the layout inflater
        mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        //getCount() represents how many items are in the list
        return mListItems.size();
    }

    @Override
    //get the data of an item from a specific position
    //i represents the position of the item in the list
    public Object getItem(int i) {
        return null;
    }

    @Override
    //get the position id of the item from the list
    public long getItemId(int i) {
        return 0;
    }

    @Override

    public View getView(int position, View view, ViewGroup viewGroup) {

        // create a ViewHolder reference
        ViewHolder holder;

        //check to see if the reused view is null or not, if is not null then reuse it
        if (view == null) {
            holder = new ViewHolder();

            view = mLayoutInflater.inflate(R.layout.list_item, null);
            holder.itemName = (TextView) view.findViewById(R.id.list_item_text_view);

            // the setTag is used to store the data within this view
            view.setTag(holder);
        } else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)view.getTag();
        }

        //get the string item from the position "position" from array list to put it on the TextView
        String stringItem = mListItems.get(position);
        if (stringItem != null) {
            if (holder.itemName != null) {
                //set the item name on the TextView
                holder.itemName.setText(stringItem);
            }
        }

        //this method must return the view corresponding to the data at the specified position.
        return view;

    }

    /**
     * Static class used to avoid the calling of "findViewById" every time the getView() method is called,
     * because this can impact to your application performance when your list is too big. The class is static so it
     * cache all the things inside once it's created.
     */
    private static class ViewHolder {

        protected TextView itemName;

    }
}

5. Now go to MyActivity class and add the code below:

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;


public class MyActivity extends Activity {

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

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

        // Create an empty array list of strings
        List<String> items = new ArrayList<String>();

        // Set the adapter
        MyCustomAdapter adapter = new MyCustomAdapter(items);
        listView.setAdapter(adapter);

        // Set the emptyView to the ListView
        listView.setEmptyView(findViewById(R.id.emptyElement));
    }
}

 

And this is it. Now, if you run the app you should see something like this:

ListView empty message

And if you populate the ArrayList of Strings, the message will disappear and the list items will be displayed.  (You can use a for statement in MyActivity where the empty array was created in order to populate the array of strings)

for (int i = 0; i < 5; i++) {
            items.add("Item " + i);
        }

populated listView

So in conclusion, when you want to show a message to the user when the ListView is empty, you have to keep in mind the following 3 steps:

  • In the xml where the ListView is declared, create a TextView (the TextView can be inside a LinearLayout if you want) right below the ListView
  • Set the TextView’s id as “emptyElement”
  • And inside the activity, set the setEmptyView() property to the ListView

Add CardView to Android OS versions below L ()

You might notice the new CardView widget on Android L preview presentation. The view can be used to display text or images and has a nice shadow.

You can add that view into your project even if you don’t have the minimum API level to “L”… to do that, follow the steps below:

1.  Edit your gradle.build file to:

dependencies {
    // your other dependencies
    compile 'com.android.support:cardview-v7:21.+' // this will load the CardView
}

2. Edit your manifest file and add the following tag

<uses-sdk tools:node="replace" />

Make sure you import the XML schema first in the main tag:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 package="com.yourpackage" >

You might remember that from a previous post.
That will help you fix the Manifest.xml merging issue and avoid the following error:

Error:Execution failed for task ':TestApp:processDebugManifest'.
> Manifest merger failed : uses-sdk:minSdkVersion 14 cannot be smaller than version L declared in library com.android.support:cardview-v7:21.0.0-rc1

3. Use the CardView from the package: android.support.v7.widget like this:

<android.support.v7.widget.CardView
 android:id="@+id/some_card_view"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_alignParentLeft="true">
<LinearLayout
 android:id="@+id/some_view"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"/>
</android.support.v7.widget.CardView>

That should be all :)

 

 

Android L: RecyclerView Tutorial

Hi,  in today’s tutorial I will show you how to create a list with the newest widget presented at Google I/O 2014, RecyclerView. Also I will show how to add click and long click events within adapter.

WHAT’S DIFFERENT?

  • is a more advanced and flexible version of ListView
  • it forces the implementation of ViewHolde pattern
  • the recycling process is more efficient
  • before you had to create only the ListView and the Adapter, now you have to create the ListView, a LayoutManager and the Adapter.
  • the LayoutManager avoids the calling of findViewById for too many times

 

1. Create a new project and name your main activity MyActivity. (At this step do not write anything in this class).

NOTE: Create your project to support Android L Preview. If you do not have the Android L sdk you can download it from SDK manager.  Your build.gradle file should look like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 'android-L'
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 'L'
        targetSdkVersion 'L'
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:recyclerview-v7:+'
}

2.  Create an xml (or rename the generated one) and name it “my_activity_layout.xml”.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

3. Create a new xml and name it “item_row.xml”

<?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="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:id="@+id/layout">

    <TextView
        android:id="@+id/rowNumberTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/nameTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

4. Create a new java class for the adapter and name it “MyCustomAdapter”

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.ViewHolder> implements View.OnClickListener,
        View.OnLongClickListener{

    private ArrayList<String> mDataset;
    private static Context sContext;

    // Adapter's Constructor
    public MyCustomAdapter(Context context, ArrayList<String> myDataset) {
        mDataset = myDataset;
        sContext = context;
    }

    // Create new views. This is invoked by the layout manager.
    @Override
    public MyCustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        // Create a new view by inflating the row item xml.
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_row, parent, false);

        // Set the view to the ViewHolder
        ViewHolder holder = new ViewHolder(v);
        holder.mNameTextView.setOnClickListener(MyCustomAdapter.this);
        holder.mNameTextView.setOnLongClickListener(MyCustomAdapter.this);

        holder.mNameTextView.setTag(holder);

        return holder;
    }

    // Replace the contents of a view. This is invoked by the layout manager.
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        holder.mNumberRowTextView.setText(String.valueOf(position) + ". ");
        // Get element from your dataset at this position and set the text for the specified element
        holder.mNameTextView.setText(mDataset.get(position));

        // Set the color to red if row is even, or to green if row is odd.
        if (position % 2 == 0) {
            holder.mNumberRowTextView.setTextColor(Color.RED);
        } else {
            holder.mNumberRowTextView.setTextColor(Color.GREEN);
        }
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    // Implement OnClick listener. The clicked item text is displayed in a Toast message.
    @Override
    public void onClick(View view) {
        ViewHolder holder = (ViewHolder) view.getTag();
        if (view.getId() == holder.mNameTextView.getId()) {
            Toast.makeText(sContext, holder.mNameTextView.getText(), Toast.LENGTH_SHORT).show();
        }
    }

    // Implement OnLongClick listener. Long Clicked items is removed from list.
    @Override
    public boolean onLongClick(View view) {
        ViewHolder holder = (ViewHolder) view.getTag();
        if (view.getId() == holder.mNameTextView.getId()) {
            mDataset.remove(holder.getPosition());

            // Call this method to refresh the list and display the "updated" list
            notifyDataSetChanged();

            Toast.makeText(sContext, "Item " + holder.mNameTextView.getText() + " has been removed from list",
                    Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    // Create the ViewHolder class to keep references to your views
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mNumberRowTextView;
        public TextView mNameTextView;

        /**
         * Constructor
         * @param v The container view which holds the elements from the row item xml
         */
        public ViewHolder(View v) {
            super(v);

            mNumberRowTextView = (TextView) v.findViewById(R.id.rowNumberTextView);
            mNameTextView = (TextView) v.findViewById(R.id.nameTextView);
        }
    }
}

5. Go to your “MyActivity” class and add the following code:

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;

public class MyActivity extends Activity {

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

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // improve performance if you know that changes in content
        // do not change the size of the RecyclerView
        recyclerView.setHasFixedSize(true);

        // use a linear layout manager
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);

        // Data set used by the adapter. This data will be displayed.
        ArrayList<String> myDataset = new ArrayList<String>();
        for (int i= 0; i < 70; i++){
            myDataset.add("Diana " + i);
        }

        // Create the adapter
        RecyclerView.Adapter adapter = new MyCustomAdapter(MyActivity.this, myDataset);
        recyclerView.setAdapter(adapter);
    }
}

Create an emulator which can run Android L (Api Level 20) and run the app.

RecyclerView