Wednesday, November 4, 2015

Publishing Android

Publishing Android:

Android application publishing is a process that makes your Android applications available to users. Infect, publishing is the last phase of the Android application development process.
Publish

Android development life cycle

Once you developed and fully tested your Android Application, you can start selling or distributing free using Google Play (A famous Android marketplace). You can also release your applications by sending them directly to users or by letting users download them from your own website.
You can check a detailed publishing process at Android official website, but this tutorial will take you through simple steps to launch your application on Google Play. Here is a simplified check list which will help you in launching your Android application −
Step Activity
1 Regression Testing Before you publish your application, you need to make sure that its meeting the basic quality expectations for all Android apps, on all of the devices that you are targeting. So perform all the required testing on different devices including phone and tablets.
2 Application Rating When you will publish your application at Google Play, you will have to specify a content rating for your app, which informs Google Play users of its maturity level. Currently available ratings are (a) Everyone (b) Low maturity (c) Medium maturity (d) High maturity.
3 Targeted Regions Google Play lets you control what countries and territories where your application will be sold. Accordingly you must take care of setting up time zone, localization or any other specific requirement as per the targeted region.
4 Application Size Currently, the maximum size for an APK published on Google Play is 50 MB. If your app exceeds that size, or if you want to offer a secondary download, you can use APK Expansion Files, which Google Play will host for free on its server infrastructure and automatically handle the download to devices.
5 SDK and Screen Compatibility It is important to make sure that your app is designed to run properly on the Android platform versions and device screen sizes that you want to target.
6 Application Pricing Deciding whether you app will be free or paid is important because, on Google Play, free app's must remain free. If you want to sell your application then you will have to specify its price in different currencies.
7 Promotional Content It is a good marketing practice to supply a variety of high-quality graphic assets to showcase your app or brand. After you publish, these appear on your product details page, in store listings and search results, and elsewhere.
8 Build and Upload release-ready APK The release-ready APK is what you you will upload to the Developer Console and distribute to users. You can check complete detail on how to create a release-ready version of your app: Preparing for Release.
9 Finalize Application Detail Google Play gives you a variety of ways to promote your app and engage with users on your product details page, from colourful graphics, screen shots, and videos to localized descriptions, release details, and links to your other apps. So you can decorate your application page and provide as much as clear crisp detail you can provide.

Export Android Application Process

Android Application Process

Apk development process

Before exporting the apps, you must some of tools
  • Dx tools(Dalvik executable tools ): It going to convert .class file to .dex file. it has useful for memory optimization and reduce the boot-up speed time
  • AAPT(Android assistance packaging tool):it has useful to convert .Dex file to.Apk
  • APK(Android packaging kit): The final stage of deployment process is called as .apk.
You will need to export your application as an APK (Android Package) file before you upload it Google Play marketplace.
To export an application, just open that application project in Android studio and select Build → Generate Signed APK from your Android studio and follow the simple steps to export your application −
Generate Signed APK Next select, Generate Signed APK option as shown in the above screen shot and then click it so that you get following screen where you will choose Create new keystore to store your application.
Generate Signed APK Enter your key store path,key store password,key alias and key password to protect your application and click on Next button once again. It will display following screen to let you create an application:
Generate Signed APK Once you filled up all the information,like app destination,build type and flavours click finish button While creating an application it will show as below
Creating Application Finally, it will generate your Android Application as APK formate File which will be uploaded at Google Play marketplace.

Google Play Registration

The most important step is to register with Google Play using Google Play Marketplace. You can use your existing google ID if you have any otherwise you can create a new Google ID and then register with the marketplace. You will have following screen to accept terms and condition.
Android Market Place Terms and Conditions You can use Continue to payment button to proceed to make a payment of $25 as a registration fee and finally to complete your account detail.
Once you are a registered user at Google Play, you can upload release-ready APK for your application and finally you will complete application detail using application detail page as mentioned in step 9 of the above mentioned checklist.

Signing Your App Manually

You do not need Android Studio to sign your app. You can sign your app from the command line using standard tools from the Android SDK and the JDK. To sign an app in release mode from the command line −
  • Generate a private key using keytool
$ keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000
  • Compile your app in release mode to obtain an unsigned APK
  • Sign your app with your private key using jarsigner
$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1
-keystore my-release-key.keystore my_application.apk alias_name
  • Verify that your APK is signed. For example −
$ jarsigner -verify -verbose -certs my_application.apk
  • Align the final APK package using zipalign.
$ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk

Some of App markets

  • Google play

  • phoload

  • APTOiDE

  • Amazon AppStore

  • 1mobile

  • Insyde Market

  • Yandex store

  • F-Droid

  • Samsung Galaxy AppStore

 

Monday, November 2, 2015

Android - WebView

Android - WebView:

WebView is a view that display web pages inside your application. You can also specify HTML string and can show it inside your application using WebView. WebView makes turns your application to a web application.
In order to add WebView to your application, you have to add <WebView> element to your xml layout file. Its syntax is as follows −
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/webview"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
/>
In order to use it, you have to get a reference of this view in Java file. To get a reference, create an object of the class WebView. Its syntax is −
WebView browser = (WebView) findViewById(R.id.webview);
In order to load a web url into the WebView, you need to call a method loadUrl(String url) of the WebView class, specifying the required url. Its syntax is:
browser.loadUrl("http://www.tutorialspoint.com");
Apart from just loading url, you can have more control over your WebView by using the methods defined in WebView class. They are listed as follows −
Sr.NoMethod & Description
1canGoBack()This method specifies the WebView has a back history item.
2canGoForward()This method specifies the WebView has a forward history item.
3clearHistory()This method will clear the WebView forward and backward history.
4destroy()This method destroy the internal state of WebView.
5findAllAsync(String find)This method find all instances of string and highlight them.
6getProgress()This method gets the progress of the current page.
7getTitle()This method return the title of the current page.
8getUrl()This method return the url of the current page.
If you click on any link inside the webpage of the WebView , that page will not be loaded inside your WebView. In order to do that you need to extend your class from WebViewClient and override its method. Its syntax is −
private class MyBrowser extends WebViewClient {
   @Override
   public boolean shouldOverrideUrlLoading(WebView view, String url) {
      view.loadUrl(url);
      return true;
   }
}

Example

Here is an example demonstrating the use of WebView Layout. It creates a basic web application that will ask you to specify a url and will load this url website in the WebView.
To experiment with this example, you need to run this on an actual device on which internet is running.
StepsDescription
1You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add WebView code.
3Modify the res/layout/activity_main to add respective XML components
4Modify the AndroidManifest.xml to add the necessary permissions
5Run the application and choose a running android device and install the application on it and verify the results.
Following is the content of the modified main activity file src/MainActivity.java.
package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.webkit.WebView;
import android.webkit.WebViewClient;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class MainActivity extends Activity  {
   Button b1;
   EditText ed1;
   
   private WebView wv1;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      b1=(Button)findViewById(R.id.button);
      ed1=(EditText)findViewById(R.id.editText);
      
      wv1=(WebView)findViewById(R.id.webView);
      wv1.setWebViewClient(new MyBrowser());
      
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String url = ed1.getText().toString();
            
            wv1.getSettings().setLoadsImagesAutomatically(true);
            wv1.getSettings().setJavaScriptEnabled(true);
            wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            wv1.loadUrl(url);
         }
      });
   }
   
   private class MyBrowser extends WebViewClient {
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
         view.loadUrl(url);
         return true;
      }
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}
Following is the modified content of the xml res/layout/activity_main.xml.
<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" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
   
   <TextView android:text="WebView" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:hint="Enter Text"
      android:focusable="true"
      android:textColorHighlight="#ff7eff15"
      android:textColorHint="#ffff25e6"
      android:layout_marginTop="46dp"
      android:layout_below="@+id/imageView"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignRight="@+id/imageView"
      android:layout_alignEnd="@+id/imageView" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Enter"
      android:id="@+id/button"
      android:layout_alignTop="@+id/editText"
      android:layout_toRightOf="@+id/imageView"
      android:layout_toEndOf="@+id/imageView" />
      
   <WebView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/webView"
      android:layout_below="@+id/button"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:layout_alignParentBottom="true" />
      
</RelativeLayout>
Following is the content of the res/values/string.xml.
<resources>
   <string name="app_name">My Application</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <uses-permission android:name="android.permission.INTERNET" />
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      
      </activity>
      
   </application>
</manifest>

Let's try to run your WebView application. To run the app from Android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android studio will display as shown below
Now just specify a url on the url field and press the browse button that appears,to launch the website. But before that please make sure that you are connected to the internet. After pressing the button, the following screen would appear −
Android WebView Tutorial Note. By just changing the url in the url field, your WebView will open your desired website.
Android WebView Tutorial Above image shows webview of tutorialspoint.com

 

Friday, October 30, 2015

Android - Text To Speech

Android - Text To Speech:

Android allows you convert your text into voice. Not only you can convert it but it also allows you to speak text in variety of different languages.
Android provides TextToSpeech class for this purpose. In order to use this class, you need to instantiate an object of this class and also specify the initListnere. Its syntax is given below:
private EditText write;
ttobj=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
   @Override
   public void onInit(int status) {
   }
}
);
In this listener, you have to specify the properties for TextToSpeech object , such as its language ,pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given below −
ttobj.setLanguage(Locale.UK);
The method setLanguage takes an Locale object as parameter. The list of some of the locales available are given below −
Sr.NoLocale
1US
2CANADA_FRENCH
3GERMANY
4ITALY
5JAPAN
6CHINA
Once you have set the language, you can call speak method of the class to speak the text. Its syntax is given below −
ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
Apart from the speak method, there are some other methods available in the TextToSpeech class. They are listed below:
Sr.NoMethod & description
1addSpeech(String text, String filename)This method adds a mapping between a string of text and a sound file.
2getLanguage()This method returns a Locale instance describing the language.
3isSpeaking()This method checks whether the TextToSpeech engine is busy speaking.
4setPitch(float pitch)This method sets the speech pitch for the TextToSpeech engine.
5setSpeechRate(float speechRate)This method sets the speech rate.
6shutdown()This method releases the resources used by the TextToSpeech engine.
7stop()This method stop the speak.

Example

The below example demonstrates the use of TextToSpeech class. It crates a basic application that allows you to set write text and speak it.
To experiment with this example , you need to run this on an actual device.
StepsDescription
1You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add TextToSpeech code.
3Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
4Run the application and choose a running android device and install the application on it and verify the results.
Here is the content of src/MainActivity.java.
package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;

import android.speech.tts.TextToSpeech;
import android.util.Log;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.List;
import java.util.Locale;

import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.widget.Toast;

public class MainActivity extends Activity {
   TextToSpeech t1;
   EditText ed1;
   Button b1;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      ed1=(EditText)findViewById(R.id.editText);
      b1=(Button)findViewById(R.id.button);
      
      t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
         @Override
         public void onInit(int status) {
            if(status != TextToSpeech.ERROR) {
               t1.setLanguage(Locale.UK);
            }
         }
      });
      
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String toSpeak = ed1.getText().toString();
            Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show();
            t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
         }
      });
   }
   
   public void onPause(){
      if(t1 !=null){
         t1.stop();
         t1.shutdown();
      }
      super.onPause();
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}
Here is the content of activity_main.xml
<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" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:transitionGroup="true">
   
   <TextView android:text="Text to Speech" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:theme="@style/Base.TextAppearance.AppCompat" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:layout_below="@+id/imageView"
      android:layout_marginTop="46dp"
      android:hint="Enter Text"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:textColor="#ff7aff10"
      android:textColorHint="#ffff23d1" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Text to Speech"
      android:id="@+id/button"
      android:layout_below="@+id/editText"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="46dp" />

</RelativeLayout>
Here is the content of Strings.xml.
<resources>
   <string name="app_name">My Application</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
</resources>
Here is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
   
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
      
         <intent-filter>
            <action android:name="android.intent.action.MAIN" >
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, android studio will display following window to select an option where you want to run your Android application.
Anroid Text To Speech Tutorial Select your mobile device as an option and then check your mobile device which will display following screen.
Android Text To Speech  Tutorial Now just type some text in the field and click on the text to speech button below. A notification would appear and text will be spoken. It is shown in the image below −
Android Text To Speech  Tutorial Now type something else and repeat the step again with different locale. You will again hear sound. This is shown below −
Android Text To Speech  Tutorial

 

Tuesday, October 27, 2015

Android - SQLite Database

Android - SQLite Database:

SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c

Database - Package

The main package is android.database.sqlite that contains the classes to manage your own databases

Database - Creation

In order to create a database you just need to call this method openOrCreateDatabase with your database name and mode as a parameter. It returns an instance of SQLite database which you have to receive in your own object.Its syntax is given below
SQLiteDatabse mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);
Apart from this , there are other functions available in the database package , that does this job. They are listed below
Sr.NoMethod & Description
1openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler)This method only opens the existing database with the appropriate flag mode. The common flags mode could be OPEN_READWRITE OPEN_READONLY
2openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)It is similar to the above method as it also opens the existing database but it does not define any handler to handle the errors of databases
3openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)It not only opens but create the database if it not exists. This method is equivalent to openDatabase method
4openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)This method is similar to above method but it takes the File object as a path rather then a string. It is equivalent to file.getPath()

Database - Insertion

we can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the same job but take some additional parameter is given below
Sr.NoMethod & Description
1execSQL(String sql, Object[] bindArgs)This method not only insert data , but also used to update or modify already existing data in database using bind arguments

Database - Fetching

We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(1);
String password = resultSet.getString(2);
There are other functions available in the Cursor class that allows us to effectively retrieve the data. That includes
Sr.NoMethod & Description
1getColumnCount()This method return the total number of columns of the table.
2getColumnIndex(String columnName)This method returns the index number of a column by specifying the name of the column
3getColumnName(int columnIndex)This method returns the name of the column by specifying the index of the column
4getColumnNames()This method returns the array of all the column names of the table.
5getCount()This method returns the total number of rows in the cursor
6getPosition()This method returns the current position of the cursor in the table
7isClosed()This method returns true if the cursor is closed and return false otherwise

Database - Helper class

For managing all the operations related to the database , an helper class has been given and is called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its syntax is given below
public class DBHelper extends SQLiteOpenHelper {
   public DBHelper(){
      super(context,DATABASE_NAME,null,1);
   }
   public void onCreate(SQLiteDatabase db) {}
   public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}

Example

Here is an example demonstrating the use of SQLite Database. It creates a basic contacts applications that allows insertion , deletion and modification of contacts.
To experiment with this example , you need to run this on an actual device on which camera is supported.
s
StepsDescription
1You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to get references of all the XML components and populate the contacts on listView.
3Create new src/DBHelper.java that will manage the database work
4Create a new Activity as DisplayContact.java that will display the contact on the screen
5Modify the res/layout/activity_main to add respective XML components
6Modify the res/layout/activity_display_contact.xml to add respective XML components
7Modify the res/values/string.xml to add necessary string components
8Modify the res/menu/display_contact.xml to add necessary menu components
9Create a new menu as res/menu/mainmenu.xml to add the insert contact option
10Run the application and choose a running android device and install the application on it and verify the results.
Following is the content of the modified MainActivity.java.
package com.example.sairamkrishna.myapplication;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ActionBarActivity {
   public final static String EXTRA_MESSAGE = "MESSAGE";
   private ListView obj;
   DBHelper mydb;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      mydb = new DBHelper(this);
      ArrayList array_list = mydb.getAllCotacts();
      ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
      
      obj = (ListView)findViewById(R.id.listView1);
      obj.setAdapter(arrayAdapter);
      obj.setOnItemClickListener(new OnItemClickListener(){
         @Override
         public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
            // TODO Auto-generated method stub
            int id_To_Search = arg2 + 1;
            
            Bundle dataBundle = new Bundle();
            dataBundle.putInt("id", id_To_Search);
            
            Intent intent = new Intent(getApplicationContext(),DisplayContact.class);
            
            intent.putExtras(dataBundle);
            startActivity(intent);
         }
      });
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item){
      super.onOptionsItemSelected(item);
      
      switch(item.getItemId())
      {
         case R.id.item1:Bundle dataBundle = new Bundle();
         dataBundle.putInt("id", 0);
         
         Intent intent = new Intent(getApplicationContext(),DisplayContact.class);
         intent.putExtras(dataBundle);
         
         startActivity(intent);
         return true;
         default:
         return super.onOptionsItemSelected(item);
      }
   }
   
   public boolean onKeyDown(int keycode, KeyEvent event) {
      if (keycode == KeyEvent.KEYCODE_BACK) {
         moveTaskToBack(true);
      }
      return super.onKeyDown(keycode, event);
   }
}
Following is the modified content of display contact activity DisplayContact.java
package com.example.addressbook;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DisplayContact extends Activity {
   int from_Where_I_Am_Coming = 0;
   private DBHelper mydb ;
   
   TextView name ;
   TextView phone;
   TextView email;
   TextView street;
   TextView place;
   int id_To_Update = 0;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_display_contact);
      name = (TextView) findViewById(R.id.editTextName);
      phone = (TextView) findViewById(R.id.editTextPhone);
      email = (TextView) findViewById(R.id.editTextStreet);
      street = (TextView) findViewById(R.id.editTextEmail);
      place = (TextView) findViewById(R.id.editTextCity);

      mydb = new DBHelper(this);

      Bundle extras = getIntent().getExtras(); 
      if(extras !=null)
      {
         int Value = extras.getInt("id");
         
         if(Value>0){
            //means this is the view part not the add contact part.
            Cursor rs = mydb.getData(Value);
            id_To_Update = Value;
            rs.moveToFirst();
            
            String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
            String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
            String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
            String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
            String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));
            
            if (!rs.isClosed()) 
            {
               rs.close();
            }
            Button b = (Button)findViewById(R.id.button1);
            b.setVisibility(View.INVISIBLE);

            name.setText((CharSequence)nam);
            name.setFocusable(false);
            name.setClickable(false);

            phone.setText((CharSequence)phon);
            phone.setFocusable(false); 
            phone.setClickable(false);

            email.setText((CharSequence)emai);
            email.setFocusable(false);
            email.setClickable(false);

            street.setText((CharSequence)stree);
            street.setFocusable(false); 
            street.setClickable(false);

            place.setText((CharSequence)plac);
            place.setFocusable(false);
            place.setClickable(false);
         }
      }
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      Bundle extras = getIntent().getExtras(); 
      
      if(extras !=null)
      {
         int Value = extras.getInt("id");
         if(Value>0){
            getMenuInflater().inflate(R.menu.display_contact, menu);
         }
         
         else{
            getMenuInflater().inflate(R.menu.main, menu);
         }
      }
      return true;
   }

   public boolean onOptionsItemSelected(MenuItem item) 
   { 
      super.onOptionsItemSelected(item); 
      switch(item.getItemId()) 
   { 
      case R.id.Edit_Contact: 
      Button b = (Button)findViewById(R.id.button1);
      b.setVisibility(View.VISIBLE);
      name.setEnabled(true);
      name.setFocusableInTouchMode(true);
      name.setClickable(true);

      phone.setEnabled(true);
      phone.setFocusableInTouchMode(true);
      phone.setClickable(true);

      email.setEnabled(true);
      email.setFocusableInTouchMode(true);
      email.setClickable(true);

      street.setEnabled(true);
      street.setFocusableInTouchMode(true);
      street.setClickable(true);

      place.setEnabled(true);
      place.setFocusableInTouchMode(true);
      place.setClickable(true);

      return true; 
      case R.id.Delete_Contact:

      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setMessage(R.string.deleteContact)
      .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            mydb.deleteContact(id_To_Update);
            Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();  
            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intent);
         }
      })
      .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            // User cancelled the dialog
         }
      });
      AlertDialog d = builder.create();
      d.setTitle("Are you sure");
      d.show();

      return true;
      default: 
      return super.onOptionsItemSelected(item); 

      } 
   } 

   public void run(View view)
   { 
      Bundle extras = getIntent().getExtras();
      if(extras !=null)
      {
         int Value = extras.getInt("id");
         if(Value>0){
            if(mydb.updateContact(id_To_Update,name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){
               Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show(); 
               Intent intent = new Intent(getApplicationContext(),MainActivity.class);
               startActivity(intent);
            }  
            else{
               Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show(); 
            }
         }
         else{
            if(mydb.insertContact(name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){
               Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show(); 
            }  
            
            else{
               Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show(); 
            }
            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intent);
         }
      }
   }
}
Following is the content of Database class DBHelper.java
package com.example.addressbook;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;

public class DBHelper extends SQLiteOpenHelper {

   public static final String DATABASE_NAME = "MyDBName.db";
   public static final String CONTACTS_TABLE_NAME = "contacts";
   public static final String CONTACTS_COLUMN_ID = "id";
   public static final String CONTACTS_COLUMN_NAME = "name";
   public static final String CONTACTS_COLUMN_EMAIL = "email";
   public static final String CONTACTS_COLUMN_STREET = "street";
   public static final String CONTACTS_COLUMN_CITY = "place";
   public static final String CONTACTS_COLUMN_PHONE = "phone";
   private HashMap hp;

   public DBHelper(Context context)
   {
      super(context, DATABASE_NAME , null, 1);
   }

   @Override
   public void onCreate(SQLiteDatabase db) {
      // TODO Auto-generated method stub
      db.execSQL(
      "create table contacts " +
      "(id integer primary key, name text,phone text,email text, street text,place text)"
      );
   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      // TODO Auto-generated method stub
      db.execSQL("DROP TABLE IF EXISTS contacts");
      onCreate(db);
   }

   public boolean insertContact  (String name, String phone, String email, String street,String place)
   {
      SQLiteDatabase db = this.getWritableDatabase();
      ContentValues contentValues = new ContentValues();
      contentValues.put("name", name);
      contentValues.put("phone", phone);
      contentValues.put("email", email); 
      contentValues.put("street", street);
      contentValues.put("place", place);
      db.insert("contacts", null, contentValues);
      return true;
   }
   
   public Cursor getData(int id){
      SQLiteDatabase db = this.getReadableDatabase();
      Cursor res =  db.rawQuery( "select * from contacts where id="+id+"", null );
      return res;
   }
   
   public int numberOfRows(){
      SQLiteDatabase db = this.getReadableDatabase();
      int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
      return numRows;
   }
   
   public boolean updateContact (Integer id, String name, String phone, String email, String street,String place)
   {
      SQLiteDatabase db = this.getWritableDatabase();
      ContentValues contentValues = new ContentValues();
      contentValues.put("name", name);
      contentValues.put("phone", phone);
      contentValues.put("email", email);
      contentValues.put("street", street);
      contentValues.put("place", place);
      db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
      return true;
   }

   public Integer deleteContact (Integer id)
   {
      SQLiteDatabase db = this.getWritableDatabase();
      return db.delete("contacts", 
      "id = ? ", 
      new String[] { Integer.toString(id) });
   }
   
   public ArrayList<String> getAllCotacts()
   {
      ArrayList<String> array_list = new ArrayList<String>();
      
      //hp = new HashMap();
      SQLiteDatabase db = this.getReadableDatabase();
      Cursor res =  db.rawQuery( "select * from contacts", null );
      res.moveToFirst();
      
      while(res.isAfterLast() == false){
         array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
         res.moveToNext();
      }
   return array_list;
   }
}
Following is the content of the res/layout/activity_main.xml
<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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="30dp"
        android:text="Data Base" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tutorials Point"
        android:id="@+id/textView2"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:textSize="35dp"
        android:textColor="#ff16ff01" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true"
        android:src="@drawable/logo"/>

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/scrollView"
        android:layout_below="@+id/imageView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true">
        
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >
    </ListView>
    </ScrollView>

</RelativeLayout>;
Following is the content of the res/layout/activity_display_contact.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
      android:id="@+id/scrollView1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      tools:context=".DisplayContact" >

<RelativeLayout
   android:layout_width="match_parent"
   android:layout_height="370dp"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin">

   <EditText
      android:id="@+id/editTextName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_marginTop="5dp"
      android:layout_marginLeft="82dp"
      android:ems="10"
      android:inputType="text" >
   </EditText>

   <EditText
      android:id="@+id/editTextEmail"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editTextStreet"
      android:layout_below="@+id/editTextStreet"
      android:layout_marginTop="22dp"
      android:ems="10"
      android:inputType="textEmailAddress" />

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBottom="@+id/editTextName"
      android:layout_alignParentLeft="true"
      android:text="@string/name"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editTextCity"
      android:layout_alignParentBottom="true"
      android:layout_marginBottom="28dp"
      android:onClick="run"
      android:text="@string/save" />

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBottom="@+id/editTextEmail"
      android:layout_alignLeft="@+id/textView1"
      android:text="@string/email"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <TextView
      android:id="@+id/textView5"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBottom="@+id/editTextPhone"
      android:layout_alignLeft="@+id/textView1"
      android:text="@string/phone"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <TextView
      android:id="@+id/textView4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_above="@+id/editTextEmail"
      android:layout_alignLeft="@+id/textView5"
      android:text="@string/street"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <EditText
      android:id="@+id/editTextCity"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignRight="@+id/editTextName"
      android:layout_below="@+id/editTextEmail"
      android:layout_marginTop="30dp"
      android:ems="10"
      android:inputType="text" />

   <TextView
      android:id="@+id/textView3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/editTextCity"
      android:layout_alignBottom="@+id/editTextCity"
      android:layout_alignParentLeft="true"
      android:layout_toLeftOf="@+id/editTextEmail"
      android:text="@string/country"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <EditText
      android:id="@+id/editTextStreet"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editTextName"
      android:layout_below="@+id/editTextPhone"
      android:ems="10"
      android:inputType="text" >

      <requestFocus />
   </EditText>

   <EditText
      android:id="@+id/editTextPhone"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editTextStreet"
      android:layout_below="@+id/editTextName"
      android:ems="10"
      android:inputType="phone|text" />

</RelativeLayout>
</ScrollView>
Following is the content of the res/value/string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">Address Book</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="Add_New">Add New</string>
   <string name="edit">Edit Contact</string>
   <string name="delete">Delete Contact</string>
   <string name="title_activity_display_contact">DisplayContact</string>
   <string name="name">Name</string>
   <string name="phone">Phone</string>
   <string name="email">Email</string>
   <string name="street">Street</string>
   <string name="country">City/State/Zip</string>
   <string name="save">Save Contact</string>
   <string name="deleteContact">Are you sure, you want to delete it.</string>
   <string name="yes">Yes</string>
   <string name="no">No</string>
</resources>
Following is the content of the res/menu/main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
   
   <item android:id="@+id/item1" 
      android:icon="@drawable/add"
      android:title="@string/Add_New" >
   </item>
   
</menu>
Following is the content of the res/menu/display_contact.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
   <item
      android:id="@+id/Edit_Contact"
      android:orderInCategory="100"
      android:title="@string/edit"/>
   
   <item
      android:id="@+id/Delete_Contact"
      android:orderInCategory="100"
      android:title="@string/delete"/>

</menu>
This is the defualt AndroidManifest.xml of this project
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      
      </activity>
      
      <activity android:name=".DisplayContact"/>
      
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio , open one of your project's activity files and click Run Eclipse Run Icon icon from the tool bar. Before starting your application,Android studio will display following window to select an option where you want to run your Android application.
Anroid Camera Tutorial Select your mobile device as an option and then check your mobile device which will display following screen −
Anroid SQLite Tutorial Now open your optional menu, it will show as below image: Optional menu appears different places on different versions
Anroid SQLite Tutorial Click on the add button of the menu screen to add a new contact. It will display the following screen −
Anroid SQLite Tutorial It will display the following fields. Please enter the required information and click on save contact. It will bring you back to main screen.
Android SQLite Tutorial Now our contact john has been added. Tap on this to edit it or delete it.It will bring you to the following screen. Now select menu from your mobile. And there will be two options there.
Android SQLite Tutorial Select delete contact and an dialog box would appear asking you about deleting this contact. It would be like this
Android SQLite Tutorial Select Yes from the above screen that appears and a notification will appear that the contact has been deleted successfully. It would appear like this
Anroid SQLite Tutorial In order to see that where is your database is created. Open your android studio, connect your mobile. Go tools/android/android device monitor. Now browse the file explorer tab. Now browse this folder /data/data/<your.package.name>/databases<database-name>.