Posts

Showing posts from 2012

ORM for android

     ORM – Object relational mapping has been around for quite some time now. Basically it’s a piece of software (regardless of targeted platform), which simplifies the connection between objects (as in OOP) and data in database (mostly used is tables based relational database), and it exists in order to help simplify bridging the gap between the two in our development process.     Microsoft's Entity framework is a great example for a robust easy to use framework which allows creating and querying the database from an object’s point of view with classic object oriented programming paradigms while maintaining all DB construction’s needs such as relationships between objects (tables) such as one to many or many to many including all the indexing, optimization etc..      In android, we have SQLite as a database platform, from simple to advanced application, it’s likely to assume that we’ll need some relational database to store and retrieve local data from the database using the bas

How to update UI from a different thread

     Google has set it’s tone on some tough guidelines for developing android apps, basically there aren’t any strict rules but one very easy to misunderstand. there is a single Thread which is called the “main” thread, or “UI thread” on some places. this is the thread which is in charge on the views and interaction with the users gestures. based on the guidelines of any mobile platform at the moment, all the work that shouldn’t be done on the main thread should be done on background thread. this can be achieved in many ways, you can use AsyncTask, Or A Handler, Or a simple thread with an implementation of the   run() method within the declaration of the runnable. ok, so if I’m pulling some server data, or performing long calculations, pulling stuff from or to the Sqlite database I’ll probably use an AsyncTask. but let’s say for instance that I want to simply update the UI once every couple of seconds (update a TextView or an ImageView’s content etc..), here’s a simple example of i

How to maintain global application state

       In Android application, it’s sometimes important to keep a global application state. by global application state I mean to be able to have an entry point to the application which gives us a starter place to do stuff before the application starts. this is important in many aspects, for example, the application can start from different entry points, such as the launcher, a notification, or a service, or even by responding to a certain broadcast.     There are many approaches to achieve this goal, one of them which a prefer is the Application Class, once extending the application class, we are able to load resources, setting different contexts , or even starting a certain service before the first activity starts, this is done simply by overriding the onCreate() method. Example: public class MyApplication extends Application { boolean hasAgreed; @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); // get d

Installing the development environment for android is now easier then ever

  Developing for android can a complicated task. Some developers including myself had a hard time starting with the development due to a somewhat complicated process which should be done prior to development – Installing the development enjoinment. how we used to do it: Download the SDK Download the Eclipse Download the ADT – (Android development tools) Download the plugin for eclipse (by using https://dl.google.com/ …) now it’s easier: go to https://developer.android.com/sdk/index.html , download the package and it will include all of the above. this is probably perfect for starting to develop for the Android without having to deal with the messy installation process.

Fragments–applications made modular

  The Android SDK 3.0 (Honeycomb) introduced the Fragments API. The Fragments API is basically a set of tools which allows us to create, manage and re-use Chuncks of logic and UI. For example, let’s assume I’m starting to develop an Application, which should be compatible for both Smartphones and Tablet, as well as support both orientation(landscape, portrait). It’s fairly easy to say that the same “lisviews” or forms will be used on both versions in terms of business logic and behavior with some UI adjustments. the fragments API is exactly what we need in order to do it in an elegant manner. let’s check out the following sample: public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); Button btn = (Button) findViewById(R.id.button); btn.setOnClickListener( new OnClickListener() {

Testing Android Applications

Android Testing testing in Android application can be really tricky, there’s a lot to test if we want to deliver a proper application which supports as much users as posible, here are a few tips on the what to test and how to test: Testing in Android: · Screen sizes Testing how the app is shown in different screen sizes · OS versions Apps can behave differently or even crush in some OSD versions due to lack of targeting to specific device · Densities Screen densities change from device to device, and from a UI point of view this can be real issues, having apps to look far from the designers aim · Resolutions When not targeting a specific resolution the graphics are used with OS manipulations like stretch and scale, which can be resulting in a disastrous UI and UX for the user · Functionality Basic functionality testing of the app in terms of business logic · Usability The usability angle is very important once we are handling a small device, a lack of attention to the UI and user e

תכנות לאנדרואיד בקלות פרק 15 – שימוש במצלמה

אחד השימושים היותר נפוצים במכשיר נייד בכלל וב smartphone בפרט הינו צילום תמונות, זהו דבר שכולנו עושים ואם נוכל לכלול פונקציונאליות שכזאת באפליקציות שלנו, זה בוודאי רק יוסיף. מה אנחנו צריכים בשביל לצלם תמונה? נניח לצורך הדוגמא כי יש לנו איזשהו layout עם 2 אלמנטים: - כפתור למעבר למצב מצלמה (פתיחת צמצם) Button - Imageview אשר יציג את התמונה 1. בקובץ ה manifest שלנו יש לציין permission לגישה למצלמה, זאת ע"י <uses-feature android:name="android.hardware.camera" /> 2. הרעיון הוא פשוט מאוד, אנו נפעיל Capture Intent אשר נקרא :  android.provider.MediaStore.ACTION_IMAGE_CAPTURE מה שיעביר אותנו ל Activity של המצלמה, בonActivityResult נקבל בחזרה את התמונה כחלק מה intent שיחזור מה CameraActivity(של מערכת ההפעלה) כפי שלמדנו נקבל את הintent בחזרה דרך  onActivityResult() ומשם נגזור את התמונה עצמה שחוזרת כ Bitmap עם ה key שנקרא “data” (חלק מהתיעוד של android) ולאחר מכן נציג את התמונה באותו ImageView שיועד לכך מלכתחילה. public void onCreate(Bundle savedInstanceState

תכנות לאנדרואיד בקלות פרק 14 – עבודה מול Sensors

מכשיר האנדרואיד שלנו מציע לנו בתור מפתחים ובתור משתמשים מגוון רחב של חיישנים, אותם אנו יכולים לרתום לשימושנו, ולשלב באפליקציות על מנת להעשיר את חוויית השימוש ולהציע שימושיות ברמה מאוד גבוהה למשתמשים. דוגמא לחיישנים : אור, תנועה, שדה מגנטי, תאוצה, אוריינטציה, סוללה.. וכו.. דוגמא: כרגיל אנו מדברים על Activity, שימו לב שישנו יישום של SensorListener ע"י: implements SensorListener המתודה onSensorChanged() הינה זאת שנותנת לנו לדגום את השינויים ולהציג על המסך , למעשה אנו דוגמים את האוריינטציה של המכשיר בכל רגע נתון, וכמובן המתודה  onAccuracyChanged()  כותבת ללוג את השינויים ברמת הדיוק. נקבל מופע של SensorManager  ע"י מערכת ההפעלה, ונרצה לדגום כמה נתונים: כאשר האפליקציה היא ב forground ולא ברקע, נרצה להרשם לשינויים בחיישנים אלה, כדאי לעשות את זה כאשר האפליקציה אינה ברקע על מנת לחסוך בסוללה, מכיוון שהאזנה לשינויים אלה צורכת משאבים לא מעטים. וכמובן נרצה לא להאזין לשינויים כאשר האפליקצייה ברקע בדיוק מאותם השיקולים. public class SensorDemo extends Activity implements

תכנות לאנדרואיד בקלות פרק 13 – עבודה ברקע – Services

תכנות לאנדרואיד בקלות פרק 13 – עבודה ברקע – Services מהם services? למעשה ניתן לסווג אותם כתהליכים שרצים ברקע, ללא תלות באפליקציה לדוגמא: שעון הוא service, שעון מעורר, מזג אוויר, מד סוללה, כל אלה הם services שאינם "אפליקציות במלוא מובן המילה" ורוב הפעמים גם אין להם ממשק משתמש – UI מדוע אנחנו צריכים services? מכיוון שאנחנו צריכים תהליכים שירוצו ברקע ללא התערבות שלנו, לדוגמא: Facebook, במידה וישנם עדכונים רלוונטים, אני צריך לקבל עדכון, דהיינו יש update service שרץ ברקע ודוגם את השרת כל X שניות/דקות לקבלת מידע חדש, כנ"ל עבור gmail, calendar וכו.. מה אנחנו צריכים בשביל לפתח service? 1. להצהיר עליו ב manifest שלנו, בדיוק כמו שהיינו עושים עם Activity בצורה הבאה: <service android:enabled="true" android:name=".MyService" /> כאשר ה name שלו הוא אותו השם של ה Class אותו נכתוב בסעיף הבא. 2. לכתוב את ה Service עצמו: מדובר ב service שמתחיל לנגן קובץ מדיה כשלוחצים על play, ועוצר כשלוחצים על stop כמו כן, מציג חיווים מתאימים לגבי הstate של ה serv

תכנות לאנדרואיד בקלות פרק 12 – מיקבול תהליכים - Threads

בכל פעם שאנו יוצרים אפליקציית אנדרואיד, Thread שנקרא "main" נוצר באופן אוטומטי. Thread זה המכונה גם UI THREAD, הוא חשוב מאוד משום שהוא אחראי על שיגור האירועים ליישומונים המתאימים וזה כולל את אירועי ה draw. זה גם Thread שמנהל אינטראקציה עם פקדים באנדרואיד. לדוגמה, אם אתה נוגע בכפתור על מסך, Thread UI משגר אירוע שבעצם נותן פקודה למערכת ההפעלה לפעול בהתאם. מודל Thread זה יכול להניב ביצועים גרועים ביישומי אנדרואיד מכיוון שכל הפעולות מתבצעות על אותו ה Thread, כגון עבודות חישוב ארוכות, גישה לשרת, הורדה של קבצים. אלה תהליכים שחייבים לפעול באופן מקביל ולא על ה UI thread , זאת על מנת לשמר מצב שבו האפליקציה מגיבה ולא קורסת. במידה וה UI THREAD תפוס למשך 5 שניות, אנו נקבל תוצאת ANR- Application not responding שיתבטא בקריסה של האפליקציה. מכאן מגיעה החשיבות הגדולה בעבודה Multi threaded , ותיכף נדגים כיצד זה מתבצע. public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap b = loadImageFromNetwork(); mImageView.setImageBitmap(b); } }).start(); }

תכנות לאנדרואיד בקלות פרק 11 – בסיסי נתונים Sqlite

באפליקציית mobile יש חשיבות רבה לשמירת נתונים, החשיבות נובעת מכמה סיבות עיקריות: 1. שמירה של נתונים עבור המשתמש, העדפות שלו, הגדרות וכו. 2. במידה ואין חיבור זמין לרשת, יש לאפשר לו לעבוד במצב לא מקוון. 3. תוצאות משחקים, data של אפליקצייה – יש לשמור אותם מקומית. 4. להמעיט את הגישה לשרת לצורך אחזור של מידע קבוע, זאת על מנת לחסוך גם בסוללה וגם בעלויות של מפעיל סלולרי. ישנן כמה דרכים לשמור מידע במכשיר שלנו, בפרק זה נתרכז בבסיס נתונים רלציוני מאוד נפוץ בשם sqlite Sqlite נפוצה בהרבה פלטפורמות והיא מאוד רזה, אך מאפשרת פונקציונאליות כמעט מלאה כפי שתצפו מכל בסיס נתונים רלציוני. class DB extends SQLiteOpenHelper {     final static int DB_VERSION = 1; final static String DB_NAME = "mydb.db";     Context context;     public DB(Context context) {         super(context, DB_NAME, null, DB_VERSION);         // Store the context for later use         this.context = context;     } על מנת להתחיל לעבוד עם בסיס נתונים sqlite באפליקציית אנדרואיד אנו נשתמש במחלקה שמרחיבה א

תכנות לאנדרואיד בקלות פרק 10 – ניידות בין מסכים שונים והעברת מידע בין Activities (Implicit, Explicit)

אוקיי, עד עכשיו יצרנו כמה מסכים עם כמה ממשקים נחמדים וצבעוניים, יש תפריט שהגדרנו שמאפשר לגשת להגדרות וכו.. איך אנחנו מחברים את הכל? 1. קריאה לactivity מתוך activity קיים (מעבר למסך חדש) 2. העברה של מידע ל activity 3. קבלת תשובה מactivity ל activity שקרא לו (onActivityResult) 4. implicit intent בפרק זה נלמד: הגדרה: Intent הינו אחד מהרכיבים המרכזיים במערכת ההפעלה ומהווה אבן בניין מאוד חשובה בבנית אפליקציה. Intent למעשה הוא מסר, שמכיל מספר מאפיינים וניתן להעמיס עליו data. 1. קריאה ל activity מתוך activity קיים (מעבר למסך חדש) על מנת להתחיל activity מתוך activity נוכחי יש ליצור Intent חדש, הבנאי של Intent מקבל שני פרמטרים (יש לו עוד כמה overloads אבל נתרכז כרגע באחד מהם).   Intent intent = new Intent(getApplicationContext(),NewActvitity.class); הפרמטר הראשון הוא ה context של ה activity הנוכחי, והפרמטר השני הוא השם של ה class של ה Activity השני .שאליו רוצים לעבור. לאחר הגדרת ה Intent יש לקרוא למתודה startActivity באופן הבא: startActivity(intent); או

תכנות לאנדרואיד בקלות פרק 9 – תפריטים - Menus

Menu באנדרואיד הינו אלמנט מאוד חשוב, כדאי לכלול אותו בכל אפליקציה על מנת לאפשר למשתמש להגדיר את ההגדרות וההעדפות שלו. ישנן 2 דרכים אשר באמצעותן ניתן ליצור menu: 1. ע"י xml 2. ע"י code יצירת menu ע"י XML <? xml version ="1.0" encoding ="utf-8" ? > < menu xmlns:android ="http://schemas.android.com/apk/res/android" > < item android:id ="@+id/new_game" android:icon ="@drawable/ic_new_game" android:title ="@string/new_game" android:showAsAction ="ifRoom" /> < item android:id ="@+id/help" android:icon ="@drawable/ic_help" android:title ="@string/help" /> </ menu > תחת תיקיית res צרו תיקיה בשם menu ובתוכה צרו menu.xml, זה הקובץ אשר מכיל את ההגדרות עבור התפריט בתצורה הבאה: תחת התגית של menu יש ליצור תגיות item אשר כל אחת תכיל: · Id – על מנת שנוכל להחליט בקוד מ

תכנות לאנדרואיד בקלות פרק 8 - בניית אנימציות tween, frame by frame

בפרק זה אנו נראה כיצד אנחנו יכולים להפוך את ה UI שלנו למעניין יותר ע"י שימוש ב Animation API שמגיע אלינו בתוך ה Android SDK. נתמקד בשני סוגי אנימציות עיקריים: Frame by frame, tween כמו בפעמים אחרות שנתקלנו בהן – ניתן לבצע אנימציות גם ב xml וגם בקוד. כרגע נדבר על tween animation: נבחן את קטע ה XML הבא: בתוך תיקיית res צרו תיקיית anim ובתוכה קובץ xml חדש אשר נקרא simpleanimation.xml <?xml version="1.0" encoding="UTF-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator"> <rotate android:fromDegrees="0" android:toDegrees="360" android:pivotX="50%" android:pivotY="30%" android:startOffset="250" android:duration="3000"/> <alpha android:fromAlpha="1.0" android:toAlpha="0.3" android:duration="1000"/> <scale android:fromXScale=&q

תכנות לאנדרואיד בקלות פרק - 7 שימוש ב Resources

בפרק זה אנו נראה כיצד ניתן להשתמש ב Resources, גם כאלה שאנחנו מוסיפים לפרוייקט (strings,images,sounds..) וגם כאלה שבאים מוכנים ב SDK של Android. כעת נראה דוגמא קצרה שתמחיש לנו את השימוש ב Resources ולאחר מכן ננתח אותה. דוגמת קוד: Resources res = getResources(); String name = res.getString(R.string.app_name); Log.i("test",name); ה Class Resources בעצם מייצג את ה Resources של האפליקצייה, והמתודה getResources() הינה מתודה של Activity שמספק לנו חבילה של ה Resources בתצורת key-value אשר מכילה סוג של Dictionary אשר מכיל את ה Resources של הפרוייקט. על מנת לחלץ איזשהו ערך מתוך ה resources אנו דוגמים את res באמצעות ה key המתאים, בדוגמא שלנו אני מחפש לקבל את שם האפליקציה כפי שהוגדרה בקובץ res/values/string.xml. הkey של הערך אותו אני צריך הינו app_name וכך אני בעצם יודע מה לבקש. בסופו של דבר אני כותב את הערך שחילצתי לLog על מנת לבדוק מה קיבלתי (נדבר על ה Log בפרק X) דוגמא נוספת: Drawable drawable = res.getDrawable(R.drawable.ic_launcher); String minHeight = String.

תכנות לאנרדואיד בקלות פרק 6 – בניית Layouts על ידי code

מבוא בפרק הקודם ראינו כיצד ניתן לבנות layouts (מסכים) שונים ע"י שימוש בשפת markup – XML כפי שאנחנו מכירים מפלטפורמות אחרות כגון WEB/ASP.NET או WPF. ע"פ הנחייה של Google וכל best practice שתפגשו אשר דן בסוגיה (XML או קוד), מומלץ לשתמש ב XML על מנת לבנות layouts, אך בכל זאת כדאי מאוד שנכיר גם את השיטה השניה, בנייה ע"י code. בואו נתחיל: בואו ניזכר במתודה אשר נקראית  setContentView(R.layout.main), זוהי מתודה של המחלקה Activity, אשר בבנאי שלה אנו בעצם שמים reference ל VIEW אשר יופיע לנו בזמן שהActivity הרלוונטי בפוקוס (Forground). במקרה ה XML-י הבנאי קיבל שם קובץ הLayout. כאשר אנו כותבים את כל הממשק בקוד, הוא יקבל View. בואו נראה דוגמא קצרה: נניח שאני רוצה שה VIEW של ה Activity שלי יכיל: Button – עם המלל hit me TextView - עם המלל : “hello world” כמו כן, ארצה ששני הcontrols הללו יופיעו בצורה מאונכת אחד מעל השני, וממורכזים אופקית. הקוד שיבצע את המשימה הנ"ל הינו הקוד הבא: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState

תכנות לאנרדואיד בקלות פרק 5 – בניית Layouts על ידי xml

Image
בפרק זה אנו נתקין את אופן כתיבת layouts באמצעות XML. בעיקר נתרכז בסוגי controls, ואיך כדאי לגשת לממשקים מעט מורכבים יותר מאשר תבניות סטנדרטיות. בואו ניזכר רגע באפליקציית hello world מפרק 3   < RelativeLayout xmlns:android ="http://schemas.android.com/apk/res/android" xmlns:tools ="http://schemas.android.com/tools" android:layout_width ="match_parent" android:layout_height ="match_parent" > < TextView android:layout_width ="wrap_content" android:layout_height ="wrap_content" android:layout_centerHorizontal ="true" android:layout_centerVertical ="true" android:text ="@string/hello_world" tools:context =".MainActivity" /> </ RelativeLayout > אז מה יש לנו כאן? יש לנו RelativeLayout שהוא בעצם container, נהוג להתחיל כל קובץ layout באיזשהו container שכזה. RelativeLayout בעצם הינו Layout