How To Show Data From SQLite Database In Android ListView

This article contains examples about how to operate SQLite database table data via android ListView control. It shows how to load, add, edit, delete and refresh rows in android ListView while save the modified result data back to SQLite database table.

1. Operate ListView Row With SQLite DB Example Demo.

load add edit delete lisview data from sqlite database table example demo

When the example start, it will load and show user account data in the list view. The user account data is saved in SQLite database file UserInfo.db

Run below command in dos window to change the folder access permission.

C:\Users\Jerry>adb shell
generic_x86:/ $ su
generic_x86:/ # chmod 777 /data
generic_x86:/ # chmod 777 /data/data
generic_x86:/ # chmod 777 /data/data/com.dev2qa.example
generic_x86:/ # chmod 777 /data/data/com.dev2qa.example/databases

Then you can see the UserInfo.db file saved in /data/data/com.dev2qa.example/databases folder use android device monitor.

android device monitor sqlite database userinfo db file

Please refer article Android Device Monitor Cannot Open Data Folder Resolve Method for more detail.

Run below command in a dos window to show UserInfo.db tables definition and row data in it.

127|generic_x86:/ # sqlite3 /data/data/com.dev2qa.example/databases/UserInfo.db
SQLite version 3.9.2 2015-11-02 18:31:45
Enter ".help" for usage hints.
sqlite> .schema
CREATE TABLE android_metadata (locale TEXT);
CREATE TABLE account( _id integer primary key autoincrement,user_name text,password text,email text );
sqlite> select * from account;
1|jerry|jerry|[email protected]
3|tom|tom|[email protected]

Please note the table account’s primary key column name should be ‘_id’, otherwise when you use SimpleCursorAdapter to bind the data to listview, there will prompt “java.lang.IllegalArgumentException: column ‘_id’ does not exist” exception.

There are three buttons in the action bar. You can click each button to add a new user account, edit a checked user account and delete all selected user account.

2. Source Code.

For database table operation source code, please refer article How To Write Reusable Code For Android SQLite Database. That article introduce how to write reusable java class to process SQLite database table operations.

There are four java classes, one layout xml file and one menu xml file in this example.

operate sqlite database table data in listview java source file

2.1 Main Activity Java File.

UserAccountListViewActivity.java

This is the main activity, it shows the ListView control and three button in the action bar.

package com.dev2qa.example.storage.sqlite.listview;

import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.dev2qa.example.R;

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

public class UserAccountListViewActivity extends AppCompatActivity {

    private UserInfoDBManager userInfoDBManager = null;

    private ListView userAccountListView = null;

    private TextView userAccountListEmptyTextView = null;

    private SimpleCursorAdapter listViewDataAdapter = null;

    private final String fromColumnArr[] = {UserInfoDBManager.TABLE_ACCOUNT_COLUMN_ID, UserInfoDBManager.TABLE_ACCOUNT_COLUMN_USERNAME, UserInfoDBManager.TABLE_ACCOUNT_COLUMN_PASSWORD, UserInfoDBManager.TABLE_ACCOUNT_COLUMN_EMAIL};

    private final int toViewIdArr[] = {R.id.user_account_list_item_id, R.id.user_account_list_item_user_name, R.id.user_account_list_item_password, R.id.user_account_list_item_email};

    // Store user checked account DTO.
    private List<UserAccountDTO> userCheckedItemList = new ArrayList<UserAccountDTO>();

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

        setTitle("dev2qa.com - Show Table Rows In List View");

        userAccountListView = (ListView)findViewById(R.id.user_account_list_view);
        userAccountListEmptyTextView = (TextView)findViewById(R.id.user_account_list_empty_text_view);
        userAccountListView.setEmptyView(userAccountListEmptyTextView);

        // Get SQLite database query cursor.
        userInfoDBManager = new UserInfoDBManager(getApplicationContext());
        userInfoDBManager.open();
        Cursor cursor = userInfoDBManager.getAllAccountCursor();

        // Create a new SimpleCursorAdapter.
        listViewDataAdapter = new SimpleCursorAdapter(this, R.layout.activity_user_account_list_view_item, cursor, fromColumnArr, toViewIdArr, CursorAdapter.FLAG_AUTO_REQUERY);
        //listViewDataAdapter.notifyDataSetChanged();

        // Set simple cursor adapter to list view.
        userAccountListView.setAdapter(listViewDataAdapter);

        // When list view item is clicked.
        userAccountListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int index, long viewId) {
                // Get list view item SQLiteCursor object.
                Object clickItemObject = adapterView.getAdapter().getItem(index);
                SQLiteCursor cursor = (SQLiteCursor)clickItemObject;

                // Get row column data.
                int rowId = cursor.getInt(cursor.getColumnIndex(UserInfoDBManager.TABLE_ACCOUNT_COLUMN_ID));
                String userName = cursor.getString(cursor.getColumnIndex(UserInfoDBManager.TABLE_ACCOUNT_COLUMN_USERNAME));
                String password = cursor.getString(cursor.getColumnIndex(UserInfoDBManager.TABLE_ACCOUNT_COLUMN_PASSWORD));
                String email = cursor.getString(cursor.getColumnIndex(UserInfoDBManager.TABLE_ACCOUNT_COLUMN_EMAIL));

                // Create a UserAccountDTO object to save row column data.
                UserAccountDTO userAccountDto = new UserAccountDTO();
                userAccountDto.setId(rowId);
                userAccountDto.setUserName(userName);
                userAccountDto.setPassword(password);
                userAccountDto.setEmail(email);

                // Get checkbox object.
                CheckBox itemCheckbox = (CheckBox) view.findViewById(R.id.user_account_list_item_checkbox);
                boolean checkboxChecked = false;
                if(itemCheckbox.isChecked())
                {
                    itemCheckbox.setChecked(false);
                    checkboxChecked = false;
                }else
                {
                    itemCheckbox.setChecked(true);
                    checkboxChecked = true;
                }

                // Add ( or remove ) userAccountDto from the instance variable userCheckedItemList.
                addCheckListItem(userAccountDto, checkboxChecked);

                // Show user select list view item id.
                Toast.makeText(getApplicationContext(),"Select id : " + getUserCheckedItemIds(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String getUserCheckedItemIds()
    {
        StringBuffer retBuf = new StringBuffer();

        if(userCheckedItemList!=null)
        {
            int size = userCheckedItemList.size();
            for(int i=0;i<size;i++)
            {
                UserAccountDTO tmpDto = userCheckedItemList.get(i);
                retBuf.append(tmpDto.getId());
                retBuf.append(" ");
            }
        }

        return retBuf.toString().trim();
    }

    /*
    *  Add user checked account dto to userCheckedItemList variable.
    *  userAccountDto : User selected account dto.
    *  add : true - add, false - remove.
    * */
    private void addCheckListItem(UserAccountDTO userAccountDto, boolean add)
    {
       if(userCheckedItemList!=null)
       {
           boolean accountExist = false;
           int existPosition = -1;

           // Loop to check whether the user account dto exist or not.
           int size = userCheckedItemList.size();
           for(int i=0;i<size;i++)
           {
               UserAccountDTO tmpDto = userCheckedItemList.get(i);
               if(tmpDto.getId() == userAccountDto.getId())
               {
                   accountExist = true;
                   existPosition = i;
                   break;
               }
           }

           if(add)
           {
               // If not exist then add it.
               if(!accountExist)
               {
                   userCheckedItemList.add(userAccountDto);
               }
           }else
           {
               // If exist then remove it.
               if(accountExist)
               {
                   if(existPosition!=-1)
                   {
                       userCheckedItemList.remove(existPosition);
                   }
               }
           }
       }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the action bar menu.
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.action_bar_add_edit_delete_example, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if(itemId == R.id.menu_add)
        {
            UserAccountAddActivity.start(getApplicationContext(), -1, "", "", "");
        }else if(itemId == R.id.menu_edit)
        {
            if(userCheckedItemList!=null)
            {
                int size = userCheckedItemList.size();
                if(size!=1)
                {
                    Toast.makeText(this, "Please select one row to edit.", Toast.LENGTH_SHORT).show();
                }else
                {
                    UserAccountDTO tmpDto = userCheckedItemList.get(0);
                    UserAccountAddActivity.start(getApplicationContext(), tmpDto.getId(), tmpDto.getUserName(), tmpDto.getPassword(), tmpDto.getEmail());
                }
            }
        }else if(itemId == R.id.menu_delete)
        {
            if(userCheckedItemList!=null) {
                int size = userCheckedItemList.size();

                if(size==0)
                {
                    Toast.makeText(this, "Please select at least one row to delete.", Toast.LENGTH_SHORT).show();
                }else {
                    for (int i = 0; i < size; i++) {
                        UserAccountDTO tmpDto = userCheckedItemList.get(i);
                        userInfoDBManager.deleteAccount(tmpDto.getId());

                        userCheckedItemList.remove(i);

                        size = userCheckedItemList.size();
                        i--;
                    }

                    // Reload user account data from SQLite database.
                    Cursor cursor = userInfoDBManager.getAllAccountCursor();
                    listViewDataAdapter = new SimpleCursorAdapter(this, R.layout.activity_user_account_list_view_item, cursor, fromColumnArr, toViewIdArr, CursorAdapter.FLAG_AUTO_REQUERY);
                    //listViewDataAdapter.notifyDataSetChanged();
                    // Set new data adapter to lise view.
                    userAccountListView.setAdapter(listViewDataAdapter);
                }
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(userInfoDBManager!=null)
        {
            userInfoDBManager.close();
            userInfoDBManager = null;
        }
    }
}

2.2 Add / Edit User Account Activity.

UserAccountAddActivity.java

This activity will be shown when user add a new or edit an exist user account row in the listview control.

package com.dev2qa.example.storage.sqlite.listview;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dev2qa.example.R;

public class UserAccountAddActivity extends AppCompatActivity {

    private UserInfoDBManager userInfoDBManager = null;

    private static final String INPUT_ID = "INPUT_ID";

    private static final String INPUT_USER_NAME = "INPUT_USER_NAME";

    private static final String INPUT_PASSWORD = "INPUT_PASSWORD";

    private static final String INPUT_EMAIL = "INPUT_EMAIL";

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

        setTitle("dev2qa.com - Add User Account.");

        // Get user account editor control.
        final EditText userAccountUserNameEditor = (EditText)findViewById(R.id.user_account_edit_username);
        final EditText userAccountPasswordEditor = (EditText)findViewById(R.id.user_account_edit_password);
        final EditText userAccountEmailEditor = (EditText)findViewById(R.id.user_account_edit_email);

        // Get input extra user account data from UserAccountListViewActivity activity.
        Intent intent = getIntent();
        final int userId = intent.getIntExtra(INPUT_ID, -1);
        String userName = intent.getStringExtra(INPUT_USER_NAME);
        String password = intent.getStringExtra(INPUT_PASSWORD);
        String email = intent.getStringExtra(INPUT_EMAIL);

        // Can not edit existed user name.
        if(userId!=-1)
        {
            userAccountUserNameEditor.setText(userName);
            userAccountUserNameEditor.setEnabled(false);

            userAccountPasswordEditor.setText(password);
            userAccountEmailEditor.setText(email);
        }

        // Open SQLite database connection.
        userInfoDBManager = new UserInfoDBManager(getApplicationContext());
        userInfoDBManager.open();

        Button saveUserAccountButton = (Button)findViewById(R.id.user_account_button_save);
        saveUserAccountButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String userName = userAccountUserNameEditor.getText().toString();
                String password = userAccountPasswordEditor.getText().toString();
                String email = userAccountEmailEditor.getText().toString();

                StringBuffer errorMessageBuf = new StringBuffer();

                if(TextUtils.isEmpty(userName))
                {
                    errorMessageBuf.append("Username can not be empty./r/n");
                }else if(TextUtils.isEmpty(userName))
                {
                    errorMessageBuf.append("Password can not be empty./r/n");
                }else if(TextUtils.isEmpty(userName))
                {
                    errorMessageBuf.append("Email can not be empty./r/n");
                }

                if(errorMessageBuf.length() > 0)
                {
                    Toast.makeText(getApplicationContext(), errorMessageBuf.toString(), Toast.LENGTH_SHORT).show();
                }else {

                    if(userId==-1) {
                        // Insert new user account.
                        userInfoDBManager.insertAccount(userName, password, email);
                    }else
                    {
                        // Update exist user account.
                        userInfoDBManager.updateAccount(userId, password, email);
                    }

                    Toast.makeText(getApplicationContext(), "User account is saved successfully.", Toast.LENGTH_SHORT).show();
                    finish();

                    Intent startUserAccountListIntent = new Intent(getApplicationContext(), UserAccountListViewActivity.class);
                    startUserAccountListIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(startUserAccountListIntent);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(userInfoDBManager!=null)
        {
            userInfoDBManager.close();
            userInfoDBManager = null;
        }
    }

    // Start this activity from other class.
    public static void start(Context ctx, int id, String userName, String password, String email)
    {
        Intent intent = new Intent(ctx, UserAccountAddActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(INPUT_ID, id);
        intent.putExtra(INPUT_USER_NAME, userName);
        intent.putExtra(INPUT_PASSWORD, password);
        intent.putExtra(INPUT_EMAIL, email);
        ctx.startActivity(intent);
    }
}

2.3 User Account Database Manager.

UserInfoDBManager.java

This java class will focus on user account database operations. It will reuse DatabaseManager class that is introduced in article How To Write Reusable Code For Android SQLite Database.

package com.dev2qa.example.storage.sqlite.listview;

import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

import com.dev2qa.example.storage.sqlite.util.DatabaseManager;
import com.dev2qa.example.storage.sqlite.util.TableColumn;

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

/**
 * Created by Jerry on 1/17/2018.
 */

public class UserInfoDBManager {

    private Context ctx;

    private DatabaseManager dbManager;

    private static final String DB_NAME = "UserInfo.db";

    private static final String TABLE_NAME_ACCOUNT = "account";

    // SQLite database need table primary key column named as _id. Otherwise a "java.lang.IllegalArgumentException: column '_id' does not exist" exception will be thrown.
    public static final String TABLE_ACCOUNT_COLUMN_ID = "_id";

    public static final String TABLE_ACCOUNT_COLUMN_USERNAME = "user_name";

    public static final String TABLE_ACCOUNT_COLUMN_PASSWORD = "password";

    public static final String TABLE_ACCOUNT_COLUMN_EMAIL = "email";

    private int DB_VERSION = 1;

    List<String> tableNameList = null;

    List<String> createTableSqlList = null;

    public UserInfoDBManager(Context ctx) {
        this.ctx = ctx;
        this.init();
        this.dbManager = new DatabaseManager(ctx, this.DB_NAME, this.DB_VERSION, this.tableNameList, this.createTableSqlList);
    }

    private void init()
    {
        if(this.tableNameList==null)
        {
            this.tableNameList = new ArrayList<String>();
        }

        if(this.createTableSqlList==null)
        {
            this.createTableSqlList = new ArrayList<String>();
        }

        this.tableNameList.add(TABLE_NAME_ACCOUNT);

        // Build create account table sql.
        StringBuffer sqlBuf = new StringBuffer();

        // Create table sql.
        sqlBuf.append("create table ");
        sqlBuf.append(TABLE_NAME_ACCOUNT);
        sqlBuf.append("( ");
        sqlBuf.append(TABLE_ACCOUNT_COLUMN_ID);
        sqlBuf.append(" integer primary key autoincrement,");
        sqlBuf.append(TABLE_ACCOUNT_COLUMN_USERNAME);
        sqlBuf.append(" text,");

        sqlBuf.append(TABLE_ACCOUNT_COLUMN_PASSWORD);
        sqlBuf.append(" text,");

        sqlBuf.append(TABLE_ACCOUNT_COLUMN_EMAIL);
        sqlBuf.append(" text )");

        this.createTableSqlList.add(sqlBuf.toString());
    }


    public void open()
    {
        this.dbManager.openDB();
    }

    public void close()
    {
        this.dbManager.closeDB();;
    }

    // Insert one row.
    public void insertAccount(String userName, String password, String email)
    {
        // Create table column list.
        List<TableColumn> tableColumnList = new ArrayList<TableColumn>();

        // Add user name column.
        TableColumn userNameColumn = new TableColumn();
        userNameColumn.setColumnName(this.TABLE_ACCOUNT_COLUMN_USERNAME);
        userNameColumn.setColumnValue(userName);
        tableColumnList.add(userNameColumn);

        // Add password column.
        TableColumn passwordColumn = new TableColumn();
        passwordColumn.setColumnName(this.TABLE_ACCOUNT_COLUMN_PASSWORD);
        passwordColumn.setColumnValue(password);
        tableColumnList.add(passwordColumn);

        // Add email column.
        TableColumn emailColumn = new TableColumn();
        emailColumn.setColumnName(this.TABLE_ACCOUNT_COLUMN_EMAIL);
        emailColumn.setColumnValue(email);
        tableColumnList.add(emailColumn);

        // Insert added column in to account table.
        this.dbManager.insert(this.TABLE_NAME_ACCOUNT, tableColumnList);
    }

    // Update one row. User name column can not be updated.
    public void updateAccount(int id, String password, String email)
    {
        // Create table column list.
        List<TableColumn> updateColumnList = new ArrayList<TableColumn>();

        // Update password can not be empty.
        if(!TextUtils.isEmpty(password)) {
            // Add password column.
            TableColumn passwordColumn = new TableColumn();
            passwordColumn.setColumnName(this.TABLE_ACCOUNT_COLUMN_PASSWORD);
            passwordColumn.setColumnValue(password);
            updateColumnList.add(passwordColumn);
        }


        // Add email column.
        TableColumn emailColumn = new TableColumn();
        emailColumn.setColumnName(this.TABLE_ACCOUNT_COLUMN_EMAIL);
        emailColumn.setColumnValue(email);
        updateColumnList.add(emailColumn);

        String whereClause = this.TABLE_ACCOUNT_COLUMN_ID + " = " + id;

        // Insert added column in to account table.
        this.dbManager.update(this.TABLE_NAME_ACCOUNT, updateColumnList, whereClause);
    }

    // Delete one account.
    public void deleteAccount(int id)
    {
        this.dbManager.delete(this.TABLE_NAME_ACCOUNT, this.TABLE_ACCOUNT_COLUMN_ID + " = " + id);
    }


    // Get all user account dto list.
    public List<UserAccountDTO> getAllAccount()
    {
        List<UserAccountDTO> ret = new ArrayList<UserAccountDTO>();
        Cursor cursor = this.dbManager.queryAllReturnCursor(this.TABLE_NAME_ACCOUNT);
        if(cursor!=null)
        {
            do {
                int id = cursor.getInt(cursor.getColumnIndex(this.TABLE_ACCOUNT_COLUMN_ID));
                String userName = cursor.getString(cursor.getColumnIndex(this.TABLE_ACCOUNT_COLUMN_USERNAME));
                String password = cursor.getString(cursor.getColumnIndex(this.TABLE_ACCOUNT_COLUMN_PASSWORD));
                String email = cursor.getString(cursor.getColumnIndex(this.TABLE_ACCOUNT_COLUMN_EMAIL));

                UserAccountDTO userAccountDto = new UserAccountDTO();
                userAccountDto.setId(id);
                userAccountDto.setUserName(userName);
                userAccountDto.setPassword(password);
                userAccountDto.setEmail(email);

                ret.add(userAccountDto);

            }while(cursor.moveToNext());

            // Close cursor after query.
            if(!cursor.isClosed()) {
                cursor.close();
            }
        }

        return ret;
    }

    // Return sqlite database cursor object.
    public Cursor getAllAccountCursor()
    {
        Cursor cursor = this.dbManager.queryAllReturnCursor(this.TABLE_NAME_ACCOUNT);
        return cursor;
    }
}

2.4 User Account DTO Class.

UserAccountDTO.java

package com.dev2qa.example.storage.sqlite.listview;

/**
 * Created by Jerry on 1/17/2018.
 */

public class UserAccountDTO {

    private int id;

    private String userName;

    private String password;

    private String email;

    public int getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

2.5 Main Layout Xml File.

activity_user_account_add.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="User Name :"/>

        <EditText
            android:id="@+id/user_account_edit_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:hint="Input user name."/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Password :"/>

        <EditText
            android:id="@+id/user_account_edit_password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:hint="Input password."
            android:password="true"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Email :"/>

        <EditText
            android:id="@+id/user_account_edit_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:hint="Input Email."/>

    </LinearLayout>

    <Button
        android:id="@+id/user_account_button_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save Account"/>
</LinearLayout>


activity_user_account_list_view.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ListView
        android:id="@+id/user_account_list_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:choiceMode="multipleChoice"
        android:clickable="true"
        android:divider="@color/colorGreen"
        android:dividerHeight="5dp">
    </ListView>

    <TextView
        android:id="@+id/user_account_list_empty_text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="The user account list is empty."
        android:textSize="20dp"/>

</LinearLayout>

2.6 User Account ListView Item Layout Xml File.

activity_user_account_list_view_item.xml

Please note you should set the checkbox’s focusable and clickable attribute to false to make the listview item response to user click event.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <CheckBox
            android:id="@+id/user_account_list_item_checkbox"
            android:width="0dp"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:clickable="false"/>

        <LinearLayout
            android:layout_weight="8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:width="0dp"
                    android:layout_weight="1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="ID : "
                    android:textSize="20dp"/>

                <TextView
                    android:id="@+id/user_account_list_item_id"
                    android:width="0dp"
                    android:layout_weight="2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="20dp"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:width="0dp"
                    android:layout_weight="1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Name : "
                    android:textSize="20dp"/>

                <TextView
                    android:id="@+id/user_account_list_item_user_name"
                    android:width="0dp"
                    android:layout_weight="2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="20dp"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:width="0dp"
                    android:layout_weight="1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Password : "
                    android:textSize="20dp"/>

                <TextView
                    android:id="@+id/user_account_list_item_password"
                    android:width="0dp"
                    android:layout_weight="2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="20dp"/>

            </LinearLayout>


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:width="0dp"
                    android:layout_weight="1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Email : "
                    android:textSize="20dp"/>

                <TextView
                    android:id="@+id/user_account_list_item_email"
                    android:width="0dp"
                    android:layout_weight="2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="20dp"/>

            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

2.7 Main Activity Menu XML File.

You also need to save three icon file add_icon.png, edit_icon.png and delete_icon.png in app/res/drawable folder.

READ :   How To Make Android VideoView Seekto Method Consistent

action_bar_add_edit_delete_example.xml

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

    <item
        android:id="@+id/menu_add"
        android:icon="@drawable/add_icon"
        android:title="Add"
        app:showAsAction="always|withText" />

    <item
        android:id="@+id/menu_edit"
        android:icon="@drawable/edit_icon"
        android:title="Edit"
        app:showAsAction="always|withText" />

    <item
        android:id="@+id/menu_delete"
        android:icon="@drawable/delete_icon"
        android:title="Delete"
        app:showAsAction="always|withText" />

</menu>

7 Comments


  1. Why don’t you provide files ??
    I tried to use yours but there’s lots omission like activity_user_account_add.xml and so on

    Reply

  2. It does not have the menus XML file. and I cant solve this problem… 🙁

    Reply

    1. The menu xml file is action_bar_add_edit_delete_example.xml and has been added at section 2.7 Main Activity Menu XML File.

      Reply

  3. Cannot find the DatabaseManager.java file in the utils cartegory. Please add it or provide the entire source code. Thanks in advance!! By the Way, great tutorial

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.