How To Show Data From SQLite Database In Android ListView

This article contains examples of 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 saving the modified result data back to the SQLite database table.

1. Operate ListView Row With SQLite DB Example Demo.

  1. Below is this example demo video ( load add edit delete lisview data from sqlite database table example demo ).
  2. When the example starts, it will load and show user account data in the list view.
  3. The user account data is saved in the SQLite database file UserInfo.db.
  4. Run the below command in the 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
  5. Then you can use an android device monitor to see the file UserInfo.db is saved in the folder /data/data/com.dev2qa.example/databases. Please refer article Android Device Monitor Cannot Open Data Folder Resolve Method for more detail.
  6. 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|jerry@dev2qa.com
    3|tom|tom|tom@dev2qa.com
  7. Please note the table account‘s primary key column name should be ‘_id‘, otherwise when you use SimpleCursorAdapter to bind the data to the ListView, there will prompt “java.lang.IllegalArgumentException: column ‘_id’ does not exist” exception.
  8. 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. Show Data From SQLite Database In Android ListView Example Source Code.

  1. For database table operation source code, please refer article How To Write Reusable Code For Android SQLite Database. That article introduces how to write a reusable java class to process SQLite database table operations.
  2. There are four Java classes, one layout XML file, and one menu XML file in this example.
    ./
    ├── app
    │   ├── build.gradle
    │   ├── proguard-rules.pro
    │   └── src
    │       ├── main
    │       │   ├── AndroidManifest.xml
    │       │   ├── java
    │       │   │   └── com
    │       │   │       └── dev2qa
    │       │   │           └── example
    │       │   │               ├── storage
    │       │   │               │   └── sqlite
    │       │   │               │       ├── listview
    │       │   │               │       │   ├── UserAccountAddActivity.java
    │       │   │               │       │   ├── UserAccountDTO.java
    │       │   │               │       │   ├── UserAccountListViewActivity.java
    │       │   │               │       │   └── UserInfoDBManager.java

2.1 Main Activity Java File.

  1. UserAccountListViewActivity.java: This is the main activity, it shows the ListView control and three buttons 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.

  1. UserAccountAddActivity.java: This activity will be shown when the user adds a new or edit an existing 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 another 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.

  1. UserInfoDBManager.java: This java class will focus on user account database operations. It will reuse the DatabaseManager class that is introduced in the 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;
    
    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. The 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.

  1. UserAccountDTO.java
    package com.dev2qa.example.storage.sqlite.listview;
    
    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.

  1. 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>
  2. 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.

  1. 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 the 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.

  1. You also need to save the three icon files add_icon.png, edit_icon.png, and delete_icon.png in the app/res/drawable folder.
  2. 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 thoughts on “How To Show Data From SQLite Database In Android ListView”

  1. 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

  2. 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

Leave a Comment

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.