Design Useful CRUD Tables in Android Studio

Design Useful CRUD Tables in Android Studio

Introduction

The goal of this guide is to explain, how can we create from a database a set of tables in android studio, where we can see all the data in a user-friendly way and perform the CRUD operations. Since on internet, there are not a lot of detailed tutorials to create rows of a table from a database and the buttons modify and delete, in the same row for a table, I created this blog that I hope will be useful for you.

This will allow us to create user and administrator interfaces to interact with the data. For example, we have the table roles with the following information.

Also, we have our nodejs application that will communicate with the android studio application to create the table with the information as it is in the database and perform the crud operations.

Our IRetroFit will be called many times to perform the CRUD operations.

Design

In this application we are using fragments but you can use any type of UI, always we will need to use a scroll view to be able to scroll if the table is too big, and a linear layout before creating the table inside of these components.

<ScrollView
        android:id="@+id/scrollView6"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <HorizontalScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent">

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

                    <TableLayout
                        android:id="@+id/tablaRoles"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@android:color/white">

                        <!-- Table Heading -->

                        <TableRow android:background="@color/colorGreen">
                            xmlns:app="http://schemas.android.com/apk/res-auto"

                            <TextView
                                android:id="@+id/tvCodigo"
                                android:layout_width="150dp"
                                android:layout_height="wrap_content"
                                android:layout_weight="4"
                                android:gravity="center_horizontal"
                                android:padding="10sp"
                                android:text="Codigo"
                                android:textColor="@android:color/white"
                                android:textSize="14sp" />

We will need to create an id for the table **tablaRoles** (**rolestable**), we can start the first row which will contain the names of each column, so we can add an specific background, then we add the textview's which each one will be a column title, so we will need an ID *tvCodigo* and also add the text we want to display at the top of our table.

Now we have the base of our program so in the next step, we will see how we bring all the data from the database, and create the buttons "modify and delete".

Logic

We create the java class which will declare the behaving of the fragment created, and we import the table, and all the components you need like buttons. Also in this case we are using retrofit to create the request for the data.

We create the request for the information by creating the URL, that communicates to the API, and also we assign the buttons and the table to the ID that we created. In this request, we have a List<Rol> which will give us all the roles available in the database.

We call the request, and by the size of the response we iterate, so for each row of data that we receive from the database, we will iterate a for loop to create the rows in the application and allocate the values.

During this operation, we create a new TableRow, and TextView that is the text view that will have the information from the database, also the button that will allow us to modify this row.

So after creating this button, we can add his click listener, to perform the operation of modification, in this case we will bring the user to a new fragment, where he will have an input to make this operation, since this is an easy operation and we are focusing in how to create the table, we won't explain how the modification works. Just have in mind that in this function, you will put the logic you need to be done by the buttons of each row.

The same is for deleting, but in this case, we will delete the row straight forward, and not drive the user to another interface, so we search the request "executeDeleteRol" that is already created in our IRetroFit. This will create a request to /deleteRol/{id} and the NodeJS application will delete a rol by his id if exists.

And to finally finish our call.enqueue, we asign the new rows created, and put each TextView in the order we want, in this case we want.

(CODE|ROLE|MODIFY BUTTON|DELETE BUTTON)

And then add the row to the table, also we have a function to give an error in case that there's no information in the database, so we cant display any roles.

call.enqueue(new Callback<List<Rol>>() {
            @Override
            public void onResponse(Call<List<Rol>> call, Response<List<Rol>> response) {
                for(int i=0; i<response.body().size(); i++){
                    TableRow fila = new TableRow(getActivity());
                    TextView textRol = new TextView(getActivity());
                    Button btnModificar = new Button(getActivity());
                    Button btnEliminar = new Button(getActivity());
                    textRol.setBackgroundResource(R.drawable.columna_1);
                    textRol.setText(response.body().get(i).getRol());
                    textRol.setTypeface(null, Typeface.BOLD);
                    TextView textCodigo = new TextView(getActivity());
                    textCodigo.setText(String.valueOf(response.body().get(i).getCodigo()));
                    btnModificar.setText("Modificar");

                    btnModificar.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            System.out.println("id cupo = " + Integer.parseInt(textCodigo.getText().toString()));
                            ((Sesion)getActivity().getApplicationContext()).setIdRol(Integer.parseInt(textCodigo.getText().toString()));
                            NavHostFragment.findNavController(Roles.this).
                                    navigate(R.id.action_roles_to_modificarRoles);
                        }
                    });
                    btnEliminar.setText("Eliminar");
                    btnEliminar.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Call call1 = iRetrofit.executeDeleteRol(Integer.parseInt(textCodigo.getText().toString()));
                            call1.enqueue(new Callback() {
                                @Override
                                public void onResponse(Call call, Response response) {
                                    Toast.makeText(getContext(), "Rol Borrado", Toast.LENGTH_LONG).show();
                                    NavHostFragment.findNavController(Roles.this).
                                            navigate(R.id.action_roles_to_admin);
                                }

                                @Override
                                public void onFailure(Call call, Throwable t) {
                                    Toast.makeText(getContext(), "No se pudo borrar el rol", Toast.LENGTH_LONG).show();
                                }
                            });

                        }
                    });
                    textCodigo.setGravity(Gravity.CENTER);
                    textRol.setGravity(Gravity.CENTER);
                    fila.addView(textCodigo);
                    fila.addView(textRol);
                    fila.addView(btnModificar);
                    fila.addView(btnEliminar);
                    tablaRoles.addView(fila);
                }

            }

            @Override
            public void onFailure(Call<List<Rol>> call, Throwable t) {
                Snackbar.make(v, "No se encontraron los roles", Snackbar.LENGTH_LONG).show();
            }
        });

Result