You are on page 1of 18

Fragments

• we can only show a single Activity on the screen at one given point of time so
we were not able to divide the screen and control different parts separately.
With the help of Fragment’s we can divide the screens in different parts and
controls different parts separately.
• By using Fragments we can comprise multiple Fragments in a single Activity.
Fragments have their own events, layouts and complete life cycle. It provide
flexibility and also removed the limitation of single Activity on the screen at a
time.
Fragments offer an escape solution.
‫• يمكننا فقط عرض نشاط واحد على الشاشة في وقت معين لذلك لم نتمكن من تقسيم الشاشة‬
‫ يمكننا تقسيم‬،Fragment’s ‫ بمساعدة‬.‫والتحكم في أجزاء مختلفة بشكل منفصل‬
.‫الشاشات إلى أجزاء مختلفة والتحكم في أجزاء مختلفة بشكل منفصل‬
‫ األجزاء لها أحداثها‬.‫ يمكننا تكوين أجزاء متعددة في نشاط واحد‬، ‫• باستخدام األجزاء‬
‫ إنه يوفر المرونة ويزيل أيضًا قيود نشاط واحد على‬.‫وتخطيطاتها ودورة حياتها الكاملة‬
.‫الشاشة في كل مرة‬
) ‫ (من هذه المشكلة‬.‫• شظايا تقدم حال للهروب‬
• Fragments must exist within the boundaries of an Activity that acts as a
‘home-base’ or host.
• We can add , replace or remove Fragment’s in an Activity while the activity
is running.
• Fragments has its own layout and its own behavior with its own life cycle
callbacks.
• Fragment can be used in multiple activities.
• We can also combine multiple Fragments in a single activity.

.‫يجب أن توجد الشظايا داخل حدود نشاط يعمل بمثابة "قاعدة منزلية" أو مضيف‬ •
.‫يمكننا إضافة أو استبدال أو إزالة جزء في نشاط أثناء تشغيل النشاط‬ •
‫األجزاء لها تخطيطها الخاص وسلوكها الخاص مع عمليات االسترجاعات لدورة الحياة‬ •
.‫الخاصة بها‬
.‫يمكن استخدام جزء في أنشطة متعددة‬ •
.‫يمكننا أيضًا دمج أجزاء متعددة في نشاط واحد‬ •

Fragments could access ‘global data’ held in the main activity to which
they belong. Likewise, they could send values of their own to the main
activity for potential dissemination ) ‫ (النشر محتمل‬to other fragments.
Fragments have their own particular Life-Cycle, in which the
onCreateView method does most of the work needed to make them.

‫• يمكن لألجزاء الوصول إلى "البيانات العالمية" الموجودة في النشاط الرئيسي الذي تنتمي‬
‫ يمكنهم إرسال القيم الخاصة بهم إلى النشاط الرئيسي للنشر المحتمل (النشر‬، ‫ وبالمثل‬.‫إليه‬
.‫محتمل) إلى أجزاء أخرى‬
‫ حيث يكون ملف‬، ‫• لألجزاء دورة حياة خاصة بها‬
.‫بمعظم العمل المطلوب إلنجازها‬onCreateView ‫• تقوم طريقة‬
Fragments: Modularity
• On larger screens: the app should display a static navigation drawer and a
list in a grid layout.
• On smaller screens; the app should display a bottom navigation
bar and a list in a linear layout.
—Separating the navigation elements from the content can make this process
more manageable. The activity is then responsible for displaying the
correct navigation UI while the fragment displays the list with the proper
layout.

‫ يجب أن يعرض التطبيق درج تنقل ثاب ًتا وقائمة في تخطيط‬:‫• على الشاشات األكبر حجمًا‬
.‫الشبكة‬
.‫• على الشاشات األصغر ؛ يجب أن يعرض التطبيق شريط تنقل سفلي وقائمة بتنسيق خطي‬
‫• يمكن أن يؤدي فصل عناصر التنقل عن المحتوى إلى جعل هذه العملية أكثر قابلية‬
‫ يكون النشاط بعد ذلك مسؤوالً عن عرض واجهة مستخدم التنقل الصحيحة بينما‬.‫لإلدارة‬
.‫يعرض الجزء القائمة بالتخطيط المناسب‬
Fragment:
• We can create Fragments by :
1. extending Fragment class: For creating a Fragment firstly we extend
the Fragment class, then we must override key lifecycle methods
onCreateView() to define the layout and in order to run a Fragment.
import android.os.Bundle;
import
android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class FirstFragment extends

Fragment { @Override

public View onCreateView(LayoutInflater inflater, ViewGroup


container, Bundle savedInstanceState)
{ // Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false); }}

return a View component from this method that is the root of the fragment’s layout.
:‫يمكننا إنشاء شظايا من خالل‬
‫ ثم يجب علينا تجاوز‬،Fragment ‫ نقوم بتوسيع فئة‬، ً‫إلنشاء جزء أوال‬Fragment: ‫توسيع فئة‬.1
‫لتعريف التخطيط ومن أجل تشغيل جزء‬onCreateView () ‫طرق دورة حياة المفتاح‬
‫إرجاع مكون عرض من هذه الطريقة التي تمثل جذر تخطيط الجزء‬
• We can create Fragments by :
2. or by inserting a Fragment into our Activity layout: by declaring
the Fragment in the activity’s layout file, as a <fragment> element.
We can manipulate each Fragment independently, such as add or
remove them.
Basic Fragment Code In XML:
<?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"
xmlns:tools="http://schemas.android.com/tools" :‫يمكننا إنشاء شظايا من خالل‬ •
android:layout_width="fill_parent" ‫ أو عن طريق إدراج جزء في تخطيط‬.2 •
android:layout_height="fill_parent"
tools:context=".MainActivity"> ‫ عن طريق إعالن الجزء في ملف‬:‫النشاط لدينا‬
<fragment fragment>.< ‫ كعنصر‬، ‫تخطيط النشاط‬
android:id="@+id/fragments“android:lay ‫ مثل‬، ‫يمكننا معالجة كل جزء بشكل مستقل‬ •
out_width="match_parent" ‫اإلضافة أو الحذف‬
android:layout_height="match_parent" />
</LinearLayout>
– We can manipulate each Fragment independently, such as add or remove them.

‫ مثل إضافته أو إزالته‬، ‫يمكننا معالجة كل جزء بشكل مستقل‬


Fragment:
There are some primary classes related to Fragment’s are:
1. FragmentActivity: The base class for all activities using
compatibility based Fragment (and loader) features.
2. Fragment: The base class for all Fragment definitions
3. FragmentManager: The class for interacting with Fragment objects
inside an activity
4. FragmentTransaction: The class for performing an atomic set of Fragment
operations such as Replace or Add a Fragment.

Fragment’s: ‫هناك بعض الفئات األساسية المتعلقة بـ‬


‫الفئة األساسية لجميع األنشطة التي تستخدم ميزات التجزئة‬FragmentActivity: .1
.‫(والمحمل) القائمة على التوافق‬
‫ الفئة األساسية لكافة تعريفات الجزء‬:‫ جزء‬.2
‫فئة التفاعل مع كائنات جزء داخل نشاط‬FragmentManager: .3
‫فئة تنفيذ مجموعة صغيرة من عمليات التجزئة مثل‬FragmentTransaction: .4
.‫استبدال أو إضافة جزء‬
Types of Fragments
• Single frame fragments: Single frame fragments are using for handheld
devices like mobiles, here we can show only one fragment as a view.
• List fragments: fragments having a special list view is called a list fragment
• Fragments transaction: Using the fragment transaction, we can move
one fragment to another fragment.
‫ تستخدم شظايا اإلطار الفردي لألجهزة المحمولة مثل الهواتف‬:‫ شظايا اإلطار الفردي‬.1
‫ تسمى األجزاء‬:‫ أجزاء القائمة‬.‫ وهنا يمكننا إظهار جزء واحد فقط كعرض‬، ‫المحمولة‬
، ‫ باستخدام المعاملة الجزئية‬:‫التي لها عرض قائمة خاص جزء القائمة معاملة تجزئة‬
.‫يمكننا نقل جزء إلى جزء آخر‬
Fragments transaction:
• An application initially calls the startActivity method to display an
instance of Activity 1. Activity 1 is automatically added to the back stack
and is currently at the top of the stack.
• Activity 1 then calls the startActivity method to display Activity2, which
uses the FragmentTransaction.add method to
add FragmentA. Activity2 is automatically added to the top of the back
stack.
• Next, Activity2 uses the FragmentTransaction.replace method to
display FragmentB in place of FragmentA. As far as the user is concerned,
the application displays a new screen showing the contents of FragmentB.
The problem is that the back stack is unchanged.
• transaction.replace(FragmentA, FragmentB)
• When the user now taps the back button, his/her expectation is that the app
should display the previous screen, FragmentA; Instead, when Android
pops the back stack, the next screen it encounters is Activity 1.
• [Solution] - addToBackStack() method
We resolve this issue by calling
the FragmentTransaction class’ addToBackStack method within
the FragmentTransaction instance that displays FragmentB.
‫لعرض مثيل من النشاط‬startActivity ‫يقوم أحد التطبيقات في البداية باستدعاء طريقة‬ •
.‫ تلقائيًا إلى المكدس الخلفي وهو حاليًا في أعلى المكدس‬1 ‫ تتم إضافة النشاط‬.1
‫ والذي يستخدم طريقة‬، 2 ‫لعرض النشاط‬startActivity ‫ طريقة‬1 ‫يستدعي النشاط‬ •
‫ تلقائيًا‬2 ‫تتم إضافة النشاط‬FragmentA. ‫إلضافة‬FragmentTransaction.add
.‫إلى أعلى المكدس الخلفي‬
‫لعرض‬FragmentTransaction.replace ‫طريقة‬Activity2 ‫ يستخدم‬، ‫بعد ذلك‬ •
‫ يعرض‬، ‫بقدر ما يتعلق األمر بالمستخدم‬FragmentA. ‫بدالً من‬FragmentB
‫المشكلة هي أن المكدس الخلفي‬FragmentB. ‫التطبيق شاشة جديدة تعرض محتويات‬
.‫لم يتغير‬
FragmentB) ،transaction.replace (FragmentA •
‫ فإن توقعه هو أن التطبيق يجب أن يعرض‬، ‫عندما ينقر المستخدم اآلن على زر الرجوع‬ •
‫الحزمة‬Android ‫ عندما يظهر‬، ‫؛ بدالً من ذلك‬FragmentA ، ‫الشاشة السابقة‬
.1 ‫ فإن الشاشة التالية التي يواجهها هي النشاط‬، ‫الخلفية‬
addToBackStack () ‫ طريقة‬- ]‫[الحل‬ •
‫لفئة‬addToBackStack ‫تم حل هذه المشكلة عن طريق استدعاء طريقة‬ •
‫الذي يعرض‬FragmentTransaction ‫داخل مثيل‬FragmentTransaction
FragmentB.
Fragment’s lifecycle:
• In Android, Fragment is a part of an activity, fragment is a
kind of sub-activity. It represents a behavior or a portion of user
interface in an Activity.
• We can combine multiple Fragments in single Activity to build
a multi pane UI and reuse a Fragment in multiple Activities.
• A fragment must always be embedded in an activity and the
fragment’s life-cycle is directly affected by the host activity’s
life-cycle.
• In Android, Fragments have their own life cycle very similar
to an Activity but it has extra events that are particular to the
Fragment’s view hierarchy, state and attachment to its activity.

‫ أما الجزء فهو نوع من النشاط‬، ‫جزءًا من نشاط‬Fragment ‫ يعد‬،Android ‫في‬ •


.‫ يمثل سلو ًكا أو جزءًا من واجهة المستخدم في النشاط‬.‫الفرعي‬
‫يمكننا دمج أجزاء متعددة في نشاط واحد لبناء واجهة مستخدم متعددة األجزاء وإعادة‬ •
.‫استخدام جزء في أنشطة متعددة‬
‫يجب دائمًا تضمين جزء في نشاط ما وتتأثر دورة حياة الجزء بشكل مباشر بدورة حياة‬ •
.‫النشاط المضيف‬
، ‫بدورة حياتها الخاصة تشبه إلى حد بعيد نشاط ما‬Fragments ‫ تتمتع‬،Android ‫في‬ •
‫ والحالة‬، ‫ولكنها تحتوي على أحداث إضافية خاصة بالتسلسل الهرمي لعرض الجزء‬
.‫والمرفق بنشاطه‬

Fragment’s lifecycle:
The list of methods which you can to override in your Fragment class:
Fragment’s lifecycle:
1. onAttach(): The fragment instance is
associated with an activity instance.
This method is called first, even before
onCreate() method.
This method let us know that our Fragment has
been attached to an activity.
@Override
public void onAttach(Activity activity) {
super. onAttach(activity);
// add your code here which executes when fragment
//instance is associated}
‫ تسمى هذه‬.‫ يرتبط مثيل الجزء بنسخة النشاط‬:)( onAttach .
‫ تتيح لنا هذه‬.)( onCreate ‫ حتى قبل طريقة‬، ً‫الطريقة أوال‬
.‫الطريقة معرفة أن الجزء الخاص بنا قد تم إرفاقه بنشاط ما‬
2.onCreate(): This will be called when
creating the fragment
It means when a new fragment instance
initializes which always happens after it
attaches to the host
@Override
public void onCreate(Bundle savedlnstanceState ‫سيتم استدعاء هذا عند إنشاء الجزء‬.2
super.onCreate(savedlnstanceState); ‫هذا يعني أنه عند تهيئة مثيل جزء جديد والذي‬
// add your code here which executes when fragment’s ‫يحدث دائمًا بعد إرفاقه بالمضيف‬
//instance initializes
3. onCreateView(): Most of the work is done here.
The will be called when it’s time for the fragment to draw its
UI(user interface) for the first time.
To draw a UI for our fragment we must return a View component
from this method that is the root of our fragment’s layout.
We can also return null if the fragment does not provide a UI.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedlnstanceState)
{View v =
inflater. inflate(R. lay out. fragment_test, container, false); //
add your code here to draw the UI for the first
// time means in this method we can get the //reference of
// the views which are created in our xml file
return v; }
inflatefint resource, MewGroup root, boolean attachToRoot)
Inflate a new view hierarchy from the specified xml resource.
.‫يتم تنفيذ معظم العمل هنا‬.3
.‫سيتم استدعاء الجزء عندما يحين وقت رسم الجزء لواجهة المستخدم (واجهة المستخدم) ألول مرة‬
‫ يجب أن نعيد مكون العرض من هذه الطريقة التي تمثل جذر‬، ‫لرسم واجهة مستخدم للجزء الخاص بنا‬
.‫تخطيط الجزء الخاص بنا‬
ً ‫يمكننا أي‬
.‫ضا إرجاع قيمة خالية إذا كان الجزء ال يوفر واجهة مستخدم‬
Fragment’s lifecycle:
5.onActivityCreated(): This method is called after
the onCreateView() method when the host activity is
created.
This method indicates that the activity's onCreate
has completed
@Override
public void onActivityCreated(Bundle
savedlnstanceState
{ super.onActivityCreated(savedlnstanceState);
// add your code here which executes when the host activity
//is created.
onCreateView ‫ تستدعى هذه الطريقة بعد طريقة‬.5 •
.‫)(عند إنشاء نشاط المضيف‬
onCreate ‫تشير هذه الطريقة إلى اكتمال نشاط‬ •

6. onStart(): This method is called once the fragment


gets visible.
@Override
public void onStart() {
super. onStartQ;
// add your code here which executes when the Fragment gets visible.
}
.‫تستدعى هذه الطريقة بمجرد ظهور الجزء‬.6
7. onResume(): This method is called when the fragment is
visible becomes interactive.
@Override public void onResume()
‫ تستدعى هذه الطريقة عندما يصبح الجزء‬.7
{ super. onResume();
// add your code here which executes when the Fragment is visible
.‫المرئي تفاعليًا‬
and intractable.
} 8. onPause(): This method is the first indication that:

1- the user is leaving the current fragment, or


2-fragment is no longer interactable.
It occurs when any Fragment Transition processed or
Fragment is removed. ‫ خروج المستخدم‬-1 :‫ هذه الطريقة هي أول إشارة إلى أن‬.8 •
@Override ‫ أو‬، ‫من الجزء الحالي‬
public void onPause() { .‫الشظية لم تعد قابلة للتفاعل‬-2 •
super. onPause(); .‫يحدث ذلك عند معالجة أي جزء من عملية النقل أو إزالة جزء‬ •
// add your code here which executes when user leaving the
//current fragment or fragment is no longer intractable.
}
Fragment’s lifecycle:
9. onStop(): This method is called after onPause()
method,This method calls when the Fragment
is no longer visible.
it occurs either after the fragment is about to
be removed or Fragment Transition is
processed (replace Fragment) or when the
host activity stops.
‫ تستدعي‬،onPause () ‫تستدعى هذه الطريقة بعد طريقة‬.9
.‫هذه الطريقة عندما ال يكون الجزء مرئيًا‬
‫يحدث إما بعد أن يكون الجزء على وشك اإلزالة أو بعد معالجة‬
.‫انتقال الجزء (استبدال الجزء) أو عند توقف نشاط المضيف‬
@Override
public void onStop()
{ super. onStop();
// add your code here which executes Fragment going to be stopped.

10. onDestroyView(): This method is called


when the view and other related resources
created in onCreateView() method is
removed from the activity’s view
hierarchy and destroyed.
@Override
public void on Destroy View( ) {
super.onDestroyView(); // add your code here
which executes //when the view's and other
related resources created in //onCreateView()
method are removed

‫ يتم استدعاء هذه الطريقة عند إزالة العرض والموارد األخرى ذات الصلة التي تم‬.10
.‫ من التسلسل الهرمي لعرض النشاط وإتالفها‬onCreateView () ‫إنشاؤها في طريقة‬
Fragment’s lifecycle:
11. onDestroy(): This method is called to do
final clean up of the Fragment’s state but
Not guaranteed to be called by the Android
platform.
This method called after onDestroyView()
method.
@Override
public void onDestroy() {
super.onDestroy(); // add your code here which
//executes when the final clean up for the
//Fragment's state is needed.
} ‫يُطلق على هذه الطريقة إجراء التنظيف النهائي‬.11
‫لحالة الجزء ولكن ليس مضمو ًنا أن يتم استدعاؤها‬
‫ تسمى هذه‬.‫ األساسي‬Android ‫بواسطة نظام‬
.)( onDestroyView ‫الطريقة بعد طريقة‬
12.onDetach(): This method called after
onDestroy() method to notify that the fragment
has been disassociated from its hosting activity
means Fragment is detached from its host
Activity ‫ تستدعى هذه الطريقة بعد طريقة‬.12
@Override ‫لإلعالم بأن الجزء قد تم فصله‬onDestroy ()
public void onDetach() { ‫عن نشاط االستضافة الخاص به مما يعني فصل‬
super.onDetach(); ‫الجزء عن نشاط المضيف الخاص به‬
// add your code here which executes when
fragment has been //disassociated from its
hosting activity
}
Android SQLite: Prosperities
• Zero-Configuration:
•There is no server process that needs to be started, stopped, or configured.
•Nothing needs to be done to tell the system that SQLite is running.
• Serverless:
Most SQL database engines are implemented as a separate server process.
Programs that want to access the database communicate with the server using
some kind of interprocess communication (typically TCP/IP) to send requests to
the server and to receive back results. SQLite does not work this way.
With SQLite, the process that wants to access the database reads and writes
directly from the database files on disk. There is no intermediary server
process.
• Single Database File:
a single ordinary disk file can easily be copied onto a USB memory stick or
emailed for sharing.
• Stable Cross-Platform Database File:
A database file written on one machine can be copied to and used on a different
machine with a different architecture. Newer versions of SQLite can read and
write older database files.
• Compact:
the whole SQLite library with everything enabled is less than 500KiB in size.

:‫التكوين الصفري‬ •
.‫ال توجد عملية خادم تحتاج إلى أن تبدأ أو تتوقف أو تهيئ‬ •
.‫يعمل‬SQLite ‫ال يلزم فعل أي شيء إلخبار النظام بأن‬ •
:‫بدون خادم‬ •
‫ تتواصل البرامج التي‬.‫كعملية خادم منفصلة‬SQL ‫يتم تنفيذ معظم محركات قاعدة بيانات‬ •
‫ترغب في الوصول إلى قاعدة البيانات مع الخادم باستخدام نوع من االتصال بين العمليات‬
‫ سكليتي ال‬.‫إلرسال الطلبات إلى الخادم واستالم النتائج مرة أخرى‬TCP / IP) ‫(عاد ًة‬
.‫يعمل بهذه الطريقة‬
‫ فإن العملية التي تريد الوصول إلى قاعدة البيانات تقرأ وتكتب‬،SQLite ‫باستخدام‬ •
.‫ ال توجد عملية خادم وسيط‬.‫مباشرة من ملفات قاعدة البيانات الموجودة على القرص‬
:‫ملف قاعدة بيانات واحد‬ •
‫أو إرسالها بالبريد‬USB ‫يمكن بسهولة نسخ ملف قرص عادي واحد على ذاكرة‬ •
.‫اإللكتروني للمشاركة‬
:‫ملف قاعدة بيانات مستقر عبر األنظمة األساسية‬ •
‫يمكن نسخ ملف قاعدة البيانات المكتوب على جهاز واحد واستخدامه على جهاز مختلف‬ •
‫قراءة ملفات قاعدة البيانات‬SQLite ‫ يمكن لإلصدارات األحدث من‬.‫بهندسة مختلفة‬
.‫القديمة وكتابتها‬
:‫المدمج‬ •
.‫ كيلوبايت‬500 ‫بأكملها مع تمكين كل شيء أقل من‬SQLite ‫حجم مكتبة‬ •
Android SQLite: Prosperities
• manifest typing:
the datatype is a property of the value itself, not of the column in which the
value is stored. SQLite thus allows the user to store any value of any datatype
into any column regardless of the declared type of that column. (There are
some exceptions to this rule: An INTEGER PRIMARY KEY column may
only store integers.
• Variable-length records:
SQLite use only the amount of disk space actually needed to store the
information in a row. If you store a single character in a VARCHAR(IOO)
column, then only a single byte of disk space is consumed.
• lightweight database:
in Android there is Database Management System (DBMS) called SQLite
which is a very lightweight database included with Android Architecture ,
SQLite can be used to:
1. Create a database,
2. Define: (SQLite tables, queries, ...).
3. (Insert, Delete, change ) rows.
Android SQLite combines a clean SQL interface with a very small memory
footprint and decent speed.

:‫الكتابة الواضحة‬ •
‫ وبالتالي‬.‫ وليس للعمود الذي يتم تخزين القيمة فيه‬، ‫نوع البيانات هو خاصية للقيمة نفسها‬ •
‫للمستخدم بتخزين أي قيمة من أي نوع بيانات في أي عمود بغض النظر‬SQLite ‫يسمح‬
‫ قد يخزن عمود‬:‫ (هناك بعض االستثناءات لهذه القاعدة‬.‫عن النوع المعلن لذلك العمود‬
ً
.‫أعدادا صحيحة فقط‬ INTEGER PRIMARY KEY
:‫سجالت متغيرة الطول‬ •
‫فقط مقدار مساحة القرص الالزمة فعليًا لتخزين المعلومات في صف‬SQLite ‫يستخدم‬ •
‫ فسيتم استهالك‬،VARCHAR (IOO) ‫ إذا قمت بتخزين حرف واحد في عمود‬.‫واحد‬
.‫بايت واحد فقط من مساحة القرص‬
:‫قاعدة بيانات خفيفة الوزن‬ •
‫وهي‬SQLite ‫يسمى‬DBMS) ( ‫نظام إدارة قواعد البيانات‬Android ‫يوجد في نظام‬ •
‫ ويمكن‬،Android Architecture ‫قاعدة بيانات خفيفة الوزن ج ًدا متضمنة في‬
:‫من أجل‬SQLite ‫استخدام‬
، ‫إنشاء قاعدة بيانات‬ •
.)... ، ‫ استعالمات‬،SQLite ‫ (جداول‬:‫حدد‬ •
.)‫ تغيير‬، ‫ حذف‬، ‫صفوف (إدراج‬ •
‫النظيفة مع مساحة ذاكرة صغيرة ج ًدا‬SQL ‫بين واجهة‬Android SQLite ‫يجمع‬ •
.‫وسرعة مناسبة‬
Android SQLite: SQLiteOpenHelper
SQLite is a typical relational database, containing tables (which consists
of rows and columns), indexes etc. We can
create our own tables to hold the data accordingly. This structure is
referred to as a schema.
Android has features available to handle changing database schemas, which
mostly depend on using the SQLiteOpenHelper class.
SQLiteOpenHelper is designed to get rid of two very common
problems.
1. When the application runs the first time - At this point, we do not yet have a
database. So we will have to create the tables, indexes, starter data, and so on.
2. When the application is upgraded to a newer schema - Our database will still be
on the old schema from the older edition of the app. We will have option to alter
the database schema to match the needs of the rest of the app.
، )‫ تحتوي على جداول (تتكون من صفوف وأعمدة‬، ‫هي قاعدة بيانات عالئقية نموذجية‬SQLite •
‫ يمكننا ذلك‬.‫ إلخ‬، ‫وفهارس‬
.‫ يشار إلى هذا الهيكل على أنه مخطط‬.‫إنشاء الجداول الخاصة بنا لالحتفاظ بالبيانات وف ًقا لذلك‬ •
‫ والتي تعتمد‬، ‫على ميزات متاحة للتعامل مع مخططات قواعد البيانات المتغيرة‬Android ‫يحتوي‬ •
SQLiteOpenHelper. ‫في الغالب على استخدام فئة‬
.‫للتخلص من مشكلتين شائعتين ج ًدا‬SQLiteOpenHelper ‫تم تصميم‬ •
‫ لذلك سيتعين‬.‫ ليس لدينا قاعدة بيانات بعد‬، ‫ في هذه المرحلة‬- ‫عندما يتم تشغيل التطبيق ألول مرة‬ •
.‫علينا إنشاء الجداول والفهارس وبيانات البداية وما إلى ذلك‬
‫ ستظل قاعدة البيانات الخاصة بنا على المخطط القديم من‬- ‫عندما تتم ترقية التطبيق إلى مخطط أحدث‬ •
‫ سيكون لدينا خيار لتغيير مخطط قاعدة البيانات لتتناسب مع احتياجات‬.‫اإلصدار األقدم من التطبيق‬
.‫بقية التطبيق‬

SQLiteOpenHelper create and upgrade a database as per our


specifications. For that we’ll need to create a custom subclass of
SQLiteOpenHelper implementing at least the following three
methods:
1. Constructor.
2. onCreate(SQLiteDatabase db)
3. onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

‫ لذلك سنحتاج إلى‬.‫بإنشاء قاعدة بيانات وترقيتها وف ًقا لمواصفاتنا‬SQLiteOpenHelper ‫• يقوم‬


‫تنفذ على األقل الثالثة التالية‬SQLiteOpenHelper ‫إنشاء فئة فرعية مخصصة من‬
:‫طرق‬ ُ •
.‫ البناء‬.1
onCreate (SQLiteDatabase db) .2
int newVersion) ،int oldVersion ،SQLiteDatabase db ( ‫ عند الترقية‬.3
Android SQLite: SQLiteQpenHelper
• Constructor : This takes the Context (e.g., an Activity), the name of
the database, an optional cursor factory )we’ll discuss
this later), and an integer representing the version of the database
schema you are using (typically starting from 1 and increment later).
public class DatabaseHelper extends SQLiteOpenHelper{ public
DatabaseHelper (Context context) {
super(context, DB NAME, null, DB VERSION); }}
‫ ومصنع‬، ‫ واسم قاعدة البيانات‬، )‫ نشاط‬، ‫ يأخذ هذا السياق (على سبيل المثال‬:‫المُنشئ‬
ً
‫وعددا صحيحً ا يمثل إصدار مخطط قاعدة البيانات‬ ، )‫مؤشر اختياري (سنناقش هذا الح ًقا‬
.)‫ ويزيد الح ًقا‬1 ‫الذي تستخدمه (يبدأ عاد ًة من‬

• onCreate( SQLiteDatabase db): It s called when there is no


database and the app needs one It passes us a SQLiteDatabase object,
pointing to a newly created database, that we can populate with tables
and initial data
@Override
public void onCreate (SQLiteDatabase db) {
db.execSQL (CREATETABLE); }
‫ يمرر لنا كائن‬.‫يطلق عليه في حالة عدم وجود قاعدة بيانات ويحتاج التطبيق إلى واحدة‬
ً
‫ يمكننا ملؤها بالجداول‬، ‫حديثا‬ ‫ مشيرً ا إلى قاعدة بيانات تم إنشاؤها‬،SQLiteDatabase
‫والبيانات األولية‬
• onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
:It’scalled when the schema version we need
does not match the schema version of the database, It passes us a
SQLiteDatabase object and the old and new version numbers.
• It is the best way to convert the database from the old schema to the
new one:
@Override
public void onUpgrade (SQLiteDatabase db, int oldVersion, int
newVersion)
{ db.execSQL ("DROP TABLE IF EXISTS " + TABLE NAME);
onCreate(db);}
• execSQL(String sql)Execute a single SQL statement that is NOT
a SELECT or any other SQL statement that returns data.
، ‫يتم استدعاؤه عندما ال يتطابق إصدار المخطط الذي نحتاجه مع إصدار مخطط قاعدة البيانات‬ •
.‫وأرقام اإلصدار القديم والجديد‬SQLiteDatabase ‫ويمرر إلينا كائن‬
:‫إنها أفضل طريقة لتحويل قاعدة البيانات من مخطط قاعدة البيانات القديم إلى المخطط الجديد‬ •

‫أو أي عبارة‬SELECT ‫واحدة ليست عبارة‬SQL ‫تنفيذ جملة‬execSQL (String sql) •


.‫أخرى تقوم بإرجاع البيانات‬SQL
Android SQLite: SOLiteOpenHelper
defining with DatabaseHelper, which is a subclass of SQLiteOpenHelper as
follows: DatabaseHelperjava
package com.journaldev.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper { Example


// Table Name
public static final String TABLE_NAME = "COUNTRIES";
DatabaseHelper.j ava
// Table columns
public static final String _ID = "_id";
public static final String SUBJECT = "subject";
public static final String DESC = "description";
// Database Information
static final String DB_NAME = "JOURNALDEVCOUNTRIES.DB";
// database version
static final int DB_VERSION = 1;
// Creating table query
private static final String CREATE_TABLE = "create table " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY
AUTOINCREMENT, " + SUBJECT + " TEXT NOT NULL, " + DESC + " TEXT);";

public DatabaseHelper(Context context) {


super (context, DB_NAME, null, DB_VERSION); } ‫ وهو فئة‬DatabaseHelper ‫التعريف باستخدام‬
@Override ‫ على النحو‬SQLiteOpenHelper ‫فرعية من‬
public void onCreate (SQLiteDatabase db)
{ db.execSQL(CREATE_TABLE); }
DatabaseHelper java ‫التالي‬
@Override
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)
{ db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db); } }

Opening and Closing Android SQLite Database Connection:


‫فتح وإغالق اتصال قاعدة بيانات‬
• We define a DBManager class to perform all database CRUD(Create, Read,
Update and Delete) operations.
• Before performing any database operations like insert, update, delete records
in a table, first open the database connection by calling
getWritableDatabase() method as shown below:
public DBManager open() throws
SQLException { dbHelper = new
DatabaseHelper(context); database =
dbHelper.getWritableDatabase(); return
this; }
The dbHelper is an instance of the subclass of SQLiteOpenHelper i.e
(DatabaseHelper in DatabaseHelper.java )
• To close a database connection the following method is invoked:
public void close() {
dbHelper.close(); }
‫ (إنشاء‬CRUD ‫ ألداء جميع عمليات قاعدة البيانات‬DBManager ‫• نحدد فئة‬
.)‫وقراءة وتحديث وحذف‬
، ‫ حذف سجالت في جدول‬، ‫ تحديث‬، ‫• قبل إجراء أي عمليات قاعدة بيانات مثل إدراج‬
‫افتح أوالً اتصال قاعدة البيانات عن طريق استدعاء طريقة‬
:‫كما هو موضح اعاله‬getWritableDatabase ()
)‫ واغالقه‬dbhelper ‫• (أيضا بالنسبة لل‬
inserting new Record into Android SQLite database table
• inserting a new record in the android SQLite database.

public void insert (String name, String desc) {


Content Values content Value = new Content ValuesQ;
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
database. insert(DatabaseHelper. TABLE_NAME, null, content Value); }

Content Values creates an empty set of values.


Updating deleting Record in Android SQLite
database table
Updating:The following snippet shows how to update a single record.
public int update (long id, String name, String desc) {
ContentValues contentvalues = new ContentValues(); content
Values .put(DatabaseHelper. SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
int i = database.update(DatabaseHelper.TABLE_NAME,
contentvalues, DatabaseHelper.ID + " = " + id, null); return i;}
Deleting: We just need to pass the id of the record to be deleted as shown
below:
public void delete (long id) {
database.delete(DatabaseHelper. TAB LENAME,
DatabaseHelper._ID + "=" + id, null); }
Defining DBManager java as follows:
package com.journaldev.sqlite;
import android.content.ContentValues; import
android.content.Context; import
android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBManager { private
DatabaseHelper dbHelper; private Context Example
context; DBManager. j ava
private SQLiteDatabase database;
public DBManager(Context c) { context = c; }
public DBManager open () throws SQLException
{ dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase(); return
this; }
public void close () { dbHelper.close(); }
public void insert (String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValue); }
public Cursor fetch () { String[] columns = new String[]
{ DatabaseHelper._ID, DatabaseHelper.SUBJECT,DatabaseHelper.DESC };
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null,
null, null, null, null); if (cursor != null) { cursor.moveToFirst(); } return cursor; }
public int update (long _id, String
name, String desc) { ContentValues
contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SU
BJECT, name);
contentValues.put(DatabaseHelper.DE
SC, desc);
int i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID
+ " = " + _id, null); return i; }
public void delete (long _id) {
database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null); } }
Android SQLite
• An alternative way of opening/creating a SQLite database in Android’s internal
data space is given below:

SQLiteDatabase db = this.openOrCreateDatabase( “myfriendsDB”


MODE-PRIVATE, null);//!Equivalent to openDatabase();

- Con text. MOD EPRIVATE indicates that the database hie can only be
accessed by the calling application or all applications sharing the same user ID.
- The third parameter is a Cursor factory object which can be left null if not
required.
‫يشير إلى أنه ال يمكن الوصول إلى قاعدة البيانات إال عن طريق تطبيق االتصال أو‬
.‫جميع التطبيقات التي تشترك في نفس معرف المستخدم‬
.‫ المعلمة الثالثة هي كائن مصنع المؤشر الذي يمكن تركه فار ًغا إذا لم يكن مطلوبًا‬-

• Once a database is created successfully located in data/data//package/


space.
• Assume this app is made in a package called
cis470.matos.sqldatabases: then the
full name of the newly created data file will be:

You might also like