Tuesday, 27 September 2016


ConstraintLayout Android Studio 2.2


  • This new layout is a flexible layout manager for your app that allows you to create dynamic user interfaces without nesting multiple layouts. It is distributed as a support library that is tightly coupled with Android Studio and backwards compatible to API Level 9. 
At first glance, Constraint Layout is similar to RelativeLayout. However, the Constraint Layout was designed to be used in Studio and it can efficiently express your app design so that you rely on fewer layouts like LinearLayout, FrameLayout, TableLayout, or GridLayout. Lastly, with the built-in automatic constraints inference engine. You can freely design your UI to your liking and let Android Studio do the hard work.

What is ConstraintLayout?

ConstraintLayout  is a new type of layout that you can use in your Android App, it is compatible down to API level 9 and is part of the support library. Its aim is to reduce layout hierarchies (and improve performance of layouts) and it also reduces the complexity of trying to work with RelativeLayouts .  It is compatible with other layouts, so they can live in harmony together without having to choose one or the other.

Getting Started with ConstraintLayout:

You need to download Android Studio 2.2 Preview 3 to try it out. 

To get started using ConstraintLayout , you can add the following to your build.gradle  dependencies (or Android Studio will automatically add the  ConstraintLayout dependency to your build.gradle when you create a new layout using it)
To use the new ConstraintLayout , click on res/layout  folder. Select New > Layout Resource Folder. In the root element option, remove LinearLayout and start typing ConstraintLayout. .  You will then create a new file with your ConstraintLayout , the default view includes the Blueprint modeBlueprint Mode and Design ModeDesign Mode  which will look something like this:
ConstraintLayout

How does this new layout builder work?

Constraints:

Constraints are rules that you define for a widget, much likeRelativeLayouts  “toLeftOf , toRightOf”, constraints offer similar options. They can also specify how widgets are aligned.

Definition

ConstraintLayout is a new type of layout introduced by Android, similar to RelativeLayout but more flexible, and it is used to position UI elements relative to other UI elements by using constraints.
constraint represent the rules we have to apply in order to position our UI elements relative to each other.

Overview

  • ConstraintLayout has backwards compatibility (it is available in Support Library compatible with Android 2.3 and higher)
  • When you create a new project, ConstraintLayout is used now in the template instead of RelativeLayout
  • ConstraintLayout can be used directly from xml, but it is recommended to use the new Layout Editor
  • Layout editor is available from Android Studio 2.2 Preview and was build especially for this new type of layout
  • constraints can be created:
    • manually
    • by using Autoconnect (before, the layout editor started with Autoconnect enabled, but from Android Studio 2.2 Preview 5, it is now disabled by default. Also, the icon will be visible only if you use ConstraintLayout).
    • by using  Inference
  • the difference between Autoconnect and Inference is that, Autoconnect creates constraints for the widget being currently moved (the current widget is constrained by other widgets, but other widgets won’t be constrained by the widget currently being moved) , whereas Inference creates constraints among all elements in a layout.
  • constraints can be defined for one or more sides of a view by connecting the view to:
    • an anchor point on another view
    • an edge of the layout
    • an invisible guideline

Rules for the Constraint System

  • anchors on different axis cannot be connected (such as top and left anchor)
  • baseline constraint can only be constrained to another baseline
  • constraints resulting in a cycle are not permitted
References


Wednesday, 20 April 2016

Difference between Service, Threads & AsyncTask

Hi All.


After long time, again I have to something for write and share.

You can find many documents, post, blogs and discussion on this topic but I think if we have all the stuff at one place it is better to understand.

So I will try to my best to put the all things which covers the all thing for this topic.

So far, we have a way for applications to implicitly do work in the background, as long as the process doesn't get killed by Android as part of its regular memory management. This is fine for things like loading web pages in the background, but what about features with harder requirements? Background music playback, data synchronization, location tracking, alarm clocks, etc.


Service:
  • Service is a Android component without UI.
  • A Service allows an application to implement longer-running background operations. The fundamental purpose is for an application to "continue running even while in the background, until it done."
  • While services do provide a rich client-server model, its use is optional. Upon starting an application's services, Android simply instantiates the component in the application's process to provide its context. How it is used after that is up to the application: it can put all of the needed code inside of the service itself without interacting with other parts of the application, make calls on other singleton objects shared with other parts of the app, directly retrieve the Service instance from elsewhere if needed, or run it in another process and do a full-blown RPC protocol if that is desired.
  • Because an unbounded number of services can ask to be running for an unknown amount of time. There may not be enough RAM to have all of the requesting services run, so as a result no strong guarantees are made about being able to keep them running.
  • If there is too little RAM, processes hosting services will be immediately killed like background processes are. However, if appropriate, Android will remember that these services wish to remain running, and restart their process at a later time when more RAM is available. For example, if the user goes to a web page that requires large amounts of RAM, Android may kill background service processes like sync until the browser's memory needs go down.
  • Services can further negotiate this behaviour by requesting they be considered "foreground." This places the service in a "please don't kill" state, but requires that it include a notification to the user about it actively running. This is useful for services such as background music playback or car navigation, which the user is actively aware of; when you're playing music and using the browser, you can always see the music-playing glyph in the status bar. Android won't try to kill these services, but as a trade-off, ensures the user knows about them and is able to explicitly stop them when desired.
  • Service never runs in a dedicated /thread/. By default it runs in the main application thread, and may optionally run in a separate /process.
  • If you need to have something to keep on running while the user goes from one of your activities to the other, then you may also need a service.
  • Thread must be "embedded" in the service, not the opposite. The service acts as an entry point, in which you can create. several threads if you like.
Note: 
  • In Android, even if the Service runs in the background, it runs on the Main Thread of the application. So, if at the same time if you have an activity displayed, the running service will take the main thread and the activity will seem slow. It is important to note that a Service is just a way of telling Android that something needs to run without a user interface in the background while the user may not interacting with your application. So, if you expect the user to be interacting with the application while the service is running and you have a long task to perform in a service, you need to create a worker thread in the Service to carry out the task.
  • Services are a way to tell Android that certain code in your application is important to the user, and Android should make an effort to keep it running even when it doesn't have active activities.
  • Your service will want to spawn its own thread or asynctask to do your heavy work or else you will get a forceclose.


Service
Thread
IntentService
AsyncTask
When to use ?
Task with no UI, but shouldn't be too long. Use threads within service for long tasks.
- Long task in general.

- For tasks in parallel use Multiple threads (traditional mechanisms)
- Long task usually with no communication to main thread.
(Update)- If communication is required, can use main thread handler or broadcast intents

- When callbacks are needed (Intent triggered tasks). 
- Small task having to communicate with main thread.

- For tasks in parallel use multiple instances OR Executor
 
Trigger
Call to method
onStartService()
Thread start() method
Intent
Call to method execute()
Triggered From (thread)
Any thread
Any Thread
Main Thread (Intent is received on main thread and then worker thread is spawed)
Main Thread
Runs On (thread)
Main Thread
Its own thread
Separate worker thread
Worker thread. However, Main thread methods may be invoked in between to publish progress.
Limitations /
Drawbacks
May block main thread
- Manual thread management

- Code may become difficult to read
- Cannot run tasks in parallel.

- Multiple intents are queued on the same worker thread.
- one instance can only be executed once (hence cannot run in a loop) 

- Must be created and executed from the Main thread

Friday, 27 March 2015



1. SQLite and Android

What is SQLite?

SQLite is an Open Source database. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. The database requires limited memory at runtime (approx. 250 KByte) which makes it a good candidate from being embedded into other runtimes.
SQLite supports the data types TEXT (similar to String in Java), INTEGER (similar to long in Java) and REAL(similar to double in Java). All other types must be converted into one of these fields before getting saved in the database. SQLite itself does not validate if the types written to the columns are actually of the defined type, e.g. you can write an integer into a string column and vice versa.

SQLite in Android

SQLite is embedded into every Android device. Using an SQLite database in Android does not require a setup procedure or administration of the database.
You only have to define the SQL statements for creating and updating the database. Afterwards the database is automatically managed for you by the Android platform.
Access to an SQLite database involves accessing the file system. This can be slow. Therefore it is recommended to perform database operations asynchronously.
If your application creates a database, this database is by default saved in the directoryDATA/data/APP_NAME/databases/FILENAME.
The parts of the above directory are constructed based on the following rules. DATA is the path which theEnvironment.getDataDirectory() method returns. APP_NAME is your application name. FILENAME is the name you specify in your application code for the database.


Creating and updating database with SQLiteOpenHelper

To create and upgrade a database in your Android application you create a subclass of the SQLiteOpenHelperclass. In the constructor of your subclass you call the super() method of SQLiteOpenHelper, specifying the database name and the current database version.
In this class you need to override the following methods to create and update your database.
  • onCreate() - is called by the framework, if the database is accessed but not yet created.
  • onUpgrade() - called, if the database version is increased in your application code. This method allows you to update an existing database schema or to drop the existing database and recreate it via theonCreate() method.
Both methods receive an SQLiteDatabase object as parameter which is the Java representation of the database.
The SQLiteOpenHelper class provides the getReadableDatabase() and getWriteableDatabase()methods to get access to an SQLiteDatabase object; either in read or write mode.
The database tables should use the identifier _id for the primary key of the table. Several Android functions rely on this standard.



SQLiteDatabase is the base class for working with a SQLite database in Android and provides methods to open, query, update and close the database.
More specifically SQLiteDatabase provides the insert()update() and delete() methods.
In addition it provides the execSQL() method, which allows to execute an SQL statement directly.
The object ContentValues allows to define key/values. The key represents the table column identifier and thevalue represents the content for the table record in this column. ContentValues can be used for inserts and updates of database entries.
Queries can be created via the rawQuery() and query() methods or via the SQLiteQueryBuilder class .
rawQuery() directly accepts an SQL select statement as input.
query() provides a structured interface for specifying the SQL query.
SQLiteQueryBuilder is a convenience class that helps to build SQL queries.



rawQuery() Example

The following gives an example of a rawQuery() call.

return database.query(DATABASE_TABLE, 
  new String[] { KEY_ROWID, KEY_CATEGORY, KEY_SUMMARY, KEY_DESCRIPTION }, 
  null, null, null, null, null);
 


Parameters of the query() method
ParameterComment
String dbNameThe table name to compile the query against.
String[] columnNamesA list of which table columns to return. Passing "null" will return all columns.
String whereClauseWhere-clause, i.e. filter for the selection of data, null will select all data.
String[] selectionArgsYou may include ?s in the "whereClause"". These placeholders will get replaced by the values from the selectionArgs array.
String[] groupByA filter declaring how to group rows, null will cause the rows to not be grouped.
String[] havingFilter for the groups, null means no filter.
String[] orderByTable columns which will be used to order the data, null means no ordering.

If a condition is not required you can pass null, e.g. for the group by clause.
The "whereClause" is specified without the word "where", for example a "where" statement might look like: "_id=19 and summary=?".
If you specify placeholder values in the where clause via ?, you pass them as the selectionArgs parameter to the query.


3.6. Cursor

A query returns a Cursor object. A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory.
To get the number of elements of the resulting query use the getCount() method.
To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. TheisAfterLast() method allows to check if the end of the query result has been reached.
Cursor provides typed get*() methods, e.g. getLong(columnIndex)getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing.
Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table.
Cursor needs to be closed with the close() method call.

Cursor is not a class but an interface. If your Cursor object is from a SQLite query, it is a SQLiteCursor. In that definition (\Android\android-sdk\source\android\database\sqlite\SQLiteCursor.java)close() is called in the finalize() function. This may be different in other cursor types, since the Cursor interface does not specify this behavior.

You can close the cursor once you have retrieved the values for that particular object inside your method.

 ListViews, ListActivities and SimpleCursorAdapter

ListViews are Views which allow to display a list of elements.
ListActivities are specialized activities which make the usage of ListViews easier.
To work with databases and ListViews you can use the SimpleCursorAdapter. TheSimpleCursorAdapter allows to set a layout for each row of the ListViews.
You also define an array which contains the column names and another array which contains the IDs of Viewswhich should be filled with the data.
The SimpleCursorAdapter class will map the columns to the Views based on the Cursor passed to it.
To obtain the Cursor you should use the Loader class.