- ** attributes in android applications.
Attribute Description android: id It is used to uniquely identify an element in the application. android:icon It is used to set the item's icon from drawable folder. android: title It is used to set the item's title android:showAsAction It is used to specify how the item should appear as an action item in the app bar. In case if we want to add submenu in menu item, then we need to add a element as the child of an . Following is the example of defining a submenu in menu item.
Load Android Menu from an Activity
Once we are done with creation of menu, we need to load the menu resource from our activity using MenuInflater.inflate() like as shown below. @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_example, menu); }
Handle Android Menu Click Events
In android, we can handle a menu item click events using ItemSelected() event based on the menu type. Following is the example of handling a context menu item click event using onContextItemSelected(). @Override public boolean onContextItemSelected(MenuItem item) {
Data It specifies a type of data to an intent filter. When we create an intent, itās important to specify the type of data (MIME type). Category Generally, the android category is optional for intents and it specifies the additional information about the type of component that should handle an intent.
Android Intent Types
There are two types of intents available in android, those are Implicit Intents and Explicit Intents.
Implicit Intents: In android, Implicit Intents wonāt specify any name of the component to start instead, it
declare an action to perform and it allows a component from other apps to handle it. For example, by using implicit intents we can request another app to show the location details of the user or etc. Following is the simple code snippet of implicit intent in the android application. Intent intent=new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.abcd.com")); startActivity(intent); Example : When we enter the website URL and click on the button it will open a website in a new browser window in the same application. More details: https://www.tutlane.com/tutorial/android/android-implicit- intents-with-examples
Explicit Intents
In android, Explicit intents explicitly specify the name of the component to be invoked by activity and we use explicit intents to start a component in our own app. For example, we can start a new activity in response to a user action using explicit intents. By using explicit intents we can send or share data/content from one activity to another activity based on our requirements. To create an Explicit Intent , we need to define the component name for an Intent object. Intent di = new Intent(this, ActivityView.class); di.setData(Uri.parse("http://www.tutlane.com")); startService(di);
Example: public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText firstNum = (EditText)findViewById(R.id.firstNum); final EditText secNum = (EditText)findViewById(R.id.secondNum); Button btnAdd = (Button)findViewById(R.id.addBtn); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int num1 = Integer.parseInt(firstNum.getText().toString()); int num2 = Integer.parseInt(secNum.getText().toString()); Intent intent = new Intent(MainActivity.this,ResultActivity.class); intent.putExtra("SUM",num1+" + "+num2+" = "+(num1+num2)); startActivity(intent); } }); } } public class ResultActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.result); TextView result = (TextView)findViewById(R.id.resultView); Intent intent = getIntent(); String addition = (String)intent.getSerializableExtra("SUM"); result.setText(addition);
Content Providers
A content provider manages access to a central repository of data. A provider is part of an Android application, which often provides its own UI for working with the data. However, content providers are primarily intended to be used by other applications, which access the provider using a ā provider client objectā. Together, providers and provider clients offer a consistent, standard interface to data that also handles inter-process communication and secure data access.
Generally, in android to send a request from UI to ContentResolver we have another object called CursorLoader which is used to run the query asynchronously in background. In android application, the UI components such as Activity or Fragment will call a CursorLoader to query and get a required data from ContentProvider using ContentResolver. The ContentProvider object will receive data requests from the client, performs the requested actions (create, update, delete, retrieve) and return the result. Following is the pictorial representation of requesting an operation from UI using Activity or Fragment to get the data from ContentProvider object. Content URIs In android, Content URI is a URI that is used to query a content provider to get the required data. The Content URIs will contain the name of an entire-provider (authority) and the name that points to a table (path). Generally the format of URI in android applications will be like as shown below content://authority/path Following are the details about various parts of an URI in android application. content:// - The string content:// is always present in the URI and it is used to represent the given URI is a content URI. authority - It represents the name of content provider, for example phone, contacts, etc. and we need to use a fully qualified name for third party content providers like com.tutlane.contactprovider path - It represents the tableās path. The ContentResolver object use the URIās authority to find the appropriate provider and send the query objects to the correct provider. After that ContentProvider uses the path of content URI to choose the right table to access. Following is the example of a simple example of URI in android applications. content://contacts_info/users
Here the string content:// is used to represent URI is a content URI, contacts_info string is the name of the providerās authority and users string is the tableās path. Creating a Content Provider To create a content provider in android applications we should follow below steps. ļ· We need to create a content provider class that extends the ContentProvider base class. ļ· We need to define our content provider URI to access the content. ļ· The ContentProvider class defines a six abstract methods (insert(), update(), delete(), query(), getType()) which we need to implement all these methods as a part of our subclass. ļ· We need to register our content provider in AndroidManifest.xml using tag. Following are the list of methods which need to implement as a part of ContentProvider class. ļ· query() - It receives a request from the client. By using arguments it will get a data from the requested table and return the data as a Cursor object. ļ· insert() - This method will insert a new row into our content provider and it will return the content URI for newly inserted row. ļ· update() - This method will update existing rows in our content provider and it returns the number of rows updated. ļ· delete() - This method will delete the rows in our content provider and it returns the number of rows deleted. ļ· getType() - This method will return the MIME type of data to given content URI. ļ· onCreate() - This method will initialize our provider. The android system will call this method immediately after it creates our provider.
SQLite Database in Android
SQLite is another data storage available in Android where we can store data in the userās device and can use it any time when required. SQLite is a opensource SQL database that stores data to a text file on a device. SQLite supports all the relational database features
The SQLiteOpenHelper is responsible for opening database if exist, creating database if it does not exists and upgrading if required. The SQLiteOpenHelper only require the DATABASE_NAME to create database. After extending SQLiteOpenHelper you will need to implement its methods onCreate, onUpgrade and constructor. onCreate(SQLiteDatabase sqLiteDatabase) method is called only once throughout the application lifecycle. It will be called whenever there is a first call to getReadableDatabase() or getWritableDatabase() function available in super SQLiteOpenHelper class. So SQLiteOpenHelper class call the onCreate() method after creating database and instantiate SQLiteDatabase object. Database name is passed in constructor call. Create: Creating a database is very simple in android by using SQLiteOpenHelper class. Whenever we need to create a database we have to extend SQLiteOpenHelper class as follows: /*A helper class to perform database related queries/ public class SqliteManager extends SQLiteOpenHelper { public static final String DATABASE_NAME = "abhiandroid.db"; public static final int version = 1 ; public SqliteManager(Context context) { super(context, DATABASE_NAME, null, version); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String dbQuery = "CREATE TABLE Items (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT, description TEXT)"; sqLiteDatabase.execSQL(dbQuery); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { } } Insert, Read, Delete & Update Operation In Sqlite: To perform insert, read, delete, update operation there are two different ways: ļ· Write parameterized queries (Recommended) ļ· Write raw queries Parameterized Queries : These are those queries which are performed using inbuilt functions to insert, read, delete or update data. These operations related functions are provided in SQLiteDatabase class.
Raw Queries : These are simple sql queries similar to other databases like MySql, Sql Server etc, In this case user will have to write query as text and passed the query string in rawQuery(String sql,String [] selectionArgs) or execSQL(String sql,Object [] bindArgs) method to perform operations. Insert: To perform insert operation using parameterized query we have to call insert function available in SQLiteDatabase class. insert() function has three parameters like public long insert(String tableName,String nullColumnHack,ContentValues values) where tableName is name of table in which data to be inserted. public long insert(String tableName,String nullColumnHack,ContentValues values) NullColumnHack may be passed null, it require table column value in case we donāt put column name in ContentValues object so a null value must be inserted for that particular column, values are those values that needs to be inserted- ContentValues is a key-pair based object which accepts all primitive type. Update : Update function is quite similar to insert but it requires two additional parameters, it doesnāt required nullColumnHack. It has total four parameters two are similar to insert function that is tableName and contentValues. Another two are whereClause(String) and whereArgs(String[]). Update function is available in SQLiteDatabase class it looks as follows: public int update(String tableName,ContentValues contentValues,String whereClause,String[] whereAr gs) Here whereClause is tell the database where to update data in table, itās recommended to pass ?s (questions) along with column name in whereClause String. Similarly whereArgs array will contain values for those columns whose against ?s has been put in whereClause. Update function will return number of rows affected if success, 0 otherwise. Delete: Similar to insert and update, delete function is available in SQLiteDatabase class, So delete is very similar to update function apart from ContentValues object as itās not required in delete. public int delete(String tableName,String whereClause,String [] whereArgs) function has three parameters these are totally similar to update functionās parameters and are used in same way as in update function. db.delete( "Items" , whereClause, whereArgs); Read(select): Reading from a database table is bit different from other functions like insert,update and delete. SQLiteDatabase class provides query() method to read data from table. query() method is overloaded with different set of parameters. It returns Cursor object so Cursor is a result-set with queried data, it provides different functions really helpful while reading data. Following are some overloaded query functions: ļ· public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Sr. No. Key DDL DML 1 Stands for DDL stands for Data Definition Language. DML stands for Data Manipulation Language. 2 Usage DDL statements are used to create database, schema, constraints, users, tables etc. DML statement is used to insert, update or delete the records. 3 Classification DDL has no further classification. DML is further classified into procedural DML and non- procedural DML. 4 Commands CREATE, DROP, RENAME and ALTER. INSERT, UPDATE and DELETE.
Cursors
Cursors are what contain the result set of a query made against a database in Android. The Cursor class has an API that allows an app to read (in a type-safe manner) the columns that were returned from the query as well as iterate over the rows of the result set. Reading Cursor Data Once a cursor has been returned from a database query, an app needs to iterate over the result set and read the column data from the cursor. Internally, the cursor stores the rows of data returned by the query along with a position that points to the current row of data in the result set. When a cursor is returned from a query() method, its position points to the spot before the first row of data. This means that before any rows of data can be read from the cursor, the position must be moved to point to a valid row of data. The Cursor class provides the following methods to manipulate its internal position: ļ· boolean Cursor.move(int offset): Moves the position by the given offset ļ· boolean Cursor.moveToFirst(): Moves the position to the first row ļ· boolean Cursor.moveToLast(): Moves the position to the last row ļ· boolean Cursor.moveToNext(): Moves the cursor to the next row relative to the current position ļ· boolean Cursor.moveToPosition(int position): Moves the cursor to the specified position ļ· Cursor.moveToPrevious(): Moves the cursor to the previous row relative to the current position Each move() method returns a boolean to indicate whether the operation was successful or not. This flag is useful for iterating over the rows in a cursor.
Managing the Cursor The internals of a cursor can contain a lot of resources such as all the data returned from the query along with a connection to the database. Because of this, it is important to handle a cursor appropriately and tell it to clean up when it is no longer in use to prevent memory leaks. To perform the cleanup, the Cursor class contains the Cursor.close() method, which needs to be called when an activity or fragment no longer needs the cursor. In versions of Android before 3.0, cursor maintenance was left to developers. They either had to handle the closing of the cursor themselves or had to make sure they informed an activity that it was using a cursor so the activity would close the cursor at an appropriate time. Android 3.0 introduced the loader framework that takes care of managing cursors for activities/fragments. To support older versions of Android, the loader framework has also been backported and added to the support library. When using the loader framework, apps no longer need to worry about calling Cursor.close() or informing an activity/fragment of a cursor that it needs to manage.
Reading Contacts
You can read phone contacts using Content Provider. With the help of this content provider we can communicate with the contacts app and query the URIs and columns to get contact information and it will return as contact name, all contact numbers, all email addresses, company name, etc.