Кашина_РМП_ЛБ17_2
.docxМинистерство науки и высшего образования Российской Федерации Федеральное государственное бюджетное образовательное учреждение высшего образования
«Владимирский государственный университет
имени Александра Григорьевича и Николая Григорьевича Столетовых» (ВлГУ)
Колледж инновационных технологий и предпринимательства
КАФЕДРА ФИЗИКИ И ПРИКЛАДНОЙ МАТЕМАТИКИ
Лабораторная работа № 17_2
по МДК 01.03 «Разработка мобильных приложений»
на тему: «Работа с БД»
Выполнил
студент группы ИПсп-123
Кашина Д. А.
Принял
Красильщикова В.В.
Владимир, 2026 г.
Цель работы: научится добавлять, удалять и обновлять данные в SQLite.
Ход работы:
разметка activity_main.xml
<?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" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="321dp" android:layout_height="45dp" android:layout_marginTop="44dp" android:text="Добавить" android:onClick="add" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/toolbar" /> <ListView android:id="@+id/list" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginTop="16dp" android:layout_marginBottom="16dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/button" /> </androidx.constraintlayout.widget.ConstraintLayout>
разметка activity_user.xml
<?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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/year" android:layout_width="389dp" android:layout_height="48dp" android:layout_marginTop="184dp" android:ems="10" android:hint="Введите год рождения" android:inputType="text" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.727" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/name" android:layout_width="389dp" android:layout_height="48dp" android:layout_marginTop="124dp" android:ems="10" android:hint="Введите имя" android:inputType="text" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.727" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/saveButton" android:layout_width="185dp" android:layout_height="45dp" android:layout_marginStart="24dp" android:layout_marginBottom="396dp" android:onClick="save" android:text="Сохранить" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" /> <Button android:id="@+id/deleteButton" android:layout_width="165dp" android:layout_height="47dp" android:layout_marginBottom="396dp" android:onClick="delete" android:text="Удалить" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.644" app:layout_constraintStart_toEndOf="@+id/saveButton" /> </androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.laba17_2; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; public class MainActivity extends AppCompatActivity { ListView userList; DatabaseHelper databaseHelper; SQLiteDatabase db; Cursor userCursor; SimpleCursorAdapter userAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Проверяем, есть ли Toolbar в разметке Toolbar toolbar = findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); } userList = findViewById(R.id.list); userList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getApplicationContext(), UserActivity.class); intent.putExtra("id", id); startActivity(intent); } }); databaseHelper = new DatabaseHelper(getApplicationContext()); } @Override protected void onResume() { super.onResume(); // Открываем подключение db = databaseHelper.getReadableDatabase(); // Получаем данные из БД userCursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE, null); // Определяем, какие столбцы из курсора будут выводиться в ListView String[] headers = new String[]{DatabaseHelper.COLUMN_NAME, DatabaseHelper.COLUMN_YEAR}; // Создаем адаптер userAdapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, userCursor, headers, new int[]{android.R.id.text1, android.R.id.text2}, 0); userList.setAdapter(userAdapter); } public void add(View view) { Intent intent = new Intent(this, UserActivity.class); startActivity(intent); } @Override protected void onDestroy() { super.onDestroy(); // Закрываем подключение и курсор if (db != null) db.close(); if (userCursor != null) userCursor.close(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_about) { new androidx.appcompat.app.AlertDialog.Builder(this) .setTitle("О программе") .setMessage("Работа с БД SQLite\nВыполнила Кашина Д.") .setPositiveButton("OK", null) .show(); return true; } else if (id == R.id.action_exit) { finishAffinity(); return true; } return super.onOptionsItemSelected(item); } }
DatabaseHelper.java
package com.example.laba17_2; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "users.db"; private static final int DATABASE_VERSION = 1; public static final String TABLE = "users"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_YEAR = "year"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String createTable = "CREATE TABLE " + TABLE + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT, " + COLUMN_YEAR + " INTEGER)"; db.execSQL(createTable); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE); onCreate(db); } }
UserActivity.java
package com.example.laba17_2; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class UserActivity extends AppCompatActivity { EditText nameBox; EditText yearBox; Button delButton; Button saveButton; DatabaseHelper sqlHelper; SQLiteDatabase db; Cursor userCursor; long userId = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user); nameBox = findViewById(R.id.name); yearBox = findViewById(R.id.year); delButton = findViewById(R.id.deleteButton); saveButton = findViewById(R.id.saveButton); sqlHelper = new DatabaseHelper(this); db = sqlHelper.getWritableDatabase(); Bundle extras = getIntent().getExtras(); if (extras != null) { userId = extras.getLong("id", 0); } if (userId > 0) { // Редактирование существующего пользователя userCursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE + " WHERE " + DatabaseHelper.COLUMN_ID + " = ?", new String[]{String.valueOf(userId)}); if (userCursor.moveToFirst()) { nameBox.setText(userCursor.getString(userCursor.getColumnIndex(DatabaseHelper.COLUMN_NAME))); yearBox.setText(String.valueOf(userCursor.getInt(userCursor.getColumnIndex(DatabaseHelper.COLUMN_YEAR)))); } if (userCursor != null) userCursor.close(); } else { // Добавление нового пользователя - скрываем кнопку удаления delButton.setVisibility(View.GONE); } } public void save(View view) { String name = nameBox.getText().toString().trim(); String yearStr = yearBox.getText().toString().trim(); // Проверка на пустые поля if (name.isEmpty() || yearStr.isEmpty()) { Toast.makeText(this, "Заполните все поля!", Toast.LENGTH_SHORT).show(); return; } int year; try { year = Integer.parseInt(yearStr); } catch (NumberFormatException e) { Toast.makeText(this, "Год должен быть числом!", Toast.LENGTH_SHORT).show(); return; } ContentValues cv = new ContentValues(); cv.put(DatabaseHelper.COLUMN_NAME, name); cv.put(DatabaseHelper.COLUMN_YEAR, year); if (userId > 0) { // Обновление существующей записи db.update(DatabaseHelper.TABLE, cv, DatabaseHelper.COLUMN_ID + " = ?", new String[]{String.valueOf(userId)}); Toast.makeText(this, "Данные обновлены", Toast.LENGTH_SHORT).show(); } else { // Добавление новой записи db.insert(DatabaseHelper.TABLE, null, cv); Toast.makeText(this, "Пользователь добавлен", Toast.LENGTH_SHORT).show(); } goHome(); } public void delete(View view) { db.delete(DatabaseHelper.TABLE, DatabaseHelper.COLUMN_ID + " = ?", new String[]{String.valueOf(userId)}); Toast.makeText(this, "Пользователь удален", Toast.LENGTH_SHORT).show(); goHome(); } private void goHome() { // Закрываем подключение if (db != null) db.close(); // Переход к главной активности Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); finish(); // Закрываем текущую активность } }
Результат работы программы:
