2012/2013 учебный год
Упражнение 3
База данных img_anim.db содержит одну таблицу myanim, в которой созданы три колонки:
1) id - номер изображения,
2) imgname - название файла с изображением,
3) imganim - вид анимации.
При нажатии на кнопку Next загружается изображение, к нему применяется соответствующая анимация: alpha, combo, rotate, scale, trans.
Внимание! Откройте файл
gen/org/ggpi/MyImgSQLite03/R.java
и проверяйте после выполнения каждого из ниже приведённых соответствующих примеров, что в нём зарегистрированы объекты
Самостоятельно определите: какие объекты здесь должны быть?
Для приложения можно скопировать, распаковав из архива, готовую базу данных img_anim.db в папку на Android-устройство:
/data/data/org.ggpi.MyImgSQLite03/databases/
Архив примера БД. Правый щелчок мыши на ссылке вызовет выпадающее меню, в котором нужно выбрать команду "Сохранить объект как..."
[ Скачать файл ]
Если БД не открывается в приложении, то, возможно, требуется изменить права доступа. Для этого нужно перейти с помощью
adb
в папку
/data/data/org.ggpi.MyImgSQLite03/databases/
Проверить права доступа, изменить режим, убедиться, что изменения произведены:
ls -l img_anim.db chmod 777 img_anim.db ls -l img_anim.db
Создайте папку
res/anim/
Из примеров прошлых занятий заполните её описаниями анимации:
myalpha.xml mycombo.xml myrotate.xml myscale.xml mytrans.xml
Пример 3.1. Файл res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">MyImgSQLite03</string> <string name="action_settings">Settings</string> <string name="id">ID</string> <string name="img_name">Name</string> <string name="img_anim">Animation</string> <string name="btn_add">Add</string> <string name="btn_read">Read</string> <string name="btn_clear">Clear</string> <string name="btn_next">Next</string> </resources>
Пример 3.2. Файл res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:text="@string/id" > </TextView> <EditText android:id="@+id/etID" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" > <requestFocus> </requestFocus> </EditText> </LinearLayout> <LinearLayout android:id="@+id/linearLayout3" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:text="@string/img_name" > </TextView> <EditText android:id="@+id/etName" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" > </EditText> </LinearLayout> <LinearLayout android:id="@+id/linearLayout4" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:text="@string/img_anim" > </TextView> <EditText android:id="@+id/etAnim" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" > </EditText> </LinearLayout> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="fill_parent" android:layout_height="wrap_content" > <Button android:id="@+id/btnAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_add" > </Button> <Button android:id="@+id/btnRead" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_read" > </Button> <Button android:id="@+id/btnClear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_clear" > </Button> <Button android:id="@+id/btnNext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_next" > </Button> </LinearLayout> <ImageView android:id="@+id/image1" android:src="@drawable/ic_launcher" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#000000" android:padding="1dp" android:layout_gravity="center_horizontal" /> </LinearLayout>
Пример 3.3. Файл MainActivity.java
package org.ggpi.MyImgSQLite03; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; public class MainActivity extends Activity implements OnClickListener { private static final String DATABASE_NAME = "img_anim.db"; private static final String DATABASE_TABLE = "myanim"; final String LOG_TAG = "myLogs"; Button btnAdd, btnRead, btnClear, btnNext; EditText etID, etName, etAnim; ImageView image1; // Счётчик для нажатий btnNext. int countNext = 0; DBHelper dbHelper; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnAdd = (Button) findViewById(R.id.btnAdd); btnAdd.setOnClickListener(this); btnRead = (Button) findViewById(R.id.btnRead); btnRead.setOnClickListener(this); btnClear = (Button) findViewById(R.id.btnClear); btnClear.setOnClickListener(this); btnNext = (Button) findViewById(R.id.btnNext); btnNext.setOnClickListener(this); etID = (EditText) findViewById(R.id.etID); etName = (EditText) findViewById(R.id.etName); etAnim = (EditText) findViewById(R.id.etAnim); image1 = (ImageView) findViewById(R.id.image1); // создаем объект для создания и управления версиями БД dbHelper = new DBHelper(this); } @Override public void onClick(View v) { // создаем объект для данных ContentValues cv = new ContentValues(); // получаем данные из полей ввода String id = etID.getText().toString(); String name = etName.getText().toString(); String anim = etAnim.getText().toString(); Animation animImg = null; // подключаемся к БД SQLiteDatabase db = dbHelper.getWritableDatabase(); // делаем запрос всех данных из таблицы DATABASE_TABLE, получаем Cursor Cursor c = db.query(DATABASE_TABLE, null, null, null, null, null, null); int idColIndex = c.getColumnIndex("id"); int nameColIndex = c.getColumnIndex("imgname"); int animColIndex = c.getColumnIndex("imganim"); switch (v.getId()) { case R.id.btnNext: boolean nextExist = false; countNext++; Log.d(LOG_TAG, "--- Rows in mytable: ---"); if (countNext == 1) { if (c.moveToFirst()) { Log.d(LOG_TAG, "ID = " + c.getInt(idColIndex) + ", name = " + c.getString(nameColIndex) + ", anim = " + c.getString(animColIndex)); } } if (countNext > 1) { // Локальный счётчик пройденных записей таблицы. int iCount = 0; while (iCount < countNext) { iCount++; nextExist = c.moveToNext(); Log.d(LOG_TAG, "iCount = " + iCount + ", nextExist = " + nextExist); } if (!nextExist) { countNext = 0; c.moveToFirst(); } else { int idAnim = 0; String strAnim = c.getString(animColIndex).toString(); if (strAnim.equals("alpha")) idAnim = R.anim.myalpha; if (strAnim.equals("combo")) idAnim = R.anim.mycombo; if (strAnim.equals("rotate")) idAnim = R.anim.myrotate; if (strAnim.equals("scale")) idAnim = R.anim.myscale; if (strAnim.equals("trans")) idAnim = R.anim.mytrans; Log.d(LOG_TAG, "ID = " + c.getInt(idColIndex) + ", name = " + c.getString(nameColIndex) + ", anim = " + c.getString(animColIndex) + ", idAnim = " + idAnim); etID.setText(Integer.toString(c.getInt(idColIndex))); etName.setText(c.getString(nameColIndex)); etAnim.setText(c.getString(animColIndex)); image1.setImageDrawable(Drawable.createFromPath("/data/"+c.getString(nameColIndex)+".jpg") ); animImg = AnimationUtils.loadAnimation(this, idAnim); image1.startAnimation(animImg); } } c.close(); break; case R.id.btnAdd: Log.d(LOG_TAG, "--- Insert in mytable: ---"); // подготовим данные для вставки в виде пар: наименование столбца - значение cv.put("id", id); cv.put("imgname", name); cv.put("imganim", anim); // вставляем запись и получаем ее ID long rowID = db.insert(DATABASE_TABLE, null, cv); Log.d(LOG_TAG, "row inserted, ID = " + rowID); break; case R.id.btnRead: Log.d(LOG_TAG, "--- Rows in mytable: ---"); // делаем запрос всех данных из таблицы mytable, получаем Cursor // Cursor c = db.query(DATABASE_TABLE, null, null, null, null, null, null); // ставим позицию курсора на первую строку выборки // если в выборке нет строк, вернется false if (c.moveToFirst()) { // определяем номера столбцов по имени в выборке do { // получаем значения по номерам столбцов и пишем все в лог Log.d(LOG_TAG, "ID = " + c.getInt(idColIndex) + ", name = " + c.getString(nameColIndex) + ", anim = " + c.getString(animColIndex)); // переход на следующую строку // а если следующей нет (текущая - последняя), то false - выходим из цикла } while (c.moveToNext()); } else Log.d(LOG_TAG, "0 rows"); c.close(); break; case R.id.btnClear: Log.d(LOG_TAG, "--- Clear mytable: ---"); // удаляем все записи int clearCount = db.delete(DATABASE_TABLE, null, null); Log.d(LOG_TAG, "deleted rows count = " + clearCount); break; } // закрываем подключение к БД dbHelper.close(); } class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context) { // конструктор суперкласса super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { Log.d(LOG_TAG, "--- onCreate database ---"); // создаем таблицу с полями db.execSQL("create table "+ DATABASE_TABLE + " (" + "id integer primary key autoincrement," + "imgname text," + "imganim text" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } }