5.12.1. Использование базы данных SQLite (часть 2)

5.12.1. Использование базы данных SQLite (часть 2)

Содержимое файла add_items.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Название"
        android:layout_marginBottom="16dp">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/titleText"
            android:imeOptions="actionNext"
            android:inputType="text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Содержимое">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/contentText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </com.google.android.material.textfield.TextInputLayout>

</LinearLayout>

Добавьте ещё один xml файл с названием master_fragment и Root element – ConstraintLayout, макет используется для фрагмента списка элементов:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp">

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

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/searchLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Введите текст для поиска">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/searchField"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:imeOptions="actionSearch"
                android:inputType="text" />
        </com.google.android.material.textfield.TextInputLayout>

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/addNewItem"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_marginBottom="8dp"
        android:layout_marginRight="8dp"
        android:src="@drawable/ic_add_black_24dp"
        app:backgroundTint="@color/colorPrimary"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Добавьте ещё один файл макета с названием detail_fragment и Root element – LinearLayout с нижеследующим кодом:

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

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

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Sample Title"
            android:textColor="#000"
            android:textSize="20sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Content"
            android:textColor="#444"
            android:textSize="17sp" />

    </LinearLayout>
</ScrollView>

Теперь настал черед добавления дополнительных классов для нашего приложения. Добавьте класс и назовите AddItemsDialog. Измените его код таким образом:

public class AddItemsDialog extends DialogFragment {
    // Интерфейс это объявление функций, только без кода. Как бы стандарт которого надо придерживаться в классах в которых через ключевое слово implements, объявляется соответствие интерфейсу в данном случае MainActivity должен соответствовать интерфейсу IRefreshList и для соответствия в MainActivity должны быть функции объявленные в IRefreshList. В данном случае интерфейс IRefreshList требует написания кода для всего одной функции с именем RefreshList(), который не возвращает значения (void)
    interface IRefreshList {
        void RefreshList();
    }

    EditText titleText;
    EditText contentText;
    IRefreshList activity;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.add_items, null);
        builder.setView(v);
        builder.setMessage("Добавить новую запись");
        titleText = v.findViewById(R.id.titleText);
        contentText = v.findViewById(R.id.contentText);
        builder.setIcon(R.mipmap.ic_launcher);

        builder.setPositiveButton("Сохранить", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Database db = new Database(getContext());
                if(db.addItem(new DBItem(0, titleText.getText().toString(), contentText.getText().toString()))) {
                    Toast.makeText(getContext(), "Запись добавлена", Toast.LENGTH_SHORT).show();
                    // Обновить ListView в activity после добавления записи, для показа новых данных
                    activity.RefreshList();
                } else {
                    Toast.makeText(getContext(), "Ошибка при добавлении записи повторите заново", Toast.LENGTH_SHORT).show();
                }
                dismiss();
            }
        });

        builder.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dismiss();
            }
        });

        return builder.create();
    }

    // Функцию вызывается при показе фрагмента в activity
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // Используется приведение типа context, которым является activity в котором показывается это окно к типу интерфейса IRefreshList, который декларирует что необходимо написать функцию RefreshList
        activity = (IRefreshList) context;
    }
}

Это была вторая часть, третья часть в следующем уроке...