Translate

Thursday, 31 March 2016

Example of android SQLite database

Let's see the simple example of android sqlite database.
File: Contact.java
  1. package com.example.sqlite;  
  2. public class Contact {  
  3.    int _id;  
  4.     String _name;  
  5.     String _phone_number;  
  6.      public Contact(){   }  
  7.     public Contact(int id, String name, String _phone_number){  
  8.         this._id = id;  
  9.         this._name = name;  
  10.         this._phone_number = _phone_number;  
  11.     }  
  12.    
  13.     public Contact(String name, String _phone_number){  
  14.         this._name = name;  
  15.         this._phone_number = _phone_number;  
  16.     }  
  17.     public int getID(){  
  18.         return this._id;  
  19.     }  
  20.   
  21.     public void setID(int id){  
  22.         this._id = id;  
  23.     }  
  24.   
  25.     public String getName(){  
  26.         return this._name;  
  27.     }  
  28.   
  29.     public void setName(String name){  
  30.         this._name = name;  
  31.     }  
  32.   
  33.     public String getPhoneNumber(){  
  34.         return this._phone_number;  
  35.     }  
  36.    
  37.     public void setPhoneNumber(String phone_number){  
  38.         this._phone_number = phone_number;  
  39.     }  
  40. }  
File: DatabaseHandler.java
Now, let's create the database handler class that extends SQLiteOpenHelper class and provides the implementation of its methods.
  1. package com.example.sqlite;  
  2. import java.util.ArrayList;  
  3. import java.util.List;  
  4.    
  5. import android.content.ContentValues;  
  6. import android.content.Context;  
  7. import android.database.Cursor;  
  8. import android.database.sqlite.SQLiteDatabase;  
  9. import android.database.sqlite.SQLiteOpenHelper;  
  10.    
  11. public class DatabaseHandler extends SQLiteOpenHelper {  
  12.    private static final int DATABASE_VERSION = 1;  
  13.    private static final String DATABASE_NAME = "contactsManager";  
  14.     private static final String TABLE_CONTACTS = "contacts";  
  15.      private static final String KEY_ID = "id";  
  16.     private static final String KEY_NAME = "name";  
  17.     private static final String KEY_PH_NO = "phone_number";  
  18.    
  19.     public DatabaseHandler(Context context) {  
  20.         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  21.         //3rd argument to be passed is CursorFactory instance  
  22.     }  
  23.    
  24.     // Creating Tables  
  25.     @Override  
  26.     public void onCreate(SQLiteDatabase db) {  
  27.         String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("  
  28.                 + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"  
  29.                 + KEY_PH_NO + " TEXT" + ")";  
  30.         db.execSQL(CREATE_CONTACTS_TABLE);  
  31.     }  
  32.    
  33.     // Upgrading database  
  34.     @Override  
  35.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  36.         // Drop older table if existed  
  37.         db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);  
  38.    
  39.         // Create tables again  
  40.         onCreate(db);  
  41.     }  
  42.    
  43.      // code to add the new contact  
  44.      void addContact(Contact contact) {  
  45.         SQLiteDatabase db = this.getWritableDatabase();  
  46.    
  47.         ContentValues values = new ContentValues();  
  48.         values.put(KEY_NAME, contact.getName()); // Contact Name  
  49.         values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone  
  50.    
  51.         // Inserting Row  
  52.         db.insert(TABLE_CONTACTS, null, values);  
  53.         //2nd argument is String containing nullColumnHack  
  54.         db.close(); // Closing database connection  
  55.     }  
  56.    
  57.     // code to get the single contact  
  58.     Contact getContact(int id) {  
  59.         SQLiteDatabase db = this.getReadableDatabase();  
  60.    
  61.         Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,  
  62.                 KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",  
  63.                 new String[] { String.valueOf(id) }, nullnullnullnull);  
  64.         if (cursor != null)  
  65.             cursor.moveToFirst();  
  66.    
  67.         Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),  
  68.                 cursor.getString(1), cursor.getString(2));  
  69.         // return contact  
  70.         return contact;  
  71.     }  
  72.    
  73.     // code to get all contacts in a list view  
  74.     public List<Contact> getAllContacts() {  
  75.         List<Contact> contactList = new ArrayList<Contact>();  
  76.         // Select All Query  
  77.         String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;  
  78.    
  79.         SQLiteDatabase db = this.getWritableDatabase();  
  80.         Cursor cursor = db.rawQuery(selectQuery, null);  
  81.    
  82.         // looping through all rows and adding to list  
  83.         if (cursor.moveToFirst()) {  
  84.             do {  
  85.                 Contact contact = new Contact();  
  86.                 contact.setID(Integer.parseInt(cursor.getString(0)));  
  87.                 contact.setName(cursor.getString(1));  
  88.                 contact.setPhoneNumber(cursor.getString(2));  
  89.                 // Adding contact to list  
  90.                 contactList.add(contact);  
  91.             } while (cursor.moveToNext());  
  92.         }  
  93.    
  94.         // return contact list  
  95.         return contactList;  
  96.     }  
  97.    
  98.     // code to update the single contact  
  99.     public int updateContact(Contact contact) {  
  100.         SQLiteDatabase db = this.getWritableDatabase();  
  101.    
  102.         ContentValues values = new ContentValues();  
  103.         values.put(KEY_NAME, contact.getName());  
  104.         values.put(KEY_PH_NO, contact.getPhoneNumber());  
  105.    
  106.         // updating row  
  107.         return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",  
  108.                 new String[] { String.valueOf(contact.getID()) });  
  109.     }  
  110.    
  111.     // Deleting single contact  
  112.     public void deleteContact(Contact contact) {  
  113.         SQLiteDatabase db = this.getWritableDatabase();  
  114.         db.delete(TABLE_CONTACTS, KEY_ID + " = ?",  
  115.                 new String[] { String.valueOf(contact.getID()) });  
  116.         db.close();  
  117.     }  
  118.    
  119.     // Getting contacts Count  
  120.     public int getContactsCount() {  
  121.         String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;  
  122.         SQLiteDatabase db = this.getReadableDatabase();  
  123.         Cursor cursor = db.rawQuery(countQuery, null);  
  124.         cursor.close();  
  125.    
  126.         // return count  
  127.         return cursor.getCount();  
  128.     }  
  129.    
  130. }  
File: MainActivity.java
  1. package com.example.sqlite;  
  2.   
  3. import java.util.List;  
  4.   
  5. import android.os.Bundle;  
  6. import android.app.Activity;  
  7. import android.util.Log;  
  8. import android.view.Menu;  
  9.   
  10. public class MainActivity extends Activity {  
  11.   
  12.     @Override  
  13.     protected void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.activity_main);  
  16.           
  17.         DatabaseHandler db = new DatabaseHandler(this);  
  18.            
  19.          // Inserting Contacts  
  20.         Log.d("Insert: ""Inserting ..");  
  21.         db.addContact(new Contact("Ravi""9100000000"));  
  22.         db.addContact(new Contact("Srinivas""9199999999"));  
  23.         db.addContact(new Contact("Tommy""9522222222"));  
  24.         db.addContact(new Contact("Karthik""9533333333"));  
  25.    
  26.         // Reading all contacts  
  27.         Log.d("Reading: ""Reading all contacts..");  
  28.         List<Contact> contacts = db.getAllContacts();         
  29.    
  30.         for (Contact cn : contacts) {  
  31.          String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +   
  32.             cn.getPhoneNumber();  
  33.         // Writing Contacts to log  
  34.         Log.d("Name: ", log);  
  35.     }  
  36.     }  
  37.   
  38.     @Override  
  39.     public boolean onCreateOptionsMenu(Menu menu) {  
  40.         // Inflate the menu; this adds items to the action bar if it is present.  
  41.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  42.         return true;  
  43.     }  
  44.   
  45. }  

Output:

Open Logcat and see the output. It is the basic example of android sqlite without any GUI.
For GUI application with android SQLite, visit next page.

Output:

android simple sqlite example output 1

Wednesday, 30 March 2016

Android SQLite Tutorial

SQLite is an open-source relational database i.e. used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database.
It is embedded in android bydefault. So, there is no need to perform any database setup or administration task.
Here, we are going to see the example of sqlite to store and fetch the data. Data is displayed in the logcat. For displaying data on the spinner or listview, move to the next page.
SQLiteOpenHelper class provides the functionality to use the SQLite database.

SQLiteOpenHelper class

The android.database.sqlite.SQLiteOpenHelper class is used for database creation and version management. For performing any database operation, you have to provide the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.

Constructors of SQLiteOpenHelper class

There are two constructors of SQLiteOpenHelper class.
ConstructorDescription
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) creates an object for creating, opening and managing the database.
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) creates an object for creating, opening and managing the database. It specifies the error handler.

Methods of SQLiteOpenHelper class

There are many methods in SQLiteOpenHelper class. Some of them are as follows:
MethodDescription
public abstract void onCreate(SQLiteDatabase db)called only once when database is created for the first time.
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)called when database needs to be upgraded.
public synchronized void close ()closes the database object.
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion)called when database needs to be downgraded.

SQLiteDatabase class

It contains methods to be performed on sqlite database such as create, update, delete, select etc.

Methods of SQLiteDatabase class

There are many methods in SQLiteDatabase class. Some of them are as follows:
MethodDescription
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String nullColumnHack, ContentValues values) inserts a record on the database. The table specifies the table name, nullColumnHack doesn't allow completely null values. If second argument is null, android will store null values if values are empty. The third argument specifies the values to be stored.
int update(String table, ContentValues values, String whereClause, String[] whereArgs)updates a row.
Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) returns a cursor over the resultset.

Tuesday, 29 March 2016

Android Sensor Tutorial

Sensors can be used to monitor the three-dimensional device movement or change in the environment of the device.
Android provides sensor api to work with different types of sensors.
android sensor

Types of Sensors

Android supports three types of sensors:

1) Motion Sensors

These are used to measure acceleration forces and rotational forces along with three axes.

2) Position Sensors

These are used to measure the physical position of device.

3) Environmental Sensors

These are used to measure the environmental changes such as temperature, humidity etc.

Android Sensor API

Android sensor api provides many classes and interface. The important classes and interfaces of sensor api are as follows:

1) SensorManager class

The android.hardware.SensorManager class provides methods :
  • to get sensor instance,
  • to access and list sensors,
  • to register and unregister sensor listeners etc.
You can get the instance of SensorManager by calling the method getSystemService() and passing the SENSOR_SERVICE constant in it.
  1. SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);  

2) Sensor class

The android.hardware.Sensor class provides methods to get information of the sensor such as sensor name, sensor type, sensor resolution, sensor type etc.

3) SensorEvent class

Its instance is created by the system. It provides information about the sensor.

4) SensorEventListener interface

It provides two call back methods to get information when sensor values (x,y and z) change or sensor accuracy changes.
Public and abstract methodsDescription
void onAccuracyChanged(Sensor sensor, int accuracy)it is called when sensor accuracy is changed.
void onSensorChanged(SensorEvent event)it is called when sensor values are changed.

Android simple sensor app example

Let's see the two sensor examples.
  1. A sensor example that prints x, y and z axis values. Here, we are going to see that.
  2. A sensor example that changes the background color when device is shuffled. Click for changing background color of activity sensor example

activity_main.xml

There is only one textview in this file.
File: activity_main.xml
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/textView1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentLeft="true"  
  12.         android:layout_alignParentTop="true"  
  13.         android:layout_marginLeft="92dp"  
  14.         android:layout_marginTop="114dp"  
  15.         android:text="TextView" />  
  16.   
  17. </RelativeLayout>  

Activity class

Let's write the code that prints values of x axis, y axis and z axis.
File: MainActivity.java
  1. package com.example.sensorsimple;  
  2. import android.app.Activity;  
  3. import android.os.Bundle;  
  4. import android.widget.TextView;  
  5. import android.widget.Toast;  
  6. import android.hardware.SensorManager;  
  7. import android.hardware.SensorEventListener;  
  8. import android.hardware.SensorEvent;  
  9. import android.hardware.Sensor;  
  10. import java.util.List;  
  11. public class MainActivity extends Activity {  
  12.     SensorManager sm = null;  
  13.     TextView textView1 = null;  
  14.     List list;  
  15.   
  16.     SensorEventListener sel = new SensorEventListener(){  
  17.         public void onAccuracyChanged(Sensor sensor, int accuracy) {}  
  18.         public void onSensorChanged(SensorEvent event) {  
  19.             float[] values = event.values;  
  20.             textView1.setText("x: "+values[0]+"\ny: "+values[1]+"\nz: "+values[2]);  
  21.         }  
  22.     };  
  23.   
  24.     @Override  
  25.     public void onCreate(Bundle savedInstanceState) {  
  26.         super.onCreate(savedInstanceState);  
  27.         setContentView(R.layout.activity_main);  
  28.   
  29.         /* Get a SensorManager instance */  
  30.         sm = (SensorManager)getSystemService(SENSOR_SERVICE);  
  31.   
  32.         textView1 = (TextView)findViewById(R.id.textView1);  
  33.   
  34.         list = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);  
  35.         if(list.size()>0){  
  36.             sm.registerListener(sel, (Sensor) list.get(0), SensorManager.SENSOR_DELAY_NORMAL);  
  37.         }else{  
  38.             Toast.makeText(getBaseContext(), "Error: No Accelerometer.", Toast.LENGTH_LONG).show();  
  39.         }  
  40.     }  
  41.   
  42.     @Override  
  43.     protected void onStop() {  
  44.         if(list.size()>0){  
  45.           sm.unregisterListener(sel);  
  46.         }  
  47.         super.onStop();  
  48.     }  
  49. }  


Output:

android sensor example output 1

Monday, 28 March 2016

Android Simple Graphics Example

The android.graphics.Canvas can be used to draw graphics in android. It provides methods to draw oval, rectangle, picture, text, line etc.
The android.graphics.Paint class is used with canvas to draw objects. It holds the information of color and style.
In this example, we are going to display 2D graphics in android.

activity_main.xml


File: activity_main.xml
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity" >  
  10.   
  11.     <TextView  
  12.         android:layout_width="wrap_content"  
  13.         android:layout_height="wrap_content"  
  14.         android:text="@string/hello_world" />  
  15.   
  16. </RelativeLayout>  

Activity class

File: MainActivity.java
  1. package com.example.simplegraphics;  
  2.   
  3. import android.os.Bundle;  
  4. import android.app.Activity;  
  5. import android.view.Menu;  
  6. import android.content.Context;  
  7. import android.graphics.Canvas;  
  8. import android.graphics.Color;  
  9. import android.graphics.Paint;  
  10. import android.view.View;  
  11.   
  12. public class MainActivity extends Activity {  
  13.   
  14.     DemoView demoview;  
  15.     /** Called when the activity is first created. */  
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         demoview = new DemoView(this);  
  20.         setContentView(demoview);  
  21.     }  
  22.   
  23.     private class DemoView extends View{  
  24.         public DemoView(Context context){  
  25.             super(context);  
  26.         }  
  27.   
  28.         @Override protected void onDraw(Canvas canvas) {  
  29.             super.onDraw(canvas);  
  30.   
  31.             // custom drawing code here  
  32.             Paint paint = new Paint();  
  33.             paint.setStyle(Paint.Style.FILL);  
  34.   
  35.             // make the entire canvas white  
  36.             paint.setColor(Color.WHITE);  
  37.             canvas.drawPaint(paint);  
  38.               
  39.             // draw blue circle with anti aliasing turned off  
  40.             paint.setAntiAlias(false);  
  41.             paint.setColor(Color.BLUE);  
  42.             canvas.drawCircle(202015, paint);  
  43.   
  44.             // draw green circle with anti aliasing turned on  
  45.             paint.setAntiAlias(true);  
  46.             paint.setColor(Color.GREEN);  
  47.             canvas.drawCircle(602015, paint);  
  48.   
  49.             // draw red rectangle with anti aliasing turned off  
  50.             paint.setAntiAlias(false);  
  51.             paint.setColor(Color.RED);  
  52.             canvas.drawRect(100520030, paint);  
  53.                            
  54.             // draw the rotated text  
  55.             canvas.rotate(-45);  
  56.                       
  57.             paint.setStyle(Paint.Style.FILL);  
  58.             canvas.drawText("Graphics Rotation"40180, paint);  
  59.               
  60.             //undo the rotate  
  61.             canvas.restore();  
  62.         }  
  63.     }  
  64.     @Override  
  65.     public boolean onCreateOptionsMenu(Menu menu) {  
  66.         // Inflate the menu; this adds items to the action bar if it is present.  
  67.         getMenuInflater().inflate(R.menu.main, menu);  
  68.         return true;  
  69.     }  
  70. }  


Output:

android simple graphics example output 1

Friday, 25 March 2016

Android Popup Menu Example

Android Popup Menu displays the menu below the anchor text if space is available otherwise above the anchor text. It disappears if you click outside the popup menu.
The android.widget.PopupMenu is the direct subclass of java.lang.Object class.

Android Popup Menu Example

Let's see how to create popup menu in android.

activity_main.xml

It contains only one button.
File: activity_main.xml
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity" >  
  10.   
  11.     <Button  
  12.         android:id="@+id/button1"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_alignParentLeft="true"  
  16.         android:layout_alignParentTop="true"  
  17.         android:layout_marginLeft="62dp"  
  18.         android:layout_marginTop="50dp"  
  19.         android:text="Show Popup" />  
  20.   
  21. </RelativeLayout>  

popup_menu.xml

It contains three items as show below. It is created inside the res/menu directory.
File: poupup_menu.xml
  1. <menu xmlns:androclass="http://schemas.android.com/apk/res/android" >  
  2.   
  3.     <item  
  4.         android:id="@+id/one"  
  5.         android:title="One"/>  
  6.       
  7.     <item  
  8.         android:id="@+id/two"  
  9.         android:title="Two"/>  
  10.         
  11.     <item  
  12.         android:id="@+id/three"  
  13.         android:title="Three"/>  
  14.           
  15. </menu>  

Activity class

It displays the popup menu on button click.
File: MainActivity.java
  1. package com.javatpoint.popupmenu;  
  2. import android.os.Bundle;  
  3. import android.app.Activity;  
  4. import android.view.Menu;  
  5. import android.view.MenuItem;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9. import android.widget.PopupMenu;  
  10. import android.widget.Toast;  
  11. public class MainActivity extends Activity {  
  12. Button button1;  
  13.            
  14.          @Override  
  15.          protected void onCreate(Bundle savedInstanceState) {  
  16.           super.onCreate(savedInstanceState);  
  17.           setContentView(R.layout.activity_main);  
  18.             
  19.           button1 = (Button) findViewById(R.id.button1);  
  20.           button1.setOnClickListener(new OnClickListener() {  
  21.            
  22.            @Override  
  23.            public void onClick(View v) {  
  24.             //Creating the instance of PopupMenu  
  25.             PopupMenu popup = new PopupMenu(MainActivity.this, button1);  
  26.             //Inflating the Popup using xml file  
  27.             popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());  
  28.            
  29.             //registering popup with OnMenuItemClickListener  
  30.             popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {  
  31.              public boolean onMenuItemClick(MenuItem item) {  
  32.               Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();  
  33.               return true;  
  34.              }  
  35.             });  
  36.   
  37.             popup.show();//showing popup menu  
  38.            }  
  39.           });//closing the setOnClickListener method  
  40.          }  
  41.     }  


Output:

android popup menu example output 1 android popup menu example output 2 android popup menu example output 3