DBHelper:
Код: Выделить всё
package com.leteam.materialgroup;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class DBHelper extends SQLiteOpenHelper
{
final String LOG_TAG = "myLogs";
private SqlScript sqlScript;
public DBHelper(Context context, SqlScript sqlScript)
{
super(context, "PocketIC.db", null, 1);
this.sqlScript = sqlScript;
Log.d(LOG_TAG, "DBHelper создан");
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase)
{
Log.d(LOG_TAG, "Запускаю скрипт в методе onCreate");
sqlScript.runScript(sqLiteDatabase);
Log.d(LOG_TAG, "Скрипт завершен");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2)
{
Log.d(LOG_TAG, "Запускаю метод onCreate в методе onUpgrade");
List<String> tables = new ArrayList<String>();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM sqlite_master WHERE type='table'", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String tableName = cursor.getString(1);
if (!tableName.equals("android_metadata") &&
!tableName.equals("sqlite_sequence"))
tables.add(tableName);
cursor.moveToNext();
}
cursor.close();
for(String tableName:tables) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + tableName);
}
onCreate(sqLiteDatabase);
}
}
Connect:
Код: Выделить всё
package com.leteam.materialgroup;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;
import android.util.Log;
import java.io.InputStream;
public class Connect implements BaseColumns
{
private static Connect instance;
private SQLiteDatabase sqLiteDatabase;
DBHelper dbHelper;
int parentId;
private int[] stack = new int[10];
private int stackTop;
final String LOG_TAG = "myLogs";
private Connect(Context context, InputStream inputStream)
{
Log.d(LOG_TAG, "Создаю скрипт");
SqlScript sqlScript = new SqlScript(inputStream);
Log.d(LOG_TAG, "Создаю DBHelper");
dbHelper = new DBHelper(context, sqlScript);
Log.d(LOG_TAG, "Подключаюсь к базе данных");
sqLiteDatabase = dbHelper.getWritableDatabase();
Log.d(LOG_TAG, "Включаю настройки PRAGMA");
sqLiteDatabase.execSQL("PRAGMA read_uncommitted = true;");
sqLiteDatabase.execSQL("PRAGMA defer_foreign_keys = true;");
sqLiteDatabase.execSQL("PRAGMA foreign_keys = true;");
reset();
}
public void stop()
{
sqLiteDatabase.close();
dbHelper.close();
Log.d(LOG_TAG, "Отключился от базы данных");
}
public static Connect start(Context context,InputStream inputStream)
{
if (instance == null)
{
instance = new Connect(context, inputStream);
}
return instance;
}
public void reset()
{
stack[0] = 0;
parentId = 0;
stackTop = 1;
}
private void push(int id)
{
if (stackTop < 9)
{
stack[stackTop] = id;
stackTop++;
}
}
private void pop()
{
stack[stackTop] = 0;
if (stackTop > 1)
stackTop--;
}
private int peek()
{
return stack[stackTop];
}
public int getParentId()
{
return parentId;
}
public String[] getGroupList(String table, String title)
{
Cursor cursor;
String[] titles = new String[] {};
String sql = "SELECT title FROM " + table +
" WHERE idParent = " + peek() +
" AND _id != 0";
if (title == null)
{
cursor = sqLiteDatabase.rawQuery(sql, null);
pop();
} else
{
// SELECT _id FROM " + table + " WHERE title = " + title + " AND idParent = " + peek();
cursor = sqLiteDatabase.query(table, new String[]{ _ID}, "title = ? AND idParent = ?",
new String[]{title, String.valueOf(peek())}, null, null, null);
if (cursor.getCount() == 0) return titles;
Log.d(LOG_TAG, String.valueOf(cursor.getInt(cursor.getColumnIndex("*"))));
parentId = cursor.getColumnIndex(cursor.getColumnName(0));
push(parentId);
cursor = sqLiteDatabase.rawQuery(sql, null);
}
int i = 0;
if (cursor.getCount() == 0) return titles;
titles = new String[cursor.getCount()];
if (cursor.moveToFirst())
{
do
{
titles[i] = cursor.getString(cursor.getColumnIndex("title"));
i++;
} while (cursor.moveToNext());
cursor.close();
}
return titles;
}
public void insertGroup(String table, String title)
{
ContentValues values = new ContentValues();
values.put("idParent", peek());
values.put("title", title);
long id = sqLiteDatabase.insert(table, null, values);
Log.d(LOG_TAG, String.valueOf("Запись добавлена (id = " + id + ")"));
}
public void deleteGroup(String table, String title)
{
long count = sqLiteDatabase.delete(table,"title = ? AND idParent = ?", new String[]{title, String.valueOf(peek())});
if (count > 1) Log.d(LOG_TAG, String.valueOf(count + " записей удалено"));
else Log.d(LOG_TAG, String.valueOf(count + " запись с title - \"" + title + "\" удалена"));
}
public void updateGroup(String table, String oldTitle, String newTitle)
{
ContentValues values = new ContentValues();
values.put("title", newTitle);
long count = sqLiteDatabase.update(table, values, "title = ? AND idParent = ?", new String[]{oldTitle, String.valueOf(peek())});
if (count > 1) Log.d(LOG_TAG, String.valueOf(count + " записей обновленно"));
else Log.d(LOG_TAG, String.valueOf("запись с title - \"" + oldTitle + "\" переименнована в \"" + newTitle +"\""));
}
}
MainActivity:
Код: Выделить всё
package com.leteam.materialgroup;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends Activity implements BaseColumns
{
final String LOG_TAG = "myLogs";
Toast toast;
AlertDialog.Builder ad;
private final int IDD = 1;
int i = 1;
ListView lvMain;
Connect connect;
String[] titles = {};
public static final int IDM_OPEN = 101;
int rez;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvMain = (ListView) findViewById(R.id.lvMain);
registerForContextMenu(lvMain);
Log.d(LOG_TAG, "Подключаю класс Connect");
try
{
connect = Connect.start(this, getAssets().open("Create.sql"));
}
catch (IOException e)
{
e.printStackTrace();
}
onRestart();
lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
long timeout = System.currentTimeMillis();
Log.d(LOG_TAG, "itemClick: position = " + position + ", id = " + id + "test=" + titles[position]);
/*Здесь надо получить новые значения в name*/
titles = connect.getGroupList("S_MaterialsGroup", titles[position]);
if ((titles == null) && (connect.getParentId() != 0))
{
titles = connect.getGroupList("S_Materials", titles[position]);
}
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
getApplicationContext(), R.layout.item_list, titles/*ЗДЕСЬ НОВЫЙ МАСИВ ПЕРЕПРИСВАИВАЕТСЯ*/);
lvMain.setAdapter(adapter1);
timeout = System.currentTimeMillis() - timeout;
Log.d(LOG_TAG, "time=" + timeout);
}
});
lvMain.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
rez=i;
return false;
}
});
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case IDD:
final String[] mName = {"Группу", "Материал"};
ad = new AlertDialog.Builder(this);
ad.setTitle("Добавить:"); // заголовок для диалога
ad.setNeutralButton("Назад",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
ad.setItems(mName, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
// TODO Auto-generated method stub
switch (item){
case 0:
Intent intent = new Intent(MainActivity.this, Add_Group.class);
startActivity(intent);
break;
case 1: Toast.makeText(getApplicationContext(), "Выбранный вариант: " + mName[item], Toast.LENGTH_SHORT).show();
break;
}
}
});
ad.setCancelable(false);
return ad.create();
default:
return null;
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(Menu.NONE, IDM_OPEN, Menu.NONE, "Удалить");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// CharSequence message;
switch (item.getItemId())
{
case IDM_OPEN:
connect.deleteGroup("S_MaterialsGroup",titles[rez]);
onRestart();
// Log.d(LOG_TAG, String.valueOf(rez));
break;
// case IDM_SAVE:
// message = "Выбран пункт Сохранить";
// break;
default:
return super.onContextItemSelected(item);
}
// Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.show();
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_items, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menu_save:
toast = Toast.makeText(getApplicationContext(), "Вы нажали элемент Добавить", Toast.LENGTH_SHORT);
toast.show();
showDialog(IDD);
return true;
case R.id.menu_delete:
toast = Toast.makeText(getApplicationContext(), "Вы нажали элемент Удалить", Toast.LENGTH_SHORT);
toast.show();
return true;
default:
return false;
}
}
@Override
public void onBackPressed() {
if (i == 0)
{
super.onBackPressed();
} else
{
Log.d(LOG_TAG, "i=" + i);
i = i - 1;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
connect.stop();
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(LOG_TAG, "Делаю запрос");
titles = connect.getGroupList("S_MaterialsGroup", null);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, R.layout.item_list, titles/*ЗДЕСЬ МАССИВ ИЗ TITLE*/);
lvMain.setAdapter(adapter);
}
}