منتدى فيجوال بيسك لكل العرب | منتدى المبرمجين العرب
SQLite (Insert, Delete, Update and Search)in Xamarin.Android Part2 - نسخة قابلة للطباعة

+- منتدى فيجوال بيسك لكل العرب | منتدى المبرمجين العرب (http://vb4arb.com/vb)
+-- قسم : قسم برمجة الهواتف (http://vb4arb.com/vb/forumdisplay.php?fid=208)
+--- قسم : قسم مقالات Xamarin.Android (http://vb4arb.com/vb/forumdisplay.php?fid=209)
+--- الموضوع : SQLite (Insert, Delete, Update and Search)in Xamarin.Android Part2 (/showthread.php?tid=23840)



SQLite (Insert, Delete, Update and Search)in Xamarin.Android Part2 - Sajad - 14-02-18

بسم الله الرحمن الرحيم
(رب اشرح لي صدري ويسر لي أمري أحلل عقدة من لساني يفقهوا قولي)

السلام عليكم ورحمة الله وبركاته



التعامل مع قاعدة بيانات من نوع SQLite من خلال تطبيق أندرويد باستخدام تقنية Xamarin



الجزء الثاني



تطرقنا في الجزء الأول SQLite in Xamarin.Android Part1 على خطوات انشاء قاعدة بيانات من نوع SQLite وكيفية ادراجها الى مشروع الأندرويد.


وقمنا كذلك ببناء Class نتعامل من خلاله مع قاعدة البيانات.

أما في هذا الجزء سنخصصه للتعرف على كيفية تصميم الواجهة وتنفيذ عمليات (الاضافة، التعديل، الحذف، البحث) على قاعدة البيانات.



أولاً: قم بتنزيل المكتبة التالية: Xamarin.Android.Support.v7.AppCompat من NuGet باتباع الطريقة التالية:
كلك يمين على Reference واختر Manage NuGet Packages ثم اكتب في خانة البحث اسم المكتبة وقم بتنصيبها.


ثانياً: قم بانشاء ملف باسم Styles داخل مجلد values وضع بداخل ملف الـ Styles الاكواد التالية الخاصة بالتصميم:
PHP كود :
<resources>
 
 <style name="MyTheme" parent="MyTheme.Base">
 
 </style>
 
 <style name="MyTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <
item name="windowActionBar">false</item>
        <
item name="colorPrimaryDark">#00796B</item>
        
<item name="colorPrimary">#009688</item>
        
<item name="colorAccent">#4CAF50</item>        
        
<!-- Important for CollapsingToolbarLayout -->
     
       <item name="windowNoTitle">true</item>
    </
style>
</
resources

ثالثاً: انتقل الى الملف MainActivity.cs واستبدل Activity بــ AppCompatActivity.

رابعاً: ضع Theme = "@style/MyTheme" ] داخل الـ Attribute لتصبح بالشكل التالي:
PHP كود :
   [Activity(Label "SQLiteCRUD"MainLauncher true,Theme "@style/MyTheme")] 



خامساً: انتقل الى ملف Main.axml واستبدل الكود الموجود بالتالي:

PHP كود :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    <SearchView
        android:id="@+id/searchText"
        android:queryHint="Enter a TestName"
        android:layout_marginTop="30dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <LinearLayout
        android:layout_margin="5dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="Id:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/idText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_margin="5dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="TestName:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/testNameText"
            android:inputType="text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_margin="5dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="TestAdress:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/testAdressText"
            android:inputType="text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_margin="5dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="TestAge:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/testAgeText"
            android:inputType="number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:gravity="center"
        android:layout_marginTop="15dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/insertButton"
            android:text="Insert"
            android:textAllCaps="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/updatetButton"
            android:text="Update"
            android:textAllCaps="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/deletetButton"
            android:text="Delete"
            android:textAllCaps="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/getAllButton"
            android:text="GetAll"
            android:textAllCaps="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <ListView
        android:id="@+id/testListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout> 

الاكواد أعلاه عبارة عن أكواد xml خاصة بالواجهة، حيث يتضمن الأدوات التالية:

1- LinearLayout.
2- Toolbar.
3- Button.
4- EditText.
5- SearchView.
6- ListView.
7- TextView.



حيث تخطيط التصميم بالشكل التالي:

أما شكل التصميم سيكون كالتالي:
[صورة مرفقة: screenshot_20180213-2052431.jpg?ssl=1&w=450]


سادساً: انتقل الى MainActivity.cs وعرف المتغيرات التالية:

PHP كود :
V7ToolBar v7ToolBar;
 
       SQLiteManipulation sqliteManipulation;
 
       EditText nameTextadressTextageText;
 
       TextView idView;
 
       SearchView searchText;
 
       Button insertButtonupdateButtondeleteButtongetAllButton;
 
       List<TestTabletestList;
 
       ListView testLisView;
 
       int_id

 

المتغير testList لاحتواء البيانات المسترجعة من قاعدة البيانات واسنادها الى الاداة testListView.
المتغير id_ سيتم اعتماده لعميات التحديث والحذف، حيث يتم اسناد تسلسل الحقول اليه.


وستحتاج الى مجالات الاسماء التالية:

PHP كود :
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Support.V7.App;
using V7ToolBar Android.Support.V7.Widget.Toolbar;
using System.Collections.Generic;
using System;
using System.Linq

ضع هذه الاكواد داخل الدالة OnCreate:

PHP كود :
// Set V7Toolbar as default toolbar
 
           v7ToolBar FindViewById<V7ToolBar>(Resource.Id.toolbar);
 
           SetSupportActionBar(v7ToolBar);

 
           // Initialize the widgets
 
           nameText FindViewById<EditText>(Resource.Id.testNameText);
 
           adressText FindViewById<EditText>(Resource.Id.testAdressText);
 
           ageText FindViewById<EditText>(Resource.Id.testAgeText);
 
           idView FindViewById<TextView>(Resource.Id.idText);
 
           testLisView FindViewById<ListView>(Resource.Id.testListView);

 
           // SearchView
 
           searchText FindViewById<SearchView>(Resource.Id.searchText);
 
           // Initialize the Buttons
 
           insertButton FindViewById<Button>(Resource.Id.insertButton);
 
           updateButton FindViewById<Button>(Resource.Id.updatetButton);
 
           deleteButton FindViewById<Button>(Resource.Id.deletetButton);
 
           getAllButton FindViewById<Button>(Resource.Id.getAllButton);


 
           // Initialize the Database
 
           GetAll();

 
           // Initialize the Events
 
           insertButton.Click += InsertButton_Click;
 
           updateButton.Click += UpdateButton_Click;
 
           deleteButton.Click += DeleteButton_Click;
 
           getAllButton.Click += GetAllButton_Click;
 
           searchText.QueryTextChange += SearchText_QueryTextChange


الاكواد أعلاه هي اكواد تعريفية للأدوات الموجودة على الواجهة في ملف الـ (Main.axml).

قم بتعريف هذه الدالة داخل الكلاس MainActivty:
PHP كود :
private void GetAll()
 
       {
 
           sqliteManipulation = new SQLiteManipulation();
 
           testList sqliteManipulation.GetTests();
 
       
الان نأتي الى الاحداث الخاصة بالأدوات:


الحدث InsertButton_Click:
PHP كود :
private void InsertButton_Click(object senderEventArgs e)
 
       {
 
           if (nameText.Text.Equals("")) return;
 
           var testTable = new TestTable
            
{
 
               TestName nameText.Text,
 
               TestAdress adressText.Text,
 
               TestAge Convert.ToInt32(ageText.Text)
 
           };
 
           if (sqliteManipulation.InsertTest(testTable))
 
           {
 
               GetAll();
 
               Toast.MakeText(this"The data inserted"ToastLength.Long).Show();
 
           }
 
           else
            
{
 
               Toast.MakeText(this"The data failed to insert"ToastLength.Long).Show();
 
           }
 
       



شرح الكود أعلاه: يتم تعريف Instance باسم testTable حيث يتم اسناد البيانات الى الكلاس بالتالي يتم تمرير الـ testTable الى دالة الـ InsertTest ليتم عملية الاضافة الى قاعدة البيانات.



الحدث UpdatButton_Click:

PHP كود :
private void UpdateButton_Click(object senderEventArgs e)
 
       {
 
           if (_id == null) return;
 
           var testTable testList.SingleOrDefault(id => id.Id == _id);
 
           testTable.TestName nameText.Text;
 
           testTable.TestAdress adressText.Text;
 
           testTable.TestAge Convert.ToInt32(ageText.Text);
 
           if (sqliteManipulation.UpdateTest(testTable))
 
           {
 
               GetAll();
 
               Toast.MakeText(this"The data updated"ToastLength.Long).Show();
 
           }
 
           else
            
{
 
               Toast.MakeText(this"The data failed to update"ToastLength.Long).Show();
 
           }
 
       


شرح الكود أعلاه: بعد جلب البيانات وخزنها في testList في دالة الـ GetAll يتم البحث فيها عن طريق الـ id_ واسناد ناتج البحث والتي ستكون عبارة عن كلاس من نوع TestTable الى المتغير testTable ليتم بعد ذلك اسناد البيانات الجديدة أو المحدثة الى الحقول الموجودة في الكلاس ليتم بعد ذلك اسناد الـ testTable الى دالة التحديث UpdateTest لتحديث البيانات.

الحدث DeleteButton_Click:
PHP كود :
private void DeleteButton_Click(object senderEventArgs e)
 
       {
 
           if (_id == null) return;
 
           if (sqliteManipulation.DeleteTest(_id))
 
           {
 
               GetAll();
 
               Toast.MakeText(this"The data deleted"ToastLength.Long).Show();
 
           }
 
           else
            
{
 
               Toast.MakeText(this"The data failed to delete"ToastLength.Long).Show();
 
           }
 
       


شرح الكود أعلاه: يتم اسناد المتغير الذي يحمل التسلسل الـid_ المراد حذف بياناتها الى دالة DeleteTest ليتم حذفها من قاعدة البيانات.

الحدث SearchText_QueryTextChange:

PHP كود :
private void SearchText_QueryTextChange(object senderSearchView.QueryTextChangeEventArgs e)
 
       {
 
           var test testList.Where(ss => ss.TestName.ToLower().Trim().Contains(e.NewText.ToLower().Trim())).FirstOrDefault();


 
           idView.Text test?.Id.ToString();
 
           nameText.Text test?.TestName;
 
           adressText.Text test?.TestAdress;
 
           ageText.Text test?.TestAge.ToString();
 
           _id test?.Id;
 
       

شرح الكود أعلاه: يتم عملية البحث داخل testList عن طريق الاسم وذلك باستخدام تقنية Linq ثم يتم اسناد الناتج الى الادوات لعرضها، ويتم اسناد التسسلسل الى متغير id_ لغرض عمليات الحذف والتعديل.

أما رمز ? فهي تعمل في حالة عدم وجود ناتج لعملية البحث، بحيث بدلاً من حدوث استثناء سيتم اسناد القيم الافتراضية الى الاداوت وبذلك سنتجنب توقف التطبيق عن العمل.



الى هنا انتهينا ولله الحمد من عمل تطبيق أندرويد باستخدام فيجوال ستوديو 2017 وبتقنية Xamarin.


في المرحلة القادمة باذن الله سأضع الاكواد في الـ GitHub وسيتم نشرها في هذا الموضوع.


والسلام عليكم ورحمة الله 




RE: SQLite in Xamarin.Android Part2 - حريف برمجة - 14-02-18

جزاك الله خير .