Android GridView - CRUD - ADD UPDATE DELETE

android crud

Android GridView CRUD tutorial.

Hello.We see how to perform basic CRUD operations against GridView.

  • We add,update and delete.
  • Our basic data source is an arraylist.
  • Our adapter is ArrayAdapter.

Let's start.

1. CRUD.java

Our aim is to learn how to perform CRUD(Create Read Update Delete) while using a GridView. Hence it is better to create a separate concrete class that will:

  1. Maintain our data source. In this case we ise a simple ArrayList:
    private ArrayList<String> names =new ArrayList<>();
  2. Save or Add data to GridView. We will use the ArrayList's add() method.
    public void save(String name)
    {
       names.add(name);
    }
  3. Get or Retrieve all data
    public ArrayList<String> getNames()
    {

        return names;
    }
  1. Update Data. Updating basically means removing the existing and replacing it with a new one.

    
    public Boolean update(int position,String newName)
    {
       try {
           names.remove(position);
           names.add(position,newName);
    
           return true;
       }catch (Exception e)
       {
           e.printStackTrace();
          return false;
        }
    }
  2. Delete Data Deleting implies removing an existing data without any replacement ocurring:

    public Boolean delete(int position)
    {
        try {
            names.remove(position);
    
            return true;
        }catch (Exception e)
        {
            e.printStackTrace();
            return false;
    
        }
    }

Here's the full class:

package com.tutorials.hp.gridview_crud;

import java.util.ArrayList;

public class CRUD {

    private ArrayList<String> names =new ArrayList<>();

    public void save(String name)
    {
       names.add(name);
    }
    public ArrayList<String> getNames()
    {
        return names;
    }
    public Boolean update(int position,String newName)
    {
       try {
           names.remove(position);
           names.add(position,newName);

           return true;
       }catch (Exception e)
       {
           e.printStackTrace();
          return false;
        }
    }
    public Boolean delete(int position)
    {
        try {
            names.remove(position);

            return true;
        }catch (Exception e)
        {
            e.printStackTrace();
            return false;

        }
    }
}

2. MainActivity.java

Here's our main and only activity. Activity represent screens that the users act on. You can think of it as pages in an application. Your application can have several activities. However this is not a must. For example you can have an activity contain a fragment or a dialog.

A Fragment is a sub-activity that has to be hosted in a main activity. You can use it to display for example an input form. However the simplest way is to use a Dialog. Dialog don't require us to create separate java files nor deal with complex lifecycle callbacks.

Instead we can just instantiate one and give it a layout. We will use a Dialog to display our input form. That form will just have some EditText and some buttons. The user will input data in the edittext and click any of those button depending on the action.

For example our CRUD doesn't use any database for simplicity as our focus is GridView and not data source. So we will support:

  1. Adding Data typed in EditText to GridView.
  2. Updating that Data.
  3. Deleting the data from the GridView.
package com.tutorials.hp.gridview_crud;

import android.app.Dialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    GridView gv;
    ArrayAdapter<String> adapter;
    CRUD crud=new CRUD();
    Dialog d;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        gv= (GridView) findViewById(R.id.gv);

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(d != null) {
                    if(!d.isShowing())
                    {
                        displayInputDialog(i);
                    }else
                    {
                        d.dismiss();
                    }
                }
            }
        });

        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
             //DISPLAY DIALOG FOR NEW DATA
                displayInputDialog(-1);
            }
        });
    }
    private void displayInputDialog(final int pos)
    {
        d=new Dialog(this);
        d.setTitle("GRIDVIEW CRUD");
        d.setContentView(R.layout.input_dialog);

        final EditText nameEditTxt= (EditText) d.findViewById(R.id.nameEditText);
        Button addBtn= (Button) d.findViewById(R.id.addBtn);
        Button updateBtn= (Button) d.findViewById(R.id.updateBtn);
        Button deleteBtn= (Button) d.findViewById(R.id.deleteBtn);

        if(pos== -1)
        {
            addBtn.setEnabled(true);
            updateBtn.setEnabled(false);
            deleteBtn.setEnabled(false);
        }else
        {
            addBtn.setEnabled(true);
            updateBtn.setEnabled(true);
            deleteBtn.setEnabled(true);
            nameEditTxt.setText(crud.getNames().get(pos));
        }

        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //GET DATA
                String name=nameEditTxt.getText().toString();

                //VALIDATE
                if(name.length()>0 && name != null)
                {
                    //save
                    crud.save(name);
                    nameEditTxt.setText("");
                    adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,crud.getNames());
                    gv.setAdapter(adapter);

                }else
                {
                    Toast.makeText(MainActivity.this, "Name cannot be empty", Toast.LENGTH_SHORT).show();
                }
            }
        });
        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //GET DATA
                String newName=nameEditTxt.getText().toString();

                //VALIDATE
                if(newName.length()>0 && newName != null)
                {
                    //save
                    if(crud.update(pos,newName))
                    {
                        nameEditTxt.setText(newName);
                        adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,crud.getNames());
                        gv.setAdapter(adapter);
                    }

                }else
                {
                    Toast.makeText(MainActivity.this, "Name cannot be empty", Toast.LENGTH_SHORT).show();
                }
            }
        });
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //DELETE
                if( crud.delete(pos))
                {
                    nameEditTxt.setText("");
                    adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,crud.getNames());
                    gv.setAdapter(adapter);
                }
            }
        });

        d.show();
    }
}

3. activity_main.xml

This is the main layout for our MainActivity.java. This is also acting as our template layout in that it holds the general parts of our activity like ToolBar and AppBar.

Then it includes the content_main.xml which will actually hold our GridView.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.tutorials.hp.gridview_crud.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

 

4. content_main.xml

This is the content layout as the name suggests. It will hold contain our GridView. It is independent of other parts of the screen like the ToolBar and AppBar.

All we need is come and add a GridView right here.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.tutorials.hp.gridview_crud.MainActivity"
    tools:showIn="@layout/activity_main">

    <GridView
        android:id="@+id/gv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numColumns="3" />
</RelativeLayout>

5. input_dialog.xml

Thisis our input view. Users will input data via this layut. We shall inflate from an XML layout into a dialog. This ensures we have another screen without having to create a fragment or a new activity.

We have an EditText where users will type data. Then buttons for adding updating and deleting the items.

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

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        android:orientation="vertical"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingTop="10dp">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/nameLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/nameEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:hint= "Name" />
        </android.support.design.widget.TextInputLayout>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button android:id="@+id/addBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ADD"
        android:clickable="true"
        android:background="@color/colorAccent"
        android:layout_marginTop="20dp"
        android:textColor="@android:color/white"/>

    <Button android:id="@+id/updateBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="UPDATE"
        android:clickable="true"
        android:background="#009968"
        android:layout_marginTop="20dp"
        android:textColor="@android:color/white"/>

    <Button android:id="@+id/deleteBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DELETE"
        android:clickable="true"
        android:background="#2fc1b9"
        android:layout_marginTop="20dp"
        android:textColor="@android:color/white"/>
</LinearLayout>
         </LinearLayout>

</LinearLayout>

Download

Resource Link
GitHub Browse Browse
GitHub Download Link Download

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post