Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Кашина_РМП_ЛБ17_5

.docx
Скачиваний:
0
Добавлен:
22.09.2026
Размер:
162 Кб
Скачать
☆

Министерство науки и высшего образования Российской Федерации Федеральное государственное бюджетное образовательное учреждение высшего образования

«Владимирский государственный университет

имени Александра Григорьевича и Николая Григорьевича Столетовых» (ВлГУ)

Колледж инновационных технологий и предпринимательства

КАФЕДРА ФИЗИКИ И ПРИКЛАДНОЙ МАТЕМАТИКИ

Лабораторная работа № 17_5

по МДК 01.03 «Разработка мобильных приложений»

на тему: «Приложение с использование БД»

Выполнил

студент группы ИПсп-123

Кашина Д. А.

Принял

Красильщикова В.В.

Владимир, 2026 г.

Цель работы: научится создавать мобильные приложения с использованием БД.

Ход работы:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF"> <LinearLayout android:id="@+id/blueHeader" android:layout_width="match_parent" android:layout_height="180dp" android:orientation="vertical" android:gravity="center" android:background="#0D47A1"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Привет, Админ!" android:textSize="28sp" android:textStyle="bold" android:textColor="#FFFFFF" android:paddingStart="24dp" android:paddingEnd="24dp" android:layout_marginBottom="8dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Ваш личный кабинет!" android:textSize="16sp" android:textColor="#E0E0E0" android:paddingStart="24dp" android:paddingEnd="24dp" /> </LinearLayout> <LinearLayout android:id="@+id/whiteCard" android:layout_width="295dp" android:layout_height="107dp" android:layout_centerHorizontal="true" android:layout_marginTop="135dp" android:background="#FFFFFF" android:elevation="8dp" android:gravity="center" android:orientation="vertical"> <Button android:id="@+id/profileButton" android:layout_width="200dp" android:layout_height="45dp" android:backgroundTint="#0D47A1" android:text="Личный кабинет" android:textColor="#FFFFFF" android:textSize="16sp" android:textStyle="bold" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="24dp" android:layout_below="@id/whiteCard" android:layout_marginTop="40dp" android:gravity="center_horizontal"> <EditText android:id="@+id/nameEditText" android:layout_width="match_parent" android:layout_height="55dp" android:hint="Введите имя" android:inputType="textPersonName" android:padding="16dp" android:textSize="16sp" android:textColor="#000000" android:textColorHint="#888888" android:layout_marginBottom="24dp" /> <!-- Поле: Введите номер +7 --> <EditText android:id="@+id/phoneEditText" android:layout_width="match_parent" android:layout_height="55dp" android:hint="Введите номер +7" android:inputType="phone" android:padding="16dp" android:textSize="16sp" android:textColor="#000000" android:textColorHint="#888888" android:layout_marginBottom="40dp" /> <!-- Кнопка Сохранить (меньше по длине) --> <Button android:id="@+id/saveButton" android:layout_width="200dp" android:layout_height="50dp" android:text="Сохранить" android:textSize="16sp" android:backgroundTint="#0D47A1" android:textColor="#FFFFFF" /> </LinearLayout> <!-- ===== НИЖНЯЯ СИНЯЯ ПОЛОСА (кнопки сливаются с фоном) ===== --> <LinearLayout android:layout_width="match_parent" android:layout_height="65dp" android:orientation="horizontal" android:gravity="center" android:background="#0D47A1" android:paddingHorizontal="12dp" android:layout_alignParentBottom="true"> <Button android:id="@+id/homeButton" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="ГЛАВНАЯ" android:textSize="10sp" android:textStyle="bold" android:background="@android:color/transparent" android:textColor="#FFFFFF" android:stateListAnimator="@null" /> <Button android:id="@+id/contactsButton" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="КОНТАКТЫ" android:textSize="10sp" android:textStyle="bold" android:background="@android:color/transparent" android:textColor="#FFFFFF" android:stateListAnimator="@null" /> <Button android:id="@+id/blogButton" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="БЛОГ" android:textSize="10sp" android:textStyle="bold" android:background="@android:color/transparent" android:textColor="#FFFFFF" android:stateListAnimator="@null" /> </LinearLayout> </RelativeLayout>

activity_contacts.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" android:background="#F5F5F5"> <TextView android:id="@+id/contactsTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Список контактов (0)" android:textSize="24sp" android:textStyle="bold" android:textColor="#0D47A1" android:layout_marginBottom="20dp" /> <EditText android:id="@+id/contactNameInput" android:layout_width="match_parent" android:layout_height="55dp" android:hint="Имя контакта" android:textColor="#000000" android:textColorHint="#888888" android:padding="12dp" android:layout_marginBottom="12dp" /> <EditText android:id="@+id/contactPhoneInput" android:layout_width="match_parent" android:layout_height="55dp" android:hint="Номер телефона" android:textColor="#000000" android:textColorHint="#888888" android:inputType="phone" android:padding="12dp" android:layout_marginBottom="20dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/updateContactButton" android:layout_width="0dp" android:layout_height="50dp" android:layout_weight="1" android:text="Обновить" android:backgroundTint="#0D47A1" android:textColor="#FFFFFF" android:layout_marginEnd="8dp" /> <Button android:id="@+id/deleteContactButton" android:layout_width="0dp" android:layout_height="50dp" android:layout_weight="1" android:text="Удалить" android:backgroundTint="#D32F2F" android:textColor="#FFFFFF" android:layout_marginStart="8dp" /> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Нажмите на контакт для редактирования" android:textSize="12sp" android:textColor="#888888" android:layout_marginTop="8dp" android:layout_marginBottom="16dp" /> <ListView android:id="@+id/contactsListView" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#FFFFFF" /> <include layout="@layout/navigation_bar" /> </LinearLayout>

activity_blog.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"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <include layout="@layout/navigation_bar" /> </LinearLayout>

navigation.bar.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="65dp" android:orientation="horizontal" android:gravity="center" android:background="#0D47A1"> <Button android:id="@+id/homeButton" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="ГЛАВНАЯ" android:textSize="12sp" android:textStyle="bold" android:background="@android:color/transparent" android:textColor="#FFFFFF" /> <Button android:id="@+id/contactsButton" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="КОНТАКТЫ" android:textSize="12sp" android:textStyle="bold" android:background="@android:color/transparent" android:textColor="#FFFFFF" /> <Button android:id="@+id/blogButton" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="БЛОГ" android:textSize="14sp" android:textStyle="bold" android:background="@android:color/transparent" android:textColor="#FFFFFF" /> </LinearLayout>

MainActivity.java

package com.example.laba17_5; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private DatabaseHelper dbHelper; private EditText nameInput, phoneInput; private Button saveButton, homeButton, contactsButton, blogButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHelper = new DatabaseHelper(this); nameInput = findViewById(R.id.nameEditText); phoneInput = findViewById(R.id.phoneEditText); saveButton = findViewById(R.id.saveButton); homeButton = findViewById(R.id.homeButton); contactsButton = findViewById(R.id.contactsButton); blogButton = findViewById(R.id.blogButton); saveButton.setOnClickListener(v -> { String name = nameInput.getText().toString().trim(); String phone = phoneInput.getText().toString().trim(); if (!name.isEmpty() && !phone.isEmpty()) { if (dbHelper.addContact(name, phone)) { Toast.makeText(MainActivity.this, "Контакт добавлен!", Toast.LENGTH_SHORT).show(); nameInput.setText(""); phoneInput.setText(""); } else { Toast.makeText(MainActivity.this, "Ошибка добавления", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "Заполните имя и телефон", Toast.LENGTH_SHORT).show(); } }); homeButton.setOnClickListener(v -> Toast.makeText(MainActivity.this, "Вы уже на главной", Toast.LENGTH_SHORT).show() ); contactsButton.setOnClickListener(v -> { Intent intent = new Intent(MainActivity.this, ContactsActivity.class); startActivity(intent); }); blogButton.setOnClickListener(v -> { Intent intent = new Intent(MainActivity.this, BlogActivity.class); startActivity(intent); }); } }

DatabaseHelper.java

package com.example.laba17_5; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "userdata.db"; private static final int DATABASE_VERSION = 2; public static final String TABLE_USER = "user"; public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_PHONE = "phone"; public static final String TABLE_CONTACTS = "contacts"; public static final String COLUMN_CONTACT_ID = "id"; public static final String COLUMN_CONTACT_NAME = "name"; public static final String COLUMN_CONTACT_PHONE = "phone"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String createUserTable = "CREATE TABLE " + TABLE_USER + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT, " + COLUMN_PHONE + " TEXT)"; db.execSQL(createUserTable); String createContactsTable = "CREATE TABLE " + TABLE_CONTACTS + " (" + COLUMN_CONTACT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_CONTACT_NAME + " TEXT NOT NULL, " + COLUMN_CONTACT_PHONE + " TEXT NOT NULL)"; db.execSQL(createContactsTable); ContentValues cv = new ContentValues(); cv.put(COLUMN_CONTACT_NAME, "Иван Петров"); cv.put(COLUMN_CONTACT_PHONE, "+7 999 123-45-67"); db.insert(TABLE_CONTACTS, null, cv); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER); db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS); onCreate(db); } public void saveUser(String name, String phone) { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DELETE FROM " + TABLE_USER); ContentValues cv = new ContentValues(); cv.put(COLUMN_NAME, name); cv.put(COLUMN_PHONE, phone); db.insert(TABLE_USER, null, cv); db.close(); } public String[] getUser() { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT " + COLUMN_NAME + ", " + COLUMN_PHONE + " FROM " + TABLE_USER + " LIMIT 1", null); String name = ""; String phone = ""; if (cursor.moveToFirst()) { name = cursor.getString(0); phone = cursor.getString(1); } cursor.close(); db.close(); return new String[]{name, phone}; } public boolean addContact(String name, String phone) { if (name == null || name.trim().isEmpty() || phone == null || phone.trim().isEmpty()) { return false; } SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COLUMN_CONTACT_NAME, name); cv.put(COLUMN_CONTACT_PHONE, phone); long result = db.insert(TABLE_CONTACTS, null, cv); db.close(); return result != -1; } public List<Contact> getAllContacts() { List<Contact> contacts = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS + " ORDER BY " + COLUMN_CONTACT_NAME + " ASC", null); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_CONTACT_ID)); String name = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT_NAME)); String phone = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT_PHONE)); contacts.add(new Contact(id, name, phone)); } cursor.close(); db.close(); return contacts; } public boolean deleteContactById(int id) { SQLiteDatabase db = this.getWritableDatabase(); int result = db.delete(TABLE_CONTACTS, COLUMN_CONTACT_ID + " = ?", new String[]{String.valueOf(id)}); db.close(); return result > 0; } public boolean deleteContactByName(String name) { SQLiteDatabase db = this.getWritableDatabase(); int result = db.delete(TABLE_CONTACTS, COLUMN_CONTACT_NAME + " = ?", new String[]{name}); db.close(); return result > 0; } public boolean updateContact(int id, String newName, String newPhone) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COLUMN_CONTACT_NAME, newName); cv.put(COLUMN_CONTACT_PHONE, newPhone); int result = db.update(TABLE_CONTACTS, cv, COLUMN_CONTACT_ID + " = ?", new String[]{String.valueOf(id)}); db.close(); return result > 0; } }

ContactsActivity.java

package com.example.laba17_5; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; public class ContactsActivity extends AppCompatActivity { private DatabaseHelper dbHelper; private EditText contactNameInput, contactPhoneInput; private Button updateButton, deleteButton; private ListView listView; private TextView contactsTitle; private ArrayAdapter<String> contactsAdapter; private List<String> contactDisplayList = new ArrayList<>(); private List<Contact> contactsList = new ArrayList<>(); private Contact selectedContact = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contacts); dbHelper = new DatabaseHelper(this); contactNameInput = findViewById(R.id.contactNameInput); contactPhoneInput = findViewById(R.id.contactPhoneInput); updateButton = findViewById(R.id.updateContactButton); deleteButton = findViewById(R.id.deleteContactButton); listView = findViewById(R.id.contactsListView); contactsTitle = findViewById(R.id.contactsTitle); Button homeButton = findViewById(R.id.homeButton); Button contactsButton = findViewById(R.id.contactsButton); Button blogButton = findViewById(R.id.blogButton); homeButton.setOnClickListener(v -> { Intent intent = new Intent(ContactsActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); }); contactsButton.setOnClickListener(v -> Toast.makeText(ContactsActivity.this, "Вы уже в контактах", Toast.LENGTH_SHORT).show() ); blogButton.setOnClickListener(v -> { Intent intent = new Intent(ContactsActivity.this, BlogActivity.class); startActivity(intent); }); loadContacts(); updateButton.setOnClickListener(v -> { if (selectedContact != null) { String newName = contactNameInput.getText().toString().trim(); String newPhone = contactPhoneInput.getText().toString().trim(); if (!newName.isEmpty() && !newPhone.isEmpty()) { if (dbHelper.updateContact(selectedContact.getId(), newName, newPhone)) { Toast.makeText(ContactsActivity.this, "Контакт обновлён", Toast.LENGTH_SHORT).show(); clearInputs(); loadContacts(); } else { Toast.makeText(ContactsActivity.this, "Ошибка обновления", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(ContactsActivity.this, "Заполните оба поля", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(ContactsActivity.this, "Выберите контакт для обновления", Toast.LENGTH_SHORT).show(); } }); deleteButton.setOnClickListener(v -> { if (selectedContact != null) { if (dbHelper.deleteContactById(selectedContact.getId())) { Toast.makeText(ContactsActivity.this, "Контакт удалён", Toast.LENGTH_SHORT).show(); clearInputs(); loadContacts(); } else { Toast.makeText(ContactsActivity.this, "Ошибка удаления", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(ContactsActivity.this, "Выберите контакт для удаления", Toast.LENGTH_SHORT).show(); } }); listView.setOnItemClickListener((parent, view, position, id) -> { selectedContact = contactsList.get(position); contactNameInput.setText(selectedContact.getName()); contactPhoneInput.setText(selectedContact.getPhone()); Toast.makeText(ContactsActivity.this, "Редактируйте или удалите", Toast.LENGTH_SHORT).show(); }); } private void clearInputs() { contactNameInput.setText(""); contactPhoneInput.setText(""); selectedContact = null; } private void loadContacts() { contactsList.clear(); contactDisplayList.clear(); contactsList.addAll(dbHelper.getAllContacts()); contactsTitle.setText("Список контактов (" + contactsList.size() + ")"); for (Contact c : contactsList) { contactDisplayList.add(c.getName() + " — " + c.getPhone()); } if (contactDisplayList.isEmpty()) { contactDisplayList.add("Нет контактов. Добавьте на главной странице!"); } contactsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactDisplayList) { @Override public android.view.View getView(int position, android.view.View convertView, android.view.ViewGroup parent) { android.view.View view = super.getView(position, convertView, parent); TextView textView = view.findViewById(android.R.id.text1); textView.setTextColor(Color.BLACK); textView.setTextSize(16); return view; } }; listView.setAdapter(contactsAdapter); } @Override protected void onResume() { super.onResume(); loadContacts(); clearInputs(); } }

BlogActivity.java

package com.example.laba17_5; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class BlogActivity extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_blog); webView = findViewById(R.id.webView); webView.setWebViewClient(new WebViewClient()); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("https://www.google.com/?hl=RU"); Button homeButton = findViewById(R.id.homeButton); Button contactsButton = findViewById(R.id.contactsButton); Button blogButton = findViewById(R.id.blogButton); homeButton.setOnClickListener(v -> { Intent intent = new Intent(BlogActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); }); contactsButton.setOnClickListener(v -> { Intent intent = new Intent(BlogActivity.this, ContactsActivity.class); startActivity(intent); finish(); }); blogButton.setOnClickListener(v -> Toast.makeText(BlogActivity.this, "Вы уже в блоге", Toast.LENGTH_SHORT).show() ); } @Override public void onBackPressed() { if (webView.canGoBack()) { webView.goBack(); } else { super.onBackPressed(); } } }

Результат работы программы

Вывод: в ходе выполнения лабораторной работы были получены навыки создания мобильных приложений с использованием БД.