Androidda Sqlite ma'lumotlar bazasi bilan ishlash . (1 - qism)


Assalomu alaykum.
Bugungi darsimizda biz Sqlite — ma’lumotlar bazasi bilan ishlashni o’rganamiz.
Bziga nima uchun kere bu Sqlite degan savol paydo bo’lgan bo’lsa, javob bunday: Sqlite sizga ma’lumotlaringizni saqlash uchun kerak, qisqa va lo’nda. To’gri, bu to’liq javob bo’la olmaydi, hozircha shunday tushinib turganimiz ma’qul.





main.xml — layout faylimizni ochib, editTextlar va button larni quyidagi ko’rnishda joylaymiz:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >
    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello"
            android:textSize="18dp" android:paddingBottom="10dp"/>
    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Ismingiz:"
            android:textSize="15dp"/>
    <EditText
            android:id="@+id/ism"
            android:layout_width="157dp"
            android:layout_height="wrap_content"
            />
    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Familyangiz:"
            />
    <EditText
            android:id="@+id/familya"
            android:layout_width="163dp"
            android:layout_height="wrap_content"
            />
    <Button
            android:id="@+id/add"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Add"
            />
    <Button
            android:id="@+id/deleteall"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Delete All"
            />
    <ListView
            android:id="@+id/contentlist"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
</LinearLayout>


Quyidagi ko’rinishda layout hosil bo’ladi:


Yani Ism, Familyani kiritgandan keyin “Add” tugmasini bosganda ushbu malumotlarni saqlab qo’yadi, va ro’yhatini ko’rsatib turadi.

Yana bitta row.xml fayl yaratamiz, bu fayl bizga nima uchun kerak?
Bu fayl bizga bazamizdagi malumotlarni ko’rsatib berish uchun kerak.

row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content">
<LinearLayout
    android:orientation="horizontal"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content">
<TextView
 android:layout_width="wrap_content"
 android:layout_height="fill_parent"
 android:padding="2dip"
 android:text="#"/>
<TextView
 android:id="@+id/id"
 android:layout_width="wrap_content"
 android:layout_height="fill_parent"
 android:padding="2dip"
 android:paddingRight="10dip"/>
<TextView
 android:layout_width="wrap_content"
 android:layout_height="fill_parent"
 android:padding="2dip"
 android:paddingRight="10dip"
 android:text="-" />
<TextView
 android:id="@+id/text1"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:padding="2dip"/>
</LinearLayout>
<TextView
 android:id="@+id/text2"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:padding="2dip"/>
</LinearLayout>


Mana biz kerakli layout larni yaratib oldik.
Endi asosiy kodni yozishga o’tsak:

Activity faylimizni ochib, main.xml faylida ko’rsatgan editTextlar ,Buttonlar va listView larni activity faylimizga bog’laymiz.

ism = (EditText)findViewById(R.id.ism);
        familya= (EditText)findViewById(R.id.familya);
        buttonAdd = (Button)findViewById(R.id.add);
        buttonDeleteAll = (Button)findViewById(R.id.deleteall);

        opennetchilar = (ListView)findViewById(R.id.opennetlist);


Endi biz dasturimizni malumotlar bazasi bilan boglaymiz.



Biz SqliteAdaoter nomli klass yaratamiz, aynan shunday nom bo’lishi shart emas, o’ziz hohlagan nom berishiz mumkin.

Albatta Constructor ni yaratamiz.

public SQLiteAdapter(Context c){
        context = c;
   }

Ushbu klassimizni ichida yana bitta klass yaratamiz, hohlasangiz bu klassdan tashqarida ham yaratsangiz bo’ladi:
Bu klassning nomini SQLiteHelper deb nomladim, va SQLiteOpenHelper klassidan extend olgan.
SQLiteOpenHelper — bu bizga database yaratib, undagi amallar bajarishga yordam beruvchi klass.

Bu klassning 2 ta metodi mavjud:
  onCreate — database yaratish uchun
  onUpgrade — yaratilgan database ni yangilash uchun
  
onCreate metodini ichiga quydagilarni yozing:
  @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL(SCRIPT_CREATE_DATABASE);
        }

SCRIPT_CREATE_DATABASE — oddiy String o’zgaruvchi, yani siz SQL yoki MySql ni o’rgangan quyidagi so’rovni ko’rgan bo’lishingiz kerak:

Create table `table_name`(id integer autoincrement primary key, ism TEXT NOT NULL...); VA HAKAZO...

Yani yuqoridagi o’zgaruvchining qiymatiga biz Sqlite so’rovlarini yozishimiz mumkin va execSQL bizga bu so’rovni amalga oshirib beradi.

Endi quyidagi o’zgaruvchilarni yaratamiz, bu o’zgaruvchilar database bilan ishlash uchun har doim kerak bo’ladigan o’zgaruvchilar bo’lganligi uchun hususiyatini public qilamiz

public static final String MYDATABASE_NAME = "opennet";
    public static final String MYDATABASE_TABLE = "opennetchilar";
    public static final int MYDATABASE_VERSION = 1;
    public static final String KEY_ID = "_id";
    public static final String ism = "ism";
    public static final String familya = "familya";

    //create table MY_DATABASE (ID integer primary key, Content text not null);
    private static final String SCRIPT_CREATE_DATABASE =
            "create table " + MYDATABASE_TABLE + " ("
                    + KEY_ID + " integer primary key autoincrement, "
                    + ism + " text not null, "
                    + familya + " text not null);";
    private SQLiteHelper sqLiteHelper;
   private SQLiteDatabase sqLiteDatabase;
   private Context context;


Menimcha buni ta’riflab o’tirshga hojat yo’q deb o’ylayman, ko’rib turganingizdek oddiy String o’zgaruvchilar.

Endi database yaratish funksiyasiga kelsak, quyidagikodni yozamiz

sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);

SQLiteHelper klassiga murojaat qiladi va onCreate metodi ishga tushadi, va bizning databaseimizni yaratib beradi.
Esingizda tuting, database ni 1 marta yaratadi,agar shunday nomli database bor bo’lsa yaratmaydi.

SqliteAdapter klassimizni ichida quyidagi funksiyalarni yaratamiz:
openToRead() — nomidan ham ma’lumki, databaseni o’qishga ruxsat olish uchun
public SQLiteAdapter openToRead() throws android.database.SQLException {
        sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
        sqLiteDatabase = sqLiteHelper.getReadableDatabase();
        return this;
    }


openToWrite() — nomidan ham ma’lumki, databaseni tahrirlash uchun ruxsat olish
public SQLiteAdapter openToWrite() throws android.database.SQLException {
        sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
        sqLiteDatabase = sqLiteHelper.getWritableDatabase();
        return this;
    }

Va nihoyat databaseni ishlatib bo’lganimizdan so’ng, uni yopish.
public void close(){
        sqLiteHelper.close();
   }

   
   Database ga ma’lumot qo’shish funksiyasi
       public long insert(String content1, String content2){
   
           ContentValues contentValues = new ContentValues();
           contentValues.put(ism, content1);
           contentValues.put(familya, content2);
           return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
       }

   
    Database dagi barcha ma’lumotlarni o’chirish funksiyasi
     public int deleteAll(){
           return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
       }

   
   Databasidagi barcha ma’lumotlarni olish uchun ishlatiladigan funksiya
       public Cursor queueAll(){
           String[] columns = new String[]{KEY_ID, ism, familya};
           Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
                   null, null, null, null, null);
   
           return cursor;
       }

   
   Endi qo’lgan o’zimizga kerakli funksiyalarni shu klassga qo’shib ketishingiz mumkin, yani faqat database bilan bogliq bo’lgan funksiyalarni.
   
   
   Endi SqliteAdapter imiz dan yangi object yaratamiz va database ga yozish uchun ruxsat beruvchi funksiyani ishga tushiramiz:
           mySQLiteAdapter = new SQLiteAdapter(this);
           mySQLiteAdapter.openToWrite();

   
   Database dagi barcha ma’lumotlarni oluvchi funksiyani ishga tushiramiz:
       cursor = mySQLiteAdapter.queueAll();

SimpleCursorAdapter — bu Adapter bizga databasedagi malumotlarni ro’yhatda ko’rsatishga yordam beradi.

Databasedan barcha ma’lumotlarni olganimizdan keyin uni ListView ga joylaymiz:

String[] from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.ism, SQLiteAdapter.familya};
        int[] to = new int[]{R.id.id, R.id.text1, R.id.text2};
        cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
        opennetchilar.setAdapter(cursorAdapter);


Maqolaning boshida row.xml fayli haqida ozroq ma’lumot berib ketgandik, yuqorida ko’rib turganingizdek endi ushbu faylni ishlatamiz.

Maqola rosa cho’zilib ketibdi, buyog’iga qisqaroq qilmasam zerikib qolish ehtimoli bor.

Endi Button tugmalari bilan ishlash qoldi yani yangi ma’lumot qo’shish tugmasi va barcha ma’lumotlarni o’chirish tugmasi:

Button.OnClickListener buttonAddOnClickListener = new Button.OnClickListener(){
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            String data1 = ism.getText().toString();
            String data2 = familya.getText().toString();
            mySQLiteAdapter.insert(data1, data2);
            updateList();
        }
    };

    Button.OnClickListener buttonDeleteAllOnClickListener
            = new Button.OnClickListener(){

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mySQLiteAdapter.deleteAll();
            updateList();
        }

   };

   Bu ListView ni update(yangilab) turish uchun, yani Database ga biror malumot qo’shliganda Listviewni Avtomat ravishda update qilish uchun kerak bo’ladi.
   
   Endi Dasturni ishga tushiramiz va ma’lumot kiritib Add tugmasini bosamiz:




   Ko’rib turganingizdek, dastur juda ajoyib ishlayapti.
   
   Dastur kodini ko’chirib olishni unutmang. Ko'chirib olish.
   
Bu 1-qism edi, ikkinchi qismini tez orada  saytni kuzatib borsangiz albatta o’qiysiz
   

Popular posts from this blog

Rus tili. Rus tilini o'rganish. Rus tili grammatikasi.(Грамматика русского языка в иллюстрациях.)(djvu). Mylingvo

PHP va MySQL video kursi . HTML, CSS, PHP, MYSQL dan video kurslar.