Міністерство освіти і науки
Національний університет „Львівська політехніка”
Кафедра ЕОМ
/
Звіт
з лабораторної роботи №5
з дисципліни: “Мережні операційні системи”
на тему: “Управління даними в ОС Android за допомогою СУБД SQLite”
Мета: Оволодіти навичками роботи з СУБД SQLite в ОС Android.
Перелік основних методів для роботи з СУБД SQLite в ОС Android:
openOrCreateDatabase(), execSQL(), insert(), update(), delete().
Лістинг тестової програми:
MainActivity.java
package com.example.baztar.mos_lab5;import android.app.AlertDialog;import android.content.ContentValues;import android.content.DialogInterface;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import android.widget.SearchView;import android.widget.TabHost;import android.widget.Toast;import java.util.ArrayList;public class MainActivity extends AppCompatActivity { private ListView lv; private Button btnAdd; private TabHost tabHost; private EditText etName; private EditText etLecturer; private EditText etHours; private EditText etSchedule; private EditText etMark; private SearchView sv; private ArrayAdapter<String> adapter; private DBHelper dbHelper; private ArrayList<String> names; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabHost = (TabHost) findViewById(R.id.tabHost); lv = (ListView) findViewById(R.id.listView); btnAdd = (Button) findViewById(R.id.btnAdd); etName = (EditText) findViewById(R.id.etName); etLecturer = (EditText) findViewById(R.id.etLecturer); etHours = (EditText) findViewById(R.id.etHours); etSchedule = (EditText) findViewById(R.id.etSchedule); etMark = (EditText) findViewById(R.id.etMark); sv = (SearchView) findViewById(R.id.searchView); tabHost.setup(); TabHost.TabSpec tabSpec = tabHost.newTabSpec("tag1"); tabSpec.setContent(R.id.tab1); tabSpec.setIndicator("Search"); tabHost.addTab(tabSpec); tabSpec = tabHost.newTabSpec("tag2"); tabSpec.setContent(R.id.tab2); tabSpec.setIndicator("Add"); tabHost.addTab(tabSpec); tabHost.setCurrentTab(0); dbHelper = new DBHelper(this); updateListView(); sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { adapter.getFilter().filter(newText); return false; } }); lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { readTable(position); } }); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addToTable(etName.getText().toString(), etHours.getText().toString(), etLecturer.getText().toString(), etSchedule.getText().toString(), etMark.getText().toString()); tabHost.setCurrentTab(0); updateListView(); etName.setText(""); etLecturer.setText(""); etHours.setText(""); etSchedule.setText(""); etMark.setText(""); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0,0,0,"Clear table"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case 0: deleteTable(); break; } return super.onOptionsItemSelected(item); } private void updateListView(){ try { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor c = db.query(DBHelper.TABLE_NAME, new String[]{DBHelper.NAME}, null, null, null, null, null); names = new ArrayList<>(); while (c.moveToNext()) names.add(c.getString(0)); c.close(); adapter = new ArrayAdapter(this, R.layout.list_item, R.id.subject_name, names); lv.setAdapter(adapter); } catch (Exception ex){ Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show(); } } private void addToTable(String name, String hours, String lecturer, String schedule, String mark){ try { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(DBHelper.NAME, name); contentValues.put(DBHelper.HOURS, hours); contentValues.put(DBHelper.LECTURER, lecturer); contentValues.put(DBHelper.SCHEDULE, schedule); contentValues.put(DBHelper.MARK, mark); db.insert(DBHelper.TABLE_NAME, null, contentValues); Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show(); } catch (Exception ex){ Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show(); } } private void readTable(int pos){ SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor c = db.query(DBHelper.TABLE_NAME,null,"Name=?",new String[]{names.get(pos)},null,null,null); if(c.moveToFirst()) { int nameindex = c.getColumnIndex(DBHelper.NAME); int timeindex = c.getColumnIndex(DBHelper.HOURS); int lectindex = c.getColumnIndex(DBHelper.LECTURER); int scheduleindex = c.getColumnIndex(DBHelper.SCHEDULE); int markindex = c.getColumnIndex(DBHelper.MARK); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle(c.getString(nameindex)) .setMessage("Lecturer: " + c.getString(lectindex) + "\n" + "Hours: " + c.getString(timeindex) + "\n" + "Schedule: " + c.getString(scheduleindex) + "\n" + "Mark: " + c.getString(markindex)) .setCancelable(false) .setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } else { Toast.makeText(this,"Wrong data",Toast.LENGTH_LONG).show(); return; } c.close(); } private void deleteTable(){ try { dbHelper.getWritableDatabase().delete(DBHelper.TABLE_NAME, null, null); Toast.makeText(this, "Deleted!", Toast.LENGTH_LONG).show(); } catch (Exception ex){ Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show(); } }}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><TabHost android:id="@+id/tabHost" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center_horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/tab1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="top" android:orientation="vertical"> <SearchView android:id="@+id/searchView" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listView" /> </LinearLayout> <LinearLayout android:id="@+id/tab2" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_marginLeft="16dp" android:layout_marginRight="16dp"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:id="@+id/etName" android:hint="Name" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:id="@+id/etLecturer" android:hint="Lecturer" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:ems="10" android:id="@+id/etHours" android:hint="Hours" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:id="@+id/etSchedule" android:hint="Schedule" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:id="@+id/etMark" android:hint="Mark" /> <Button android:text="btnAdd" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btnAdd" android:layout_marginTop="40dp" /> </LinearLayout> </FrameLayout> </LinearLayout></TabHost>
DBHelper.java
package com.example.baztar.mos_lab5;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;/** * Created by Тарас on 12.12.2016. */public class DBHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "mos_lab5"; public static final String TABLE_NAME = "Subjects1"; public static final String NAME = "Name"; public static final String HOURS ="Hours"; public static final String LECTURER = "Lecturer"; public static final String SCHEDULE = "Schedule"; public static final String MARK = "Mark"; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + TABLE_NAME + " ("+ NAME + " text primary key," + HOURS + " text," + LECTURER + " text," + SCHEDULE + " text," + MARK + " text)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table if exist " + TABLE_NAME); onCreate(db); }}
Результати виконання тестової програми:
///
Рис. 1. Результат виконання програми
Висновки: На цій лабораторній роботі я оволодів навичками роботи з СУБД SQLite в ОС Android.